In today’s digital era, integrating payment gateways into web applications is essential for conducting online transactions securely. PayPal remains one of the most popular choices for processing payments worldwide due to its reliability and extensive features. In this guide, we’ll walk through integrating the PayPal payment gateway into a web application using Node.js for the backend and React.js for the front end.

Prerequisites

Before we begin, make sure you have the following prerequisites installed on your system:

  • Node.js and npm (Node Package Manager)
  • React.js
  • An active PayPal developer account (for obtaining API credentials)

Setting Up the Backend (Node.js):

Create a new directory for your project and navigate into it:

mkdir paypal-payment-integration
cd paypal-payment-integration
JavaScript

Initialize a new Node.js project:

npm init -y
JavaScript

Install necessary dependencies:

npm install express paypal-rest-sdk cors
JavaScript

Create a new file named server.js and add the following code:

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

const app = express();
app.use(cors());

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

// Define routes
// Add routes for payment initiation, success, and failure

app.get('/payment', async (req, res) => {

    let data
    try {

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


        await paypal.payment.create(create_payment_json, function (error, payment) {
            if (error) {
                throw error;
            } else {
                console.log("Create Payment Response");
                // console.log(payment);
                data = payment;
                res.json(data);

            }
        });


    } catch (error) {
        console.log(error);
    }
})



app.get('/success', async (req, res) => {

    try {

        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)
                return res.redirect("http://localhost:5173/failed");
            } else {
                console.log("Execute Payment Response");
                // console.log(payment);
                const response = JSON.stringify(payment);
                const parsedResponse = JSON.parse(response);

                const transactions = parsedResponse.transactions[0];

                console.log("transactions", transactions);

                return res.redirect("http://localhost:5173/success");
            }
        })


    } catch (error) {
        console.log(error);
    }

})


app.get('/failed', async (req, res) => {

    return res.redirect("http://localhost:5173/failed");
})

// Start the server
app.listen(8000, () => {

    console.log('Server is running on port 8000');
});
JavaScript

Replace 'YOUR_CLIENT_ID' and 'YOUR_CLIENT_SECRET' with your PayPal API credentials obtained from the developer dashboard.

Setting Up the Frontend (React.js):

Create a new React app using Create React App:

mkdir client
npm create vite@latest
JavaScript

Install Axios for making HTTP requests:

npm install axios
JavaScript

Replace the contents of src/App.js with the following code:

import { useState } from 'react';
import axios from 'axios';

function App() {
  const handlePayment = async (e) => {
    e.preventDefault();

    try {
      const res = await axios.get('http://localhost:8000/payment');

      if (res && res.data) {
        window.location.href = res.data.links[1].href;
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <>
      <button onClick={handlePayment}>Proceed to Payment</button>
    </>
  );
}

export default App;
JavaScript

Integration Steps:

  1. Setting up a PayPal Sandbox Account: If you haven’t already, sign up for a PayPal developer account and create sandbox API credentials for testing.
  2. Backend Configuration: Replace placeholder values in the Node.js server file with your PayPal API credentials.
  3. Frontend Integration: Create a button in your React app that triggers a payment request to the server when clicked.
  4. Handling Payment Requests: Implement server-side logic to initiate PayPal payments and handle success and failure callbacks.

Download Source Code

Conclusion:

By following this comprehensive guide, you’ve learned how to integrate PayPal payment gateway into your web application using Node.js for the backend and React.js for the frontend. This integration allows you to securely process online payments, enhancing the user experience and expanding the capabilities of your application. Experiment with additional features the PayPal API offers to further customize and optimize your payment solution.

This guide provides a solid foundation for integrating PayPal payments into your web application, but remember to consult the official PayPal documentation for more advanced features and best practices. Happy coding!