Cannot read property 'price' of undefined node - node.js

I am very new to the node js and I get the following error:
Cannot read property 'price' of undefined
I used this package: https://github.com/paypal/PayPal-node-SDK
Code works without line
amount = req.body.price;
But I need to post data
Here is the code:
var paypal = require('paypal-rest-sdk');
var express = require('express');
var app = express();
var amount = 5;
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'AV-UFzoT7Ccua-ubSQwUGx96qVq46ySVLTHGPyMiK4CA6HP2gHNW61-cvN__sIoyxQD-xX9zZupCNi',
'client_secret': 'ELAElfR-2pjX5PWJpW3iCW0Yd-WQ_0u2LUk3BDO6v6dcSHgYv1mJG3wg6_gWaR3IwGnVvrZ8pFoRz-'
});
app.post('/pay',(req,res)=>{
amount = req.body.price;
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:8000/success",
"cancel_url": "http://localhost:8000/pay"
},
"transactions": [{
"item_list": {
"items": [{
"name": "item",
"sku": "item",
"price": amount,
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": amount
},
"description": "This is the payment description."
}]
};
paypal.payment.create(create_payment_json, (error, payment)=> {
if (error) {
throw error;
} else {
console.log(payment);
for (let i = 0; i < payment.links.length; i++) {
if (payment.links[i].rel == 'approval_url') {
console.log(payment.links[i].href);
res.redirect(payment.links[i].href);
}
}
}
});
})
Thank you in advance
Also, this is how I post argument price in dart:
String _loadHTML() {
return '''
<html>
<body onload="document.f.submit();">
<form id="f" name="f" method="post" action="http://10.0.2.2:8000/pay">
<input type="hidden" name="ok" value="$price" />
</form>
</body>
</html>
''';
}

PayPal-node-SDK is deprecated and has no support, use Checkout-NodeJS-SDK for all new integrations

Related

How to transfer amount from a merchant account to individual account or personal account by EMAI ADDRESS in nodej Express in PayPal REST API ...?

I want to Transfer amount in PayPal with Only Email Address in order Form.
I am integrate the PayPal REST API in Nodejs and Express js but its not working. I want to send payment by register user PayPal email address, but its not working and give me ERROR Site can't reach.If any one know please help me to solve this problem ..
const paypal = require('paypal-rest-sdk');
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'XXXXXCLIENT_IDXXXXX',
'client_secret': 'XXXXXXXClientSECRETXXXXX'
});
app.post('/buy',(req,res)=>{
const {email}=req.body;
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:4000/success",
"cancel_url": "http://localhost:4000/cancel"
},
"payee": {
"email_address": email
},
"transactions": [{
"item_list": {
"items": [{
"name": "Redhock Bar Soap",
"sku": "001",
"price": "25.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "25.00"
},
"description": "Washing Bar soap"
}]
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
throw error;
} else {
for(let i = 0;i < payment.links.length;i++){
if(payment.links[i].rel === 'approval_url'){
res.redirect(payment.links[i].href);
}
}
}
});
console.log(req.body);
});
app.get('/success', (req, res) => {
const payerId = req.query.PayerID;
const paymentId = req.query.paymentId;
const execute_payment_json = {
"payer_id": payerId,
"transactions": [{
"amount": {
"currency": "USD",
"total": "25.00"
}
}]
};
// Obtains the transaction details from paypal
paypal.payment.execute(paymentId, execute_payment_json, function (error, payment) {
//When error occurs when due to non-existent transaction, throw an error else log the transaction details in the console then send a Success string reposponse to the user.
if (error) {
console.log(error.response);
throw error;
} else {
console.log(payment);
console.log(JSON.stringify(payment));
res.send(payment);
}
});
});
Please Help ....
Thank You

Unable to instantiate paypal sdk for multiple configurations

