A Step-by-Step Guide to Integrating Razorpay Payment Gateway in a React.js Application
Pre-requisites: Setting Up Your Razorpay Account & Getting API Keys
To effectively integrate Razorpay payment gateway in React.js, the foundational step is establishing a robust merchant account with Razorpay and securing your API keys. Razorpay is a leading payment solution in India, known for its extensive features, ease of use, and strong security protocols, making it an ideal choice for businesses of all sizes. The first phase involves signing up on the official Razorpay website (razorpay.com). During the signup process, you'll provide essential business details for KYC verification, which is crucial for activating your account and enabling live transactions.
Once your account is set up and verified (even for testing purposes), navigate to your Razorpay Dashboard. From the left-hand menu, go to "Settings" and then select "API Keys." Here, you will find your unique Key ID and Key Secret. It's imperative to generate separate keys for your "Test Mode" and "Live Mode" environments. Always use your test keys for development and staging, and switch to live keys only when your application is ready for production. The Key ID is generally used on the client-side (though ideally, it's passed from your backend for security), while the Key Secret must always remain confidential and be used exclusively on your server-side for generating orders and verifying signatures. Never expose your Key Secret in your frontend code or public repositories. Treating these keys with utmost security prevents unauthorized access and potential financial fraud, a principle WovLab emphasizes in all our payment integration projects.
WovLab Insight: A common pitfall in payment gateway integration is the mishandling of API keys. Always differentiate between test and live keys, and strictly adhere to server-side usage for your Key Secret to maintain PCI DSS compliance and safeguard your transactions.
Step 1: Installing and Configuring the Razorpay SDK in Your React Project
Once your Razorpay API keys are securely obtained, the next phase to integrate Razorpay payment gateway in React.js involves setting up the client-side SDK. While Razorpay offers a direct script tag inclusion method, for modern React applications, integrating via an npm package provides better module management and ensures a cleaner project structure. The official Razorpay JavaScript library facilitates interaction with the payment gateway from your frontend.
Start by installing the Razorpay library in your React project. Although there isn't an official “razorpay-react” npm package, you can dynamically load the Razorpay checkout script, which is the recommended approach. This method ensures the script is loaded only when needed, optimizing initial page load times.
Here’s how you typically set up the dynamic script loading:
- Create a utility function to load the script:
loadScript(src)function that returns a Promise.- Inside the function, create a new
<script>element. - Set its
srcattribute to the Razorpay CDN URL (e.g.,"https://checkout.razorpay.com/v1/checkout.js"). - Append the script to the document body.
- Resolve the Promise on
onloadand reject ononerror. - In your React component where you want to trigger payment:
- Use the
useEffecthook to callloadScript. - Once the script is loaded, the global
Razorpayobject will be available. - Store this object in a state or ref if needed for later use.
This dynamic loading approach ensures that the Razorpay script doesn't block the rendering of your React application and is loaded efficiently. WovLab recommends this method for optimal performance and user experience in complex React SPAs.
Step 2: Creating the Payment Order on Your Backend (Node.js/Express Example)
Creating the payment order on your backend is a critical step for security and integrity when you integrate Razorpay payment gateway in React.js. This prevents malicious users from tampering with payment details like the amount or currency from the client-side. Your backend acts as a trusted intermediary, securely communicating with the Razorpay API using your Key Secret.
For this example, we'll use Node.js with Express. First, you'll need to install the official Razorpay Node.js library:
npm install razorpay
Next, configure your Razorpay instance with your Key ID and Key Secret. Remember, the Key Secret must NEVER be exposed on the frontend.
A typical backend endpoint for creating an order might look like this:
// In your Express route file (e.g., routes/payment.js)
const express = require('express');
const Razorpay = require('razorpay');
const router = express.Router();
const instance = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID,
key_secret: process.env.RAZORPAY_KEY_SECRET,
});
router.post('/create-order', async (req, res) => {
try {
const options = {
amount: req.body.amount * 100, // amount in the smallest currency unit (e.g., paise)
currency: "INR",
receipt: "order_rcptid_" + Math.random().toString(36).substring(2, 10),
notes: {
orderType: "Website Payment",
userId: req.body.userId || "guest",
}
};
const order = await instance.orders.create(options);
res.status(200).json({ orderId: order.id });
} catch (error) {
console.error("Error creating Razorpay order:", error);
res.status(500).send("Server Error");
}
});
This endpoint receives an amount (and optionally other details) from your React frontend, securely creates an order with Razorpay, and returns the generated orderId back to the frontend. This orderId is crucial for initiating the payment on the client side.
Expert Tip: Always use environment variables (
process.env) to store sensitive keys likeRAZORPAY_KEY_IDandRAZORPAY_KEY_SECRET. Hardcoding them is a significant security vulnerability that WovLab actively prevents in our development practices.
Step 3: Triggering the Razorpay Checkout Modal from Your React Frontend
With the order securely created on your backend, the focus shifts to the React frontend to seamlessly integrate Razorpay payment gateway in React.js by triggering the checkout experience. This involves presenting the Razorpay payment modal to the user, allowing them to complete the transaction. Your React component will need to make a request to your backend to obtain the orderId, and then use that ID to initialize and open the Razorpay checkout.
First, ensure the Razorpay script is loaded as discussed in Step 1. Then, you'll typically have a button or an action that initiates the payment process:
// Inside your React component (e.g., PaymentButton.js)
import React, { useState, useEffect } from 'react';
const PaymentButton = () => {
const [razorpayLoaded, setRazorpayLoaded] = useState(false);
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://checkout.razorpay.com/v1/checkout.js';
script.onload = () => setRazorpayLoaded(true);
document.body.appendChild(script);
}, []);
const displayRazorpay = async () => {
if (!razorpayLoaded) {
alert('Razorpay script not loaded yet.');
return;
}
// 1. Call your backend to create an order
const response = await fetch('/api/create-order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount: 500 }), // Example amount in Rupees
});
const { orderId } = await response.json();
const options = {
key: 'YOUR_RAZORPAY_KEY_ID', // Your Test Key ID from pre-requisites
amount: 500 * 100, // Amount in paise (e.g., 500 INR = 50000 paise)
currency: 'INR',
name: 'WovLab Services',
description: 'Payment for your order',
order_id: orderId, // The order ID obtained from your backend
handler: function(response) {
// This callback is triggered on successful payment
// Send response to your backend for signature verification
alert('Payment Success! Payment ID: ' + response.razorpay_payment_id);
// Implement Step 4 here: Call backend for verification
},
prefill: {
name: 'John Doe',
email: 'john.doe@example.com',
contact: '9999999999',
},
notes: {
address: 'WovLab Office',
shipping: 'standard',
},
theme: {
color: '#61dafb', // Custom color for the modal
},
};
const rzp1 = new window.Razorpay(options);
rzp1.on('payment.failed', function(response) {
alert('Payment failed: ' + response.error.code + ' ' + response.error.description);
// Handle payment failure logic
});
rzp1.open();
};
return (
<button onClick={displayRazorpay} disabled={!razorpayLoaded}>
Pay Now
</button>
);
};
export default PaymentButton;
This component orchestrates the client-side payment flow, fetching the order from the backend and then using the Razorpay object to open the checkout modal. The handler function is crucial as it captures the payment response for post-payment verification.
Step 4: Securely Verifying the Payment Signature for Transaction Confirmation
This is arguably the most critical security step when you integrate Razorpay payment gateway in React.js. After a successful payment, Razorpay redirects the user back to your application or, more commonly, invokes the handler callback you defined. This callback receives a payment object containing razorpay_payment_id, razorpay_order_id, and crucially, razorpay_signature. While the payment appears successful on the client, you must never trust this client-side confirmation.
The razorpay_signature is a hash generated by Razorpay using your order_id, payment_id, and your Key Secret. Your backend must recalculate this hash using the same algorithm and data, and then compare it with the signature received from Razorpay. If they match, the payment is verified as genuine; otherwise, it's a fraudulent attempt or a corrupted transaction.
You'll send the three parameters (payment_id, order_id, signature) from the frontend (inside the handler function) to a new backend endpoint. On your Node.js/Express backend:
// In your Express route file (e.g., routes/payment.js)
const crypto = require('crypto');
router.post('/verify-payment', (req, res) => {
const { razorpay_payment_id, razorpay_order_id, razorpay_signature } = req.body;
const secret = process.env.RAZORPAY_KEY_SECRET; // Your Key Secret
const generated_signature = crypto.createHmac('sha256', secret)
.update(razorpay_order_id + '|' + razorpay_payment_id)
.digest('hex');
if (generated_signature === razorpay_signature) {
// Payment is VERIFIED. Update your database, fulfill the order, etc.
res.status(200).json({ success: true, message: 'Payment verified successfully.' });
} else {
// Payment verification FAILED. Log potential fraud attempt.
res.status(400).json({ success: false, message: 'Payment verification failed.' });
}
});
This server-side verification is paramount for security. Without it, a malicious user could potentially trick your system into believing a payment was successful without any actual funds being transferred. WovLab always implements this crucial step to safeguard our clients' financial operations and ensure data integrity.
Comparison: Client-Side vs. Server-Side Verification
| Feature | Client-Side Verification (NOT Recommended) | Server-Side Verification (Recommended) |
|---|---|---|
| Security | Extremely Poor, Prone to Tampering | Robust, Secure against Client-Side Manipulation |
| Integrity | No Guarantee of Payment Authenticity | Guarantees Payment Authenticity via Signature Match |
| Key Exposure | Requires exposing Key Secret (MAJOR vulnerability) | Key Secret remains secure on the server |
| Fraud Prevention | Virtually None | Essential for Preventing Fraudulent Transactions |
| Complexity | Seemingly Simpler (but unsafe) | Adds a backend step, but critical for safety |
Integration Stuck? Let WovLab’s Fintech Experts Handle It for You
Integrating a payment gateway like Razorpay into a complex React.js application involves numerous steps, from secure key management and dynamic script loading to robust backend order creation and, most critically, rigorous signature verification. While this guide provides a clear step-by-step approach, real-world scenarios often present unique challenges:
- Handling edge cases like network failures during payment.
- Implementing custom UI/UX flows for a seamless user experience.
- Integrating with existing ERP systems or inventory management solutions.
- Ensuring PCI DSS compliance and other regulatory requirements.
- Optimizing performance for high-volume transactions.
- Debugging subtle issues that arise between frontend and backend communication.
At WovLab (wovlab.com), we understand these complexities intimately. As a leading digital agency from India, our expertise spans comprehensive development services, including intricate Payments Integration for various platforms and fintech solutions. Our team of seasoned developers and fintech experts specializes in not just setting up payment gateways but in creating end-to-end secure, scalable, and efficient payment ecosystems.
If you're finding yourself bogged down by technical hurdles, security concerns, or simply want to accelerate your development timeline, WovLab is here to help. We offer tailored solutions ranging from custom React.js development to secure Node.js backend services, cloud infrastructure management, and even leveraging AI Agents for intelligent fraud detection. By partnering with WovLab, you gain:
- Expertise: Deep knowledge in Razorpay integration and broader fintech landscapes.
- Efficiency: Faster deployment with best practices, saving you time and resources.
- Security: Implementations that adhere to the highest security standards, protecting your business and customers.
- Scalability: Solutions designed to grow with your business needs.
- Compliance: Guidance and implementation aligned with local and international payment regulations.
WovLab's Commitment: We don't just write code; we build digital foundations. For your payment integration needs, we ensure reliability, security, and a frictionless experience for your users, allowing you to focus on your core business growth.
Don't let payment gateway integration be a bottleneck. Reach out to WovLab today for a consultation, and let our experts ensure your React.js application securely processes payments with Razorpay, allowing you to focus on delivering exceptional value to your customers.
Ready to Get Started?
Let WovLab handle it for you — zero hassle, expert execution.
💬 Chat on WhatsApp