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);
}
});
Related
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
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
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.
I am having a problem debugging my paypal integration with Node and the rest api https://github.com/paypal/rest-api-sdk-nodejs
I created a Paypal account
I got the creditials for the app
I created an app and set a password for a user
I log into the sandbox with that user
I don`t see any transaction history
The code snippet is as follows :
var config_opts = {
'host': 'api.sandbox.paypal.com',
'port': '',
'client_id': 'my id',
'client_secret': 'my secret'
};
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000",
"cancel_url": "http://localhost:3000"
},
"transactions": [{
"amount": {
"currency": "USD",
"total": "10.00"
},
"description": "This is the payment description."
}]
};
paypal_sdk.payment.create(create_payment_json, config_opts, function (err, res) {
if (err) {
console.log( err );
}
if (res) {
console.log("Create Payment Response");
console.log(res);
}
});
The response I get is as follows:
{ id: 'PAY-55J119327J2030636KLXMVJI',
create_time: '2014-02-02T22:45:57Z',
update_time: '2014-02-02T22:45:57Z',
state: 'created',
intent: 'sale',
payer:
{ payment_method: 'paypal',
payer_info: { shipping_address: {} } },
transactions:
[ { amount: [Object],
description: 'This is the payment description.' } ],
links:
[ { href: 'https://api.sandbox.paypal.com/v1/payments/payment/PAY- 55J119327J2030636KLXMVJI',
rel: 'self',
method: 'GET' },
{ href: 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-90D3081342725343U',
rel: 'approval_url',
method: 'REDIRECT' },
{ href: 'https://api.sandbox.paypal.com/v1/payments/payment/PAY-55J119327J2030636KLXMVJI/execute',
rel: 'execute',
method: 'POST' } ] }
I am wondering if there is some additional step in authenticating that I am missing ?
First, you have to declare a proper return_url (not just localhost:3000). I suggest that you change your return_url to "http://localhost:3000/success". Then, insert this one above your payment POST METHOD:
app.get('/success', function(req, res) {
var paymentId = req.query.paymentId;
var payerId = { 'payer_id': req.query.PayerID };
paypal.payment.execute(paymentId, payerId, function(error, payment){
if(error){
console.error(error);
} else {
if (payment.state === 'approved'){
res.send('payment completed successfully');
console.log(payment);
} else {
res.send('payment not successful');
}
}
});
});
This GET method will execute your payment. But, before it can execute, you must redirect first your server's response to paypal sandbox for payment confirmation.
Edit the content of your paypal_sdk.payment.create() function like this one:
paypal_sdk.payment.create(create_payment_json, config_opts, function (err, res) {
if (err) {
console.log( err );
}
else {
console.log("Create Payment Response");
console.log(res);
//you forgot to redirect your response to paypal sandbox
var redirectUrl;
for(var i=0; i < payment.links.length; i++) {
var link = payment.links[i];
if (link.method === 'REDIRECT') {
redirectUrl = link.href;
}
}
res.redirect(redirectUrl);
}
});
I hope this can help (especially to those who are still looking for answers)
You must go to Dashboard -> Rest API transactions.
See the attached screenshot:
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);
}
});