I have multiple paypal configurations ~15 users
[
...,
{ environment: "sandbox", accKey: "xxxxx", secretKey: "xxxxxxx" },
....
]
I want to instantiate a paypal for each user and return the object
The problem with nodejs is that paypal-rest-sdk export default object, unlike stripe that export stripe
// paypal
const paypal = require("paypal-rest-sdk")
paypal.config({
// config goes here
})
// stripe
const { Stripe } = require("stripe")
const stripe = new Stripe("secret key")
PROBLEM: If I will wrap paypal.configure in for-loop it will overwrite the old config.
You could wrap into your own module and export it, the key here is wrapping paypal into it own scope
// my-paypal-module.js
module.exports = config => {
const paypal = require("paypal-rest-sdk")
paypal.configure(config)
return paypal
}
// main-file.js
const Paypal = require('./my-paypal-module')
const paypal = new Paypal({ /* config */ })
Well I figured it out myself only.
While executing any request, there is optional second parameter in the functions, passing in new configuration object would override the old configuration set by .configure function.
This code has been taken from the official paypal-rest-sdk, original link here
var first_config = {
'mode': 'sandbox',
'client_id': '<FIRST_CLIENT_ID>',
'client_secret': '<FIRST_CLIENT_SECRET>'
};
var second_config = {
'mode': 'sandbox',
'client_id': '<SECOND_CLIENT_ID>',
'client_secret': '<SECOND_CLIENT_SECRET>'
};
//This sets up client id and secret globally
//to FIRST_CLIENT_ID and FIRST_CLIENT_SECRET
paypal.configure(first_config);
var create_payment_json = {
"intent": "authorize",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://return.url",
"cancel_url": "http://cancel.url"
},
"transactions": [{
"item_list": {
"items": [{
"name": "item",
"sku": "item",
"price": "1.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "1.00"
},
"description": "This is the payment description."
}]
};
// Overriding the default configuration with "second_config"
paypal.payment.create(create_payment_json, second_config, function (error, payment) {
if (error) {
throw error;
} else {
console.log("Create Payment Response");
console.log(payment);
}
});

Variable not refreshing on re-run. How do I pass down the variable?

I want to pass down the variables I create when hitting the /pay route to the /success_api route. Namely I need to pass down 'content', 'productSelectTotal', 'productSubTotal', and 'shipping'. When I trigger /pay the first time, it sets content which is then passed down when I am redirected to '/success', however on all subsequent requests, the value of content, productSelectTotal, productSubTotal, and shipping in the 'success_api' get function remain the same.
Any ideas how to make sure they are being refreshed every time the value of the variables in the parent function is updated?
router.post('/pay', (req, res, next) => {
fs.readFile('ProductDB.json', function (error, data) {
if (error) {
res.status(500).end()
} else {
const productsJson = JSON.parse(data)
console.log(req.body.items)
let content = [];
let productSelect = req.body.items.map(product => {
const itemJson = productsJson.find(function (i) {
return i.productName === product.productName
}).variations.find(function (i) {
return i.id === product.id
})
product.id != null ?
content.push({
// PUSH TO CONTENT HERE
"name": product.productName,
"sku": product.id,
"price": itemJson.variationPrice / 100,
"currency": "USD",
"quantity": product.qty
}) :
false
})
let tariffObj = {
"uk": 3.6,
"us": 11.6,
"rest-of-world": 11.6,
"eu": 8.2
}
let postalCategory = req.body.postalCategory
let postalTarrif = tariffObj[postalCategory]
let shipping = postalTarrif;
let productSelectPrices = content.map(item => item.price * item.quantity);
let productSelectTotal = productSelectPrices.reduce((acc, val) => acc + val, shipping).toFixed(2)
let productSubTotal = productSelectPrices.reduce((acc, val) => acc + val, 0).toFixed(2)
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": `http://localhost:3000/success`,
"cancel_url": `http://localhost:3000/cancel`
},
"transactions": [{
"item_list": {
"items": content
},
"amount": {
"currency": "USD",
"total": productSelectTotal,
"details": {
"subtotal": productSubTotal,
"shipping": shipping
}
},
"description": "first tea added to the store"
}]
}
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
throw error;
} else {
console.log("Create Payment Response");
console.log(payment);
for (let i = 0; i < payment.links.length; i++) {
if (payment.links[i].rel === "approval_url") {
let redirectURL = payment.links[i].href
res.json({
redirectUrl: redirectURL
})
}
}
}
});
/*
After creating the response the user is redirected to paypal, where they enter their payment information after which they are returned to the website where the / success_api call is made
*/
router.route('/success_api').get((req, res) => {
//CONTENT NOT UPDATED WITHIN THIS FUNCTION ON RE - RUNS
console.log('re routed')
const payerId = req.query.PayerID
const paymentId = req.query.paymentId
const execute_payment_json = {
"payer_id": payerId,
"transactions": [{
"item_list": {
"items": content
},
"amount": {
"currency": "USD",
"total": productSelectTotal,
"details": {
"subtotal": productSubTotal,
"shipping": shipping
}
}
}]
}
paypal.payment.execute(paymentId, execute_payment_json, function (error, payment) {
if (error) {
console.log(error.response);
res.json({
message: 'payment error'
})
} else {
console.log(JSON.stringify(payment));
res.json({
message: 'Payment Successful'
})
}
});
})
}
})
})

Web Crawling Using Node js

I am scraping medium.com. I am trying to display all the links present on the website.
var url="https://medium.com/";
request(url,function(error,response,html){
if(!error && response.statusCode==200){
var $=cheerio.load(html);
var json={content:"",link:""};
var jsonObjects=[];
var links=$('a');
//console.log(links);
$(links).each(function(i,link){
json.content=$(link).text();
json.link=$(link).attr('href');
jsonObjects.push(json);
});
}
fs.writeFile('Links.json',JSON.stringify(jsonObjects,null,4),function(err){
if(!err){
res.send("File written successfully!!!!")
}
})
})
When I am using this code, only one link is showing up again an again in Links.json file.
[
{
"content": "About",
"link": "https://about.medium.com"
},
{
"content": "About",
"link": "https://about.medium.com"
},
{
"content": "About",
"link": "https://about.medium.com"
},
{
"content": "About",
"link": "https://about.medium.com"
},
{
"content": "About",
"link": "https://about.medium.com"
},
{
"content": "About",
"link": "https://about.medium.com"
},
{
"content": "About",
"link": "https://about.medium.com"
},
{
I have tried everything but not getting even the links of main page of medium.com
Please help.
It's because you keep on editing the same object and pushing it into the array again and again.
var json={content:"",link:""};
should be inside your each loop.
var url="https://medium.com/";
request(url,function(error,response,html){
if(!error && response.statusCode==200){
var $=cheerio.load(html);
var jsonObjects=[];
var links=$('a');
//console.log(links);
$(links).each(function(i,link){
var content = $(link).text();
var link = $(link).attr('href');
jsonObjects.push({ content: content, link: link });
});
}
fs.writeFile('Links.json',JSON.stringify(jsonObjects,null,4),function(err){
if(!err){
res.send("File written successfully!!!!")
}
})
})

How to pass user product details from node.js application to paypal?

I have a button in my node.js application to buy the product whatever user wants. I want to know how to pass that product details (amount etc) to paypal so that user can pay me via paypal. Is there any in-built library?
Yes. You can use paypal-rest-sdk module.
https://github.com/paypal/rest-api-sdk-nodejs
Here's a sample code taken from here.
var paypal_api = require('paypal-rest-sdk');
var config_opts = {
'host': 'api.sandbox.paypal.com',
'port': '',
'client_id': 'EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM',
'client_secret': 'EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM'
};
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http:\/\/localhost\/test\/rest\/rest-api-sdk-php\/sample\/payments\/ExecutePayment.php?success=true",
"cancel_url": "http:\/\/localhost\/test\/rest\/rest-api-sdk-php\/sample\/payments\/ExecutePayment.php?success=false"
},
"transactions": [{
"amount": {
"currency": "USD",
"total": "1.00"
},
"description": "This is the payment description."
}]
};
paypal_api.payment.create(create_payment_json, config_opts, function (err, res) {
if (err) {
throw err;
}
if (res) {
console.log("Create Payment Response");
console.log(res);
}
});

Resources