Node + Express: How to add Paypal payment

Updated: January 8, 2024 By: Guest Contributor Post a comment

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.