I find it a little hard to understand what is the difference between the paymentId invoice_number and orderId.
This is a demo code in nodejs where I mark the fields.
Also is there a way to get the invoice_number of the item that the user want to pay for before the execuation of the payment.
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express();
const paypal = require('paypal-rest-sdk');
app.use(bodyParser.urlencoded());
app.use(cors())
app.use(bodyParser.json());
paypal.configure({
'mode': 'sandbox',
'client_id':
'client_secret':
});
//Is being called from client
app.post('/pay', (req, res, next) => {
createOrder(req.body.transactionId, paymentUrl => {
res.send({paymentUrl});
});
})
//Is called from paypal after user confirmed the payment
app.get('/process', (req, res, next) => {
//Can I get here the invoice_number in order to understand what the payment for before charging ?
var paymentId = req.query.paymentId;
var payerId = {
'payer_id': req.query.PayerID
};
var order;
paypal.payment.execute(paymentId, payerId, function (error, payment) {
if (error) {
console.error(JSON.stringify(error));
} else {
if (payment.state === 'approved' &&
payment.transactions &&
payment.transactions[0].related_resources &&
payment.transactions[0].related_resources[0].order) {
orderId = payment.transactions[0].related_resources[0].order.id;
//What is the difference between the invoice_number payment.id and orderId
res.redirect('http://localhost:4200/order/payment/success/' + orderId);
} else {
res.redirect('http://localhost:4200/order/payment/failure/' + orderId);
}
}
});
});
//Should be called only from paypal
app.post('/error', (req, res, next) => {
console.log("Error from paypal");
})
app.listen(3300, function () {
console.log('Example app listening on port 3000!')
})
function createOrder(data, callback) {
let invoice_number = Math.round(Math.random() * 1000000);
var payReq = JSON.stringify({
intent: 'order',
payer: {
payment_method: 'paypal'
},
redirect_urls: {
return_url: 'http://localhost:3300/process',
cancel_url: 'http://localhost:4200/order/payment/failure'
},
transactions: [{
amount: {
total: '30.03',
currency: 'USD'
},
description: 'This is the payment transaction description.',
invoice_number: invoice_number, //should be the transactionId
payment_options: {
allowed_payment_method: 'INSTANT_FUNDING_SOURCE'
}
}]
});
paypal.payment.create(payReq, function (error, payment) {
var links = {};
if (error) {
console.error(JSON.stringify(error));
} else {
// Capture HATEOAS links
payment.links.forEach(function (linkObj) {
links[linkObj.rel] = {
href: linkObj.href,
method: linkObj.method
};
})
if (links.hasOwnProperty('approval_url')) {
callback(links.approval_url.href);
} else {
console.error('no redirect URI present');
}
}
});
}
Related
const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
dotenv.config();
app.use(cors());
app.use(bodyParser.json());
const { Schema } = mongoose;
const userSchema = Schema({
imageUrl: { type: String },
description: { type: String },
title: { type: String },
price: { type: Number },
});
const Users = mongoose.model("users", userSchema);
app.get("/", (req, res) => {
res.send("started");
});
`get metod`
app.get("/users", (req, res) => {
Users.find({}, (err, docs) => {
if (!err) {
res.send(docs);
} else {
res.status(404).json({ message: err });
}
});
});
app.get("/users/:id", (req, res) => {
const { id } = req.params;
Users.findById(id, (err, doc) => {
if (!err) {
if (doc) {
res.send(doc);
}
} else {
res.status(404).json({ message: err });
}
});
});
`delete metod`
app.delete("/users/:id", (req, res) => {
const { id } = req.params;
Users.findByIdAndDelete(id, (err, doc) => {
if (!err) {
res.send("Succesfully deleted");
} else {
res.status(404).json({ message: err });
}
});
});
`post metod`
app.post("/users", (req, res) => {
const obj = {
imageUrl: req.body.imageUrl,
description: req.body.description,
title: req.body.title,
price: req.body.price,
};
console.log(obj);
let user = new Users(obj);
user.save();
res.send({ message: " Succesfully added" });
});
const PORT = process.env.PORT;
const url = process.env.URL.replace("<password>", process.env.PASSWORD);
mongoose.set("strictQuery", true);
mongoose.connect(url, (err) => {
if (!err) {
console.log("DB connected");
app.listen(PORT, () => {
console.log("Server start");
});
}
});
I'm trying to learn how exactly get post delete queries work
I'm trying to reduce the code here, but no matter what I do, small errors appear in the end. I have a json string, I want to pass it to POST method. But the 'execute', and 'executeMethod ' are throwing error as below:
"The method execute(HttpUriRequest) in the type HttpClient is not applicable for the arguments (PostMethod)". i have included the depencencies.
Hi iam new to Vue and trying too build a MEVN application. What iam trying to do is when user adds item in cart it should store one document in mongoDB and if user adds more of same item only the price and quantity for the document should increase and not create new document.
Here is code for client when user adds item in cart,iam using Vue3:
async addToCart(state, product) {
console.log(state);
let dbProducts = await axios
.get(`http://localhost:1337/items/`)
.then((res) => res.data)
.catch((error) => console.log(error));
let item = dbProducts.find((i) => i.id === product.id);
console.log(item);
console.log('addTOcart');
if (item) {
console.log('put request');
item.quantity++;
console.log('quantity', item.quantity);
axios
//.put(`http://localhost:1337/items/${uniqueId}`, item)
.put(`http://localhost:1337/items/`, item)
.then((res) => {
console.log(res.data);
alert(res.data);
})
.catch((error) => console.log(error));
} else {
product = { ...product, quantity: 1 };
state.cart.push(product);
axios.post('http://localhost:1337/items', {
id: product.id,
title: product.title,
price: product.price,
quantity: product.quantity,
shortDesc: product.shortDesc,
category: product.category,
longDesc: product.longDesc,
imgFile: product.imgFile,
serial: product.serial,
});
}
},
And here is code for the server, iam using express js:
const express = require('express');
const app = express();
const Items = require('./Items');
const connection = require('./connection');
const Port = process.env.Port || 1337;
const cors = require('cors');
app.use(cors());
connection();
app.use(express.json());
app.post('/items', (req, res) => {
const data = new Items(req.body);
data
.save()
.then((Items) => {
console.log('item saved', Items);
res.json({ succcess: true, Items });
})
.catch((err) => {
console.log(err);
});
});
app.get('/items', async (req, res) => {
Items.find({}, (err, items) => {
res.json(items);
});
});
app.put('/items', function (req, res) {
console.log(req.body);
//Items.updateOne({ _id: req.body._id }, req.body);
Items.findOneAndUpdate({ _id: req.body._id }, req.body);
// Items.findOne({ _id: req.body._id });
});
app.listen(Port, () => {
console.log(`App running on port ${Port}`);
});
As #HeikoTheißen suggested, you should handle the logic of the operation on the server, using a single POST request:
const express = require('express');
const app = express();
const Items = require('./Items');
const connection = require('./connection');
const Port = process.env.Port || 1337;
const cors = require('cors');
app.use(cors());
connection();
app.use(express.json());
app.post('/items', async (req, res) => {
try {
let item = await Items.findById(req.body.id);
if (!item) {
item = await Items.create(req.body);
} else {
item.quantity++;
await item.save();
}
res.json({ succcess: true, item });
} catch (err) {
res.json({ succcess: false });
}
});
app.listen(Port, () => {
console.log(`App running on port ${Port}`);
});
You should simplify your client code as:
async function addToCart(state, product) {
try {
const { data } = await axios.post('http://localhost:1337/items', product);
// Add new product to card if necessary
if (!state.cart.some((p) => p.id === data.item.id)) {
state.cart.push(data.item);
}
} catch (err) {
console.log(err);
}
}
When I send this patch request with axios, the backend receives the data, but response.data comes back empty. Please and thanks!
// ACTION IN VUEX STORE
async updateMe({ commit }, payload) {
let id = localStorage.getItem('userId');
let user = { name: payload.name, email: payload.email, id: id };
try {
const response = await axios.patch(
`http://localhost:3000/api/v1/users/updateMe`,
user
);
commit('setUpdatedUser', response.data);
} catch (err) {
console.log(err);
}
}
// CONTROLLER
exports.updateMe = catchAsync(async (req, res, next) => {
const updatedUser = await User.findByIdAndUpdate(
req.body.id,
{
name: req.body.name,
email: req.body.email
},
{ new: true, runValidators: true }
);
res.status(204).json({ data: updatedUser });
});
204 is a No Content response code.
This is What I am getting on the Console of Chrome
I am Using Vue.js (vue-resource) and Express with PostgreSQL
I have a list on the server Side which I want to get on the items (and display on the Webpage)
but I am not getting anything
Following is the Vue file code
<script>
export default {
name: 'order',
data () {
return {
orderOpt: 'Deliver',
orderType: 'State',
items: []
}
},
created () {
this.$http.get('localhost:3000/items').then(response => {
this.items = response.body
}, response => {
setTimeout(function () {
alert('The Server is not Running/items')
}, 10000)
})
},
computed: {
total () {
let sum = 0
for (let i = 0; i < this.items.length; i++) {
sum += parseInt(this.items[i].quantity)
}
return sum
}
},
methods: {
itemsUpdate (value) {
this.items.forEach((item, i) => {
console.log(value)
item.inStock -= item.quantity
item.quantity = 0
})
this.post(this.items)
},
post (Data) {
this.$http.post('localhost:3000', Data)
}
},
watch: {
}
}
</script>
As I am using Express on the server side
This following code is present in the index.js
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors')
const app = express();
const Joi = require('joi');
const Data = require('./Data.json');
const { Pool, Client } = require('pg');
const pool = require('./db');
const port = process.env.USER || 3000;
//middleware
app.use(express.json());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(cors())
//DATA
const getItems = (req, res) => {
pool.query('SELECT * FROM data', (err, results) => {
if (err) {
throw err
}
res.status(200).json(results.rows)
})
}
app.listen(port, function () {
console.log(`Server Starts on ${port}`);
});
//Requests
app.get('/', (req, res) => {
res.json({Welcome: 'API Created'})
})
app.get('/item', async (req, res) => {
res.status(200).send(Data);
});
app.get('/items', getItems)
app.post('/items', (req, res) => {
try {
const items = [req.body.name, req.body.inStock, req.body.quantity];
const newItems = pool.query(
"INSERT INTO data VALUES ($1, $2, $3) RETURNING *",
items
).then(()=> {
console.log(newItems);
});
} catch (e) {
console.error(e);
}
pool.end();
});
I am trying to use passportjs with facebook and on sails js.in the middleware, this is my implementation
var verifyHandler = function (token, tokenSecret, profile, done) {
process.nextTick(function () {
//check if the user exist or not
var uid=profile.id;
User.findOne({uid:profile.id}).done(function(err,user){
if(user)
{
console.log('found');
//done(null,user);
}
else
{
console.log('user does not exists');
}
});
};
The weird thing is that it is not able to search through the model.Where Am I doing it wrongly?
I have finally figured it out and I hope it will assist anyone having the same issue with MySQL.
1. Within your user model, the uid datatype should be a STRING not an INTEGER.Please make sure you have effect the same changes on the database table structure to VARCHAR.
2.Change middleware.js verifyHandler to this(omitting parseInt)
var passport = require('passport')
, GitHubStrategy = require('passport-github').Strategy
, FacebookStrategy = require('passport-facebook').Strategy
, GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var verifyHandler = function (token, tokenSecret, profile, done) {
process.nextTick(function () {
User.findOne({uid: profile.id}).done(function (err, user) {
if (user) {
return done(null, user);
} else {
var data = {
provider: profile.provider,
uid: profile.id,
name: profile.displayName
};
if(profile.emails && profile.emails[0] && profile.emails[0].value) {
data.email = profile.emails[0].value;
}
if(profile.name && profile.name.givenName) {
data.firstname = profile.name.givenName;
}
if(profile.name && profile.name.familyName) {
data.lastname = profile.name.familyName;
}
User.create(data).done(function (err, user) {
return done(err, user);
});
}
});
});
};
passport.serializeUser(function (user, done) {
done(null, user.uid);
});
passport.deserializeUser(function (uid, done) {
User.findOne({uid:uid}).done(function (err, user) {
done(err, user)
});
});
module.exports = {
// Init custom express middleware
express: {
customMiddleware: function (app) {
passport.use(new FacebookStrategy({
clientID: "****",
clientSecret: "********",
callbackURL: "http://localhost:1337/auth/facebook/callback"
},
verifyHandler
));
app.use(passport.initialize());
app.use(passport.session());
}
}
};
Hope this helps someone out.Cheers!