Razorpay Payment Integration in Node.js & React

by Harsh Abrol 2 minute read 75 views

Integrate Razorpay with Node.js & React to facilitate secure online transactions, providing a smooth checkout experience with real-time payment processing.

Key Points

  • 40% faster checkout with Razorpay in Node.js & React increases conversions.
  • Smart retry reduces payment failures by 80% with Node.js backend integration.
  • Razorpay APIs provide 99.9% uptime with React & Express for hassle-free payments.
Digittrix Blog Author Image

Co-Founder

Vandana Abrol Digittrix Blog Author Image

4 min read

With Over 14 years of Experience in the IT Field, Helping Companies Optimise there Products for more Conversions

image showing razorpay payment integration in with node js and react

Introduction

Integrating Razorpay into your Node.js and React applications allows for hassle-free online transactions that help businesses accept payments from credit/debit cards, UPI, net banking, and wallets. It allows businesses to handle online transactions securely and efficiently. Whether you are using an eCommerce website, mobile app development, or SaaS development, integrating a trusted payment gateway increases user experience and makes payment seamless.

This guide will walk you through the integration of Razorpay with a Node/Express backend and a React frontend for a full-stack application step by step.

Why Razorpay for Payment Integration?

  1. Supports Various Payment Modes: Accept payments through UPI, credit/debit cards, net banking, or wallets.
  2. Easy Integration to API: Well-documented APIs that speed up and simplify integration for all developers working with the web app or payment app.
  3. Secure Transactions: Razorpay ensures encrypted payments, following industry standards.
  4. Real-Time Payment Tracking: Stay updated with real-time transaction monitoring.
  5. Webhook Notifications: Automate transaction updates in your system.
  6. International Payments: Expand your reach with multi-currency support.

Subscription or one-time? Find the best payment gateway for your business model and maximize your revenue efficiently.

Prerequisites

Before starting, ensure that you have the following:

  1. Node.js Installed: Download and install Node.js.
  2. Razorpay Account: Sign up at Razorpay and generate API keys.
  3. Basic Knowledge of JavaScript, Node.js, and React.
  4. Postman (optional but recommended) for testing APIs.

Setting Up Razorpay Account

Go to Razorpay Dashboard

  1. Sign up or log in.
  2. Navigate to Settings > API Keys.
  3. Click on Generate Live/Test Key.
  4. Save the key_id and key_secret.

Note: Use test keys for development. Switch to live keys when deploying.

Backend (Node.js + Express)

Step 1: Install Dependencies

npm init -y

npm install express dotenv cors axios crypto razorpay

Step 2: Create EndPoints

POST /create-order - Create a Payment Order
This endpoint generates a new order using the Razorpay API and returns an orderId, which is needed to initialize the payment process.

Request Format

  1. Method: POST
  2. Endpoint: /api/create-order
  3. Headers: Content-Type: application/json
  4. Body:

                                        {
  amount: 500,
  currency: "INR",
};
                                    

Process

  1. The frontend sends the amount and currency (default: INR).
  2. The backend communicates with Razorpay to create an order.
  3. Razorpay responds with an orderId, which is sent to the fronten

Response Format

                                        {
  success: true,
  orderId: "order_xyz123",
};
                                    

POST /api/verify-payment - Verify Payment Signature

This endpoint verifies whether the payment made by the user is genuine by validating the Razorpay signature.

Request Format

  1. Method: POST
  2. Endpoint: /api/verify-payment
  3. Headers: Content-Type: application/json
  4. Body:

                                         {
  orderId: "order_xyz123",
  razorpayPaymentId: "pay_abc123",
  razorpaySignature: "valid_signature",
};
                                    

Process

  1. The frontend sends orderId, paymentId, and signature after a successful payment.
  2. The backend generates a hash using crypto.createHmac and compares it with Razorpay’s signature.
  3. If the generated hash matches, the payment is considered valid.

Response Format

Successful Payment

                                        {
  success: true,
  message: "Payment verified successfully",
};

                                    

Invalid Signature

                                        {
  success: false,
  message: "Invalid signature",
};

                                    

Step 3: Code Implementation

                                        import express from "express";
import dotenv from "dotenv";
import Razorpay from "razorpay";
import cors from "cors";
import crypto from "crypto";

dotenv.config();

const app = express();
const port = process.env.PORT || 8080;

// Initialize Razorpay instance
const razorpay = new Razorpay({
 key_id: process.env.RAZORPAY_KEY_ID,
 key_secret: process.env.RAZORPAY_SECRET,
});

app.use(cors());
app.use(express.json());

// Root Route
app.get("/", (req, res) => {
 res.send("Razorpay Payment Gateway API is running.");
});

