How to make Paypal Payouts on a Node.Js environment - node.js

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.

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

Unsuccessfull payment transfer using Paypal with nodejs

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

Atlassian Connect-Express: JIRA REST API authentication within the JIRA plugin

i am using the atlassian-connect-express toolkit for creating Atlassian Connect based Add-ons with Node.js.
It provides Automatic JWT authentication of inbound requests as well as JWT signing for outbound requests back to the host.
The add-on is authenticated when i install it in the JIRA dashboard and return the following pay-load:
{ key: 'my-add-on',
clientKey: '*****',
publicKey: '********'
sharedSecret: '*****'
serverVersion: '100082',
pluginsVersion: '1.3.491',
baseUrl: 'https://myaccount.atlassian.net',
productType: 'jira',
description: 'Atlassian JIRA at https://myaccount.atlassian.net ',
eventType: 'installed' }
But i am not able to authenticate the JIRA Rest Api with the JWT token generated by the framework. It throws below error message.
404 '{"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}}'
below is the code when i send a GET request:
app.get('/getissue', addon.authenticate(), function(req, res){
var request = require('request');
request({
url: 'https://myaccount.atlassian.net/rest/api/2/issue/ABC-1',
method: 'GET',
}, function(error, response, body){
if(error){
console.log("error!");
}else{
console.log(response.statusCode, body);
}
});
res.render('getissue');
});
Below is the code for my app descriptor file:
{
"key": "my-add-on",
"name": "Ping Pong",
"description": "My very first add-on",
"vendor": {
"name": "Ping Pong",
"url": "https://www.example.com"
},
"baseUrl": "{{localBaseUrl}}",
"links": {
"self": "{{localBaseUrl}}/atlassian-connect.json",
"homepage": "{{localBaseUrl}}/atlassian-connect.json"
},
"authentication": {
"type": "jwt"
},
"lifecycle": {
"installed": "/installed"
},
"scopes": [
"READ",
"WRITE"
],
"modules": {
"generalPages": [
{
"key": "hello-world-page-jira",
"location": "system.top.navigation.bar",
"name": {
"value": "Hello World"
},
"url": "/hello-world",
"conditions": [{
"condition": "user_is_logged_in"
}]
},
{
"key": "getissue-jira",
"location": "system.top.navigation.bar",
"name": {
"value": "Get Issue"
},
"url": "/getissue",
"conditions": [{
"condition": "user_is_logged_in"
}]
}
]
}
}
I am pretty sure this is not the correct way i am doing, Either i should use OAuth. But i want to make the JWT method for authentication work here.
Got it working by checking in here Atlassian Connect for Node.js Express Docs
Within JIRA ADD-On Signed HTTP Requests works like below. GET and POST both.
GET:
app.get('/getissue', addon.authenticate(), function(req, res){
var httpClient = addon.httpClient(req);
httpClient.get('rest/api/2/issue/ABC-1',
function(err, resp, body) {
Response = JSON.parse(body);
if(err){
console.log(err);
}else {
console.log('Sucessful')
}
});
res.send(response);
});
POST:
var httpClient = addon.httpClient(req);
var postdata = {
"fields": {
"project":
{
"key": "MYW"
},
"summary": "My Story Name",
"description":"My Story Description",
"issuetype": {
"name": "Story"
}
}
}
httpClient.post({
url: '/rest/api/2/issue/' ,
headers: {
'X-Atlassian-Token': 'nocheck'
},
json: postdata
},function (err, httpResponse, body) {
if (err) {
return console.error('Error', err);
}
console.log('Response',+httpResponse)
});
You should be using global variable 'AP' that's initialized by JIRA along with your add-on execution. You may explore it with Chrome/Firefox Debug.
Have you tried calling ?
AP.request(..,...);
instead of "var request = require('request');"
You may set at the top of the script follwing to pass JS hinters and IDE validations:
/* global AP */
And when using AP the URL should look like:
url: /rest/api/2/issue/ABC-1
instead of:
url: https://myaccount.atlassian.net/rest/api/2/issue/ABC-1
My assumption is that ABC-1 issue and user credentials are verified and the user is able to access ABC-1 through JIRA UI.
Here is doc for ref.: https://developer.atlassian.com/cloud/jira/software/jsapi/request/

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