Node.js Express Paypal REST API SDK Payment Gateway Integration Full Example with Source Code 2020

Node.js Express Paypal REST API SDK Payment Gateway Integration Full Example with Source Code 2020

 

Welcome folks today in this blog post we will be integrating the paypal payment gateway inside our node.js express application using the paypal rest api sdk. All the source code of the application is given below. A step by step youtube video is also shown below.

 

 

 

 

 

Live Demo

 

 

You can check out the Live Demo of the App here

 

 

Get Started

 

 

In order to get started you need to install these dependencies inside your node.js project which are listed below

 

npm i express

 

npm i nodemon

 

npm i paypal-rest-sdk

 

Install all these dependencies inside your node.js project and create your index.js file for your node.js project ad copy paste the below code to it

 

 

const express = require('express');
const paypal = require('paypal-rest-sdk');

paypal.configure({
  'mode': 'sandbox', //sandbox or live
  'client_id': '####yourclientid######',
  'client_secret': '####yourclientsecret#####'
});

const app = express();

app.get('/', (req, res) => res.sendFile(__dirname + "/index.html"));


app.listen(PORT, () => console.log(`Server Started on ${PORT}`));

 

 

 

Here in this block of code we need to replace the client-id and the client-secret of the paypal like this

 

 

 

 

 

Just replace your client-id and client-secret from your paypal dashboard inside the application. But in order to get this you need to create a business account on paypal. We can create fake sandbox accounts on paypal

READ  Build a jQuery Full Screen Video Background in Browser Using HTML5 CSS3 and Javascript Full Project For Beginners

 

Go to Paypal Developer website and create a sandbox account like this

 

 

 

 

 

 

 

 

 

 

 

 

 

 

index.html

 

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>PayPal Node App</title>
</head>
<body>
  <h1>Coding Shiksha App Store</h1>
  <h2>Buy For $25</h2>
  <form action="/pay" method="post">
    <input type="submit" value="Buy">
  </form>
</body>
</html>

 

 

 

 

 

 

So we have the buy button here inside the app. When we click this button a post request will be made to the route /pay so we need to make this route like this

 

 

app.post('/pay', (req, res) => {
  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": [{
                "name": "Red Sox Hat",
                "sku": "001",
                "price": "25.00",
                "currency": "USD",
                "quantity": 1
            }]
        },
        "amount": {
            "currency": "USD",
            "total": "25.00"
        },
        "description": "Hat for the best team ever"
    }]
};

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);
        }
      }
  }
});

});

 

 

 

Basically here in this block of code we have made the json object containing all the properties which is required for the transaction so now we need to make the routes for the success callback and also the cancel callback events like this

READ  Javascript PDFMake Library to Export jQuery HTML DataTable to CSV,Excel and PDF Documents in Browser Full Project For Beginners

 

 

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"
        }
    }]
  };

  paypal.payment.execute(paymentId, execute_payment_json, function (error, payment) {
    if (error) {
        console.log(error.response);
        throw error;
    } else {
        console.log(JSON.stringify(payment));
        res.send('Success');
    }
});
});

 

 

 

app.get('/cancel', (req, res) => res.send('Cancelled'));

 

 

 

 

 

 

 

 

 

 

 

DOWNLOAD SOURCE CODE

 

 

Leave a Reply