Unsuccessfull payment transfer using Paypal with nodejs - node.js

I am trying to implement the Paypal gateway method in nodejs. I am successful redirecting to paypal from my nodejs and when I click on pay I get "Error": "Response Status : 400", with an unsuccessful payment.
My API and its response are given below in detail.
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'ATXsRtel_YoAQHVIwP4Z_bmX3VkL1n1N_fJ6FH2os0GynozBJo-Oler8wFVvXzoPpNwbfCAYFvCL76Ke',
'client_secret': 'EAwUmjDRpC-fqz_Fcs262MKrdMDltXJnWiA-
N6gURWcJq1N9IpwzISfcCMLNHzXFJ_38YLQXG3jtUK8a'
});
Post Api for req.body and get the url back
Router.post('/Pay',(req,res)=>{
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:7070/PayPal/PaymentSuccess",
"cancel_url": "http://localhost:7070/PayPal/PaymentCancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "ball",
"sku": "001",
"price": "25.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "25.00"
},
"description": "Testing Product"
}]
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
res.json({
Message:'Un Approved',
Error:error.message
})
} else {
payment.links.map(_AllLinks=>{
if(_AllLinks.rel === 'approval_url'){
res.json({
Message:'Approved',
Url:_AllLinks.href
})
}
})
}
});
})
Rout to get payerID
Router.get('/PaymentSuccess',(req,res)=>{
let payerId = req.query.PayerID;
let paymentId = req.query.paymentId;
console.log({
payerId:payerId,
paymentId:paymentId
});
let execute_payment_json = {
"payer_id" : payerId,
"transaction" : [{
"amount":{
"currency":"USD",
"total":"25.00"
}
}]
}
paypal.payment.execute(paymentId,execute_payment_json, function(error,payment){
if(error){
res.json({
Error:error.message,
Message:error
})
}else {
res.json({
Result:payment
})
}
})
})
Router.get('/PaymentCancel',(req,res)=>{
res.json({
Result:'Cancelled'
})
})
The response i get and my payment got unsuccessful.
// 20210504063330
// http://localhost:7070/PayPal/PaymentSuccess?paymentId=PAYID-MCIKIRQ60G27157PA787072M&token=EC-
9EU01414K39004833&PayerID=GFYGLAXW36YPW
{
"Error": "Response Status : 400",
"Message": {
"response": {
"name": "VALIDATION_ERROR",
"message": "Invalid request - see details",
"debug_id": "cfeb4eab621c7",
"details": [
{
"field": "/transaction",
"location": "body",
"issue": "MALFORMED_REQUEST_JSON"
}
],
"links": [
],
"httpStatusCode": 400
},
"httpStatusCode": 400
}
}

The v1/payments REST API is deprecated. Use the current v2/checkout/orders API instead.
The best integration uses no redirects, and keeps your site loaded in the background with an in-context approval.
Make two routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return only JSON data (no HTML or text). The latter one should (on success) store the payment details in your database before it does the return (particularly purchase_units[0].payments.captures[0].id, the PayPal transaction ID)
Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

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

How to make Paypal Payouts on a Node.Js environment

I am trying to execute a PayPal Payout on Node.Js environment, but I can't seem to wrap my head around it.
Could you please help me get the parameters right, and maybe where I should re-organize the code, and eventually start heading in the right direction?
Thank you all in advance.
var PAYPAL_API = "https://api-m.sandbox.paypal.com";
app.post("/my-api/execute-payment/", function (req, res) {
// 2. Get the payment ID and the payer ID from the request body.
var paymentID = req.body.paymentID;
var payerID = req.body.payerID;
let requestBody = {
"sender_batch_header": {
"sender_batch_id": "Payouts_2018_100007",
"email_subject": "You have a payout!",
"email_message": "You have received a payout! Thanks for using our service!",
},
"items": [
{
"recipient_type": "EMAIL",
"amount": {
"value": "9.87",
"currency": "USD",
},
"note": "Thanks for your patronage!",
"sender_item_id": "201403140001",
"receiver": "rev_buyer#personal.example.com",
"alternate_notification_method": {
"phone": {
"country_code": "91",
"national_number": "9999988888",
},
},
"notification_language": "fr-FR",
},
{
"recipient_type": "PAYPAL_ID",
"amount": {
"value": "5.32",
"currency": "USD",
},
"note": "Thanks for your patronage!",
"sender_item_id": "201403140003",
"receiver": "xXXXXXX-50mQSYBJpg_OWguVkwYYYYYYY-ZAFupw-aaaaa-nnnnnnn",
},
],
};
request.post(
PAYPAL_API + "/v1/payments/payouts",
{
auth: {
user: CLIENT,
pass: SECRET,
},
requestBody,
json: true,
},
function (err, response) {
if (err) {
console.error(err);
return res.sendStatus(500);
}
// 4. Return a success response to the client
res.json({
status: "success",
});
}
);
});
Have you tried the Payouts-NodeJS-SDK ?
The main issue with the custom code above is that you aren't first requesting an OAuth 2.0 access_token, and then using the access_token for your REST API call.
See the documentation: https://developer.paypal.com/docs/api/overview/#get-an-access-token
The SDK abstracts this step for 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);
}
});

Paypal payout getting Response Status : 503 when using paypal-rest-sdk in Node js

I am using the npm paypal-rest-sdk in that calling the payout api. I am sending the body like email and amount for that.When I am calling that api/payments it gives the error like Response Status : 503.
Here is my code:
app.post('/api/payment',function(req,res){
paypal.configure({
'mode':"live", //sandbox or live
'client_id': "*******",
'client_secret': "*******"
});
var sender_batch_id = Math.random().toString(36).substring(9);
var create_payout_json = {
"sender_batch_header": {
"sender_batch_id": sender_batch_id,
"email_subject": "You have a payment"
},
"items": [
{
"recipient_type": "EMAIL",
"amount": {
"value": req.body.amount,
"currency": "USD"
},
"receiver": req.body.email,
"note": "Thank you.",
"sender_item_id": Date.now()
}
]
};
var sync_mode = 'true';
paypal.payout.create(create_payout_json,sync_mode, function (error, payout) {
if (error) {
console.log(error.response);
throw error;
} else {
console.log("Create Payout Response");
console.log(payout);
}
});
})
I am getting the error response like 503.Please help me to solve this problem.Thanks

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