Integration of paypal payment gateway with node.js with errors faced and solutions

12-02-2019    Hari Kondlapudi    Views 29

INTRODUCTION:

First of all, we need to create some basic sandbox accounts(business and personal accounts) to check the functionality of PayPal integration. (note: sandbox accounts use USD currency only). If suppose any other currency is used there will be an error and we will discuss it in the later stages of this code.

Now I will explain the flow of transfer of amount through the test accounts created by using the sandbox.
U can create the sandbox accounts through this link “https://developer.paypal.com
Click on login into the dashboard. If u don't have an account just signup and create an account and login into that.
After logging in goto accounts seen at the side menu bar and then click on create an account you will see a popup like this below.
 



Click on create a custom account 
Create a business and personal accounts individually as shown below.

Now let’s go into the code 
First import the packages required for this
Then we have to configure the clientId and client secret and which mode we are using is it the live or for sandbox accounts.

var paypal=require('paypal-rest-sdk')
paypal.configure({
'mode':sandbox',//sandbox or live 
'client_id:'AV0b-9eLbx2uwy4-FJuegr0QVHbMMHs98qM1X9Hr9dem12_x_U7c 
'client_secret:'EPyVAnf56zh7fta50m6VF3Z7E8XngZe2lxV8Ze2lxv8ZQwqkb6gHY2Z 
});

Give the id and secret that u generated at the time of the creation of sandbox accounts and give the credentials as if to which mode it has been.

There will be an error stating like 
⇒ { Error: Response Status : 401
    at IncomingMessage. (/var/www/html/crashcart/server/node_modules/paypal-rest-sdk/lib/client.js:130:23)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1129:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  response:
   { error: 'invalid_client',
     error_description: 'Client Authentication failed',
     httpStatusCode: 401 },
  httpStatusCode: 401 }
If this error occur in console then jst come to the code and check whether the given mode and credentials are same .

CREATING A REQUEST OBJECT :
Now we have to create a req obj to send into the PayPal create callback


var payReq = JSON.stringify({
   'intent': 'sale',
   'redirect_urls': {
     'return_url': 'http://localhost:3001/api/payments/execute/t',
     'cancel_url': 'http://localhost:3000/payments/cancel'
   },
   'payer': {
     'payment_method': 'paypal'
   },
   'transactions': [{
     'amount': {
       'total': "25",
       'currency': "USD"
     },
     'description': 'This is the  PayPal payment transaction .'
   }]
 });
 paypal.payment.create(payReq, function (error, payment) {
   console.log("payment", payment)
   if (error) {
     req.err = error.response.message
     return res.json(respUtil.getErrorResponsepayPAl(req));
   } else {
     for (let i = 0; i < payment.links.length; i++) {
       if (payment.links[i].rel === 'approval_url') {
         res.redirect(payment.links[i].href);
       }
     }
   }
});

As I discussed at the starting that sandbox accounts only accepts USD . so the currency should be USD

Check the payment method is either PayPal or not if it is not PayPal then there will be an error like

⇒{ Error: Response Status : 400
    at IncomingMessage. (/var/www/html/crashcart/server/node_modules/paypal-rest-sdk/lib/client.js:130:23)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1129:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  response:
   { name: 'VALIDATION_ERROR',
     message: 'Invalid request - see details',
     debug_id: '52ae8389112ec',
     information_link: 'https://developer.paypal.com/docs/api/payments/#errors',
     details: [ [Object] ],
     httpStatusCode: 400 },
  httpStatusCode: 400 }
This error may occur either for that reason or may be for not sending the appropriate data into the fields that we are given for that object
 Give the succesurl as for which function u have to redirect for executing the paypal amount as the same give the cancel url.

From that, we have to redirect to the PayPal URL that has been sent through the payment.

 for (let i = 0; i < payment.links.length; i++) {
       if (payment.links[i].rel === 'approval_url') {
         res.redirect(payment.links[i].href);
       }
     }


EXECUTE THE PAYPAL AMOUNT:

const payerId = req.query.PayerID;
 const paymentId = req.query.paymentId;
 const executePayment = {
   "payer_id": payerId,
   "transactions": [{
     "amount": {
       'total': "25",
       'currency': "USD"
     }
   }]
 };
 paypal.payment.execute(paymentId, executePayment, function (error, payment) {
   if (error) {
     req.err = error.response.message
     return res.json(respUtil.getErrorResponsepayPAl(req));
   } else {
     console.log(JSON.stringify(payment));
     req.i18nKey = 'transactionSuccess'
     return res.json(respUtil.successResponse(req));
   }
});

FOR LIVE ACCOUNTS:

Change the mode to live and give the credentials of live may be either statically or dynamically .but the id and secret should match the model.






 

Add Comments

Submit Comments

More Blogs


What is Trade Finance Transaction?

Blockchain Technology In Trade Finance Transactions

Hari Kondlapudi        Views 376
block-chain-transform-your-business

BLOCKCHAIN TO TRANSFORM YOUR BUSINESS

Hari Kondlapudi        Views 345
block-chain-transform-your-business

LOCALIZATION WITH REACT

Hari Kondlapudi        Views 68

Contact Us

Address:

Do Systems Inc,
433 Plaza Real, Suite 275
Boca Raton, FL 33432 

Email: sales@dosystems.com
 
Copyright © Do Systems Inc. All rights reserved.