/**
* Create Order API
* Endpoint: POST /create-order
*/
app.post("/create-order", async (req, res) => {
 try {
   const { amount, currency } = req.body;

   if (!amount || !currency) {
     return res
       .status(400)
       .json({ success: false, message: "Invalid request parameters" });
   }

   const options = {
     amount: amount, // Amount in paise (e.g., ₹10 = 1000)
     currency: currency,
     receipt: `receipt_${Date.now()}`,
   };

   const order = await razorpay.orders.create(options);

   return res.status(200).json({
     success: true,
     orderId: order.id,
   });
 } catch (error) {
   console.error("Create Order Error:", error);
   return res.status(500).json({
     success: false,
     message: "Failed to create order",
     error: error.message,
   });
 }
});

/**
* Verify Payment API
* Endpoint: POST /verify-payment
*/
app.post("/verify-payment", async (req, res) => {
 try {
   const { orderId, razorpayPaymentId, razorpaySignature } = req.body;

   if (!orderId || !razorpayPaymentId || !razorpaySignature) {
     return res
       .status(400)
       .json({ success: false, message: "Invalid request parameters" });
   }

   const generatedSignature = crypto
     .createHmac("sha256", process.env.RAZORPAY_SECRET)
     .update(`${orderId}|${razorpayPaymentId}`)
     .digest("hex");

   if (generatedSignature === razorpaySignature) {
     return res.status(200).json({
       success: true,
       message: "Payment verified successfully",
     });
   } else {
     return res.status(400).json({
       success: false,
       message: "Payment verification failed",
     });
   }
 } catch (error) {
   console.error("Payment Verification Error:", error);
   return res.status(500).json({
     success: false,
     message: "Failed to verify payment",
     error: error.message,
   });
 }
});

// Start the server
app.listen(port, () => {
 console.log(`Server running on port ${port}`);
});
                                    

Frontend (React)

Step 1: Create a React App And install packages

npm install axios

Step 2: Create RazorpayPayment.jsx

                                        import React, { useState } from "react";
import axios from "axios";

const RazorpayPayment = () => {
 const [amount, setAmount] = useState("");


 const handlePayment = async () => {
   if (!amount) {
     alert("Please enter an amount");
     return;
   }

   try {
     // Step 1: Create order on the backend
     const { data } = await axios.post("http://localhost:8080/create-order", {
       amount: amount * 100, // Convert ₹ to paise
       currency: "INR",
     });

     if (!data.success) {
       alert("Error creating order");
       return;
     }

     const options = {
       key: "rzp_test_s6CHSVdgyr5wii", // Replace with your Razorpay Key ID
       amount: amount * 100,
       currency: "INR",
       name: "Digittrix",
       description: "Payment for Product/Service",
       order_id: data.orderId,
       handler: async function (response) {
         const verifyRes = await axios.post(
           "http://localhost:8080/verify-payment",
           {
             orderId: data.orderId,
             razorpayPaymentId: response.razorpay_payment_id,
             razorpaySignature: response.razorpay_signature,
           }
         );

         if (verifyRes.data.success) {
           alert("Payment successful!");
         } else {
           alert("Payment verification failed!");
         }
       },
       prefill: {
         name: "John Doe",
         email: "johndoe@example.com",
         contact: "9876543210",
       },
       theme: {
         color: "#528FF0",
       },
     };

     const razorpay = new window.Razorpay(options);
     razorpay.open();
   } catch (error) {
     console.error("Payment Error:", error);
     alert("Payment failed, try again.");
   }
 };

 return (
   <div className="container">
     <h2>Razorpay Payment</h2>
     <input
       type="number"
       placeholder="Enter Amount"
       value={amount}
       onChange={(e) => setAmount(e.target.value)}
     />
     <button onClick={handlePayment}>Pay with Razorpay</button>
   </div>
 );
};

export default RazorpayPayment;
                                    

Step 3: Add Component to App.js

                                        import "./App.css";
import RazorpayPayment from "./razorpayComponent";

function App() {
  return (
    <>
      <div className="App">
        <h1>React + Razorpay Integration</h1>
        <RazorpayPayment />
      </div>
    </>
  );
}

export default App;
                                    

Step 4: Load Razorpay Script

In public/index.html, add the Razorpay checkout script inside the <head> tag:

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

Final Steps

  1. Start your backend (node server.js)
  2. Start your frontend (npm start)
  3. Enter an amount and complete the Razorpay payment
  4. Backend verifies the payment
  5. Redirects to success or failure page

Final Words

Integrating Razor Pay with Node.js and React is the most important aspect of the e-commerce, mobile app development and SaaS business for transaction payments. With the help of APIs and SDKs, you can easily integrate such seamless and secure payment solutions into your web development projects.

This guide will help the developers in implementing effective Razorpay payment integration in the applications, ensuring secure transactions and better user experience.

Tech Stack & Version

Backend

  • Node.js: v18.x
  • Express.js: v4.x

Frontend

  • React: v18.x

  • Axios: v1.x

Deployment

  • Vercel
  • Netlify
  • Heroku
img

©2025Digittrix Infotech Private Limited , All rights reserved.