Sling Academy
Home/Node.js/Node + Express: How to add Paypal payment

Node + Express: How to add Paypal payment

Last updated: January 08, 2024

Overview

Integrating PayPal into a Node.js and Express application enhances commercial functionality allowing for seamless financial transactions. This tutorial methodically guides through the process from setup to successful payment processing.

Getting Started

Before jumping into code, ensure that you have Node.js and npm installed. You will also need a PayPal developer account to access the PayPal API. After setting up your developer account, create an app to obtain the API credentials you will need for the integration.

To start, initialize a new Node.js project, if you haven’t already:

mkdir paypal-integration
 cd paypal-integration
 npm init -y

Next, install Express and the PayPal REST SDK:

npm install express paypal-rest-sdk --save

Basic Server Setup

Create your ‘app.js’ which will be the entry point of your Node.js application. Start with the basic Express server setup:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
 res.send('PayPal Integration Example');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
 console.log(`Server started on PORT ${PORT}`);
});

Configuring PayPal SDK

Now, configure the PayPal SDK with your credentials obtained from your PayPal app:

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

paypal.configure({
 'mode': 'sandbox', //sandbox or live
 'client_id': 'YOUR_CLIENT_ID',
 'client_secret': 'YOUR_CLIENT_SECRET'
});

Creating a Payment

To create a payment, define a payment object and pass it to the PayPal API:

const create_payment_json = {
 "intent": "sale",
 "payer": {
   "payment_method": "paypal"
 },
 "redirect_urls": {
   "return_url": "http://",
   "cancel_url": "http://"
 },
 "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."
 }]
};

app.post('/pay', (req, res) => {
 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);
       }
     }
   }
 });
});

Executing a Payment

Upon the user’s approval, they will be redirected to the return URL where you will execute the payment:

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": "1.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('Payment Successful');
   }
 });
});

Conclusion

With this comprehensive tutorial, you are now able to integrate PayPal payments within your Node.js and Express applications, offering secure and convenient transactions to your users.

Next Article: NodeJS: Link to static assets (JS, CSS) in Pug templates

Previous Article: How to Implement a Shopping Cart in ExpressJS

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates