Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Node.js Express Paypal Checkout REST API SDK Payment Gateway Integration Full Example

Posted on January 13, 2023

 

 

Welcome folks today in this blog post we will be integrating paypal checkout rest api sdk payment gateway integration in browser using javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to initiate a new node.js project using the below command as shown below

 

 

npm init -y

 

 

After that you need to install the below libraries using the below command as shown below

 

 

npm i express

 

 

npm i paypal-rest-sdk

 

 

After that you need to make an index.js file and copy paste the following code

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const express = require("express");
const paypal = require("paypal-rest-sdk");
 
let PORT = 5000
 
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}`));

 

 

As you can see we are importing the express and paypal-rest-sdk library and also you need to replace the clientid and client_secret from the paypal dashboard (sandbox) as shown below

 

 

 

 

 

 

And now we need to load the index.html file and copy paste the following code

 

 

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!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>

 

 

 

 

And now we need to write the post request when we click the buy button inside the index.html file so now you need to go to index.js file and copy paste the below code

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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);
        }
      }
    }
  });
});

 

 

As you can see we have initialized the redirect_url for success and failure routes. And then we are using the payal.create() to create the payment using the paypal rest sdk. And here we are passing the data of json. And then we are redirecting the user to the /success route and to /failure if any error takes place.

 

 

And now we need to write the routes for the success and failure of the payment as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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'));

 

 

FULL SOURCE CODE

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const express = require("express");
const paypal = require("paypal-rest-sdk");
 
let PORT = 5000
 
paypal.configure({
  mode: "sandbox", //sandbox or live
  client_id:
    "AdjBfPk2FzyAZwNovZbcNfV4oZY11r-EDRQiwt2vdTh7b7YOVP3GpCNj8Ap70Mjym9-WG-HebchXdH5R",
  client_secret:
    "EBARwS_kvk7BQXXvParxN2NNtJ1WLGNJO2ys3FAvV3YU6xzm75ldNQcTwVheXjdkLwXzwqblFRNrJzkO",
});
 
const app = express();
 
app.get("/", (req, res) => res.sendFile(__dirname + "/index.html"));
 
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);
        }
      }
    }
  });
});
 
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'));
 
app.listen(PORT, () => console.log(`Server Started on ${PORT}`));

 

Recent Posts

  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Android Java Project to Download Random Image From Unsplash Using OkHttp & Picasso Library & Display it
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme