Integrating Razorpay Payment Gateway in React.js

December 21, 2024 (5mo ago)

Integrating a payment gateway is a crucial step in building a robust e-commerce platform. Razorpay offers a seamless solution for handling payments in India. This guide walks you through the process of integrating Razorpay into a React.js frontend with a Node.js backend.

๐Ÿงพ Prerequisites


๐Ÿ› ๏ธ Backend Setup (Node.js + Express)

1. Initialize the Project

mkdir razorpay-integration
cd razorpay-integration
npm init -y

2. Install Dependencies

npm install express cors dotenv razorpay

3. Configure Environment Variables

Create a .env file in the root directory:

RAZORPAY_KEY_ID=your_key_id
RAZORPAY_KEY_SECRET=your_key_secret

4. Create the Server (server.js)

require('dotenv').config();
const express = require('express');
const Razorpay = require('razorpay');
const cors = require('cors');
 
const app = express();
app.use(cors());
app.use(express.json());
 
const razorpay = new Razorpay({
  key_id: process.env.RAZORPAY_KEY_ID,
  key_secret: process.env.RAZORPAY_KEY_SECRET,
});
 
app.post('/create-order', async (req, res) => {
  try {
    const options = {
      amount: req.body.amount * 100, // amount in the smallest currency unit
      currency: 'INR',
      receipt: `receipt_order_${Math.random().toString(36).substring(7)}`,
    };
    const order = await razorpay.orders.create(options);
    res.json(order);
  } catch (err) {
    res.status(500).send(err);
  }
});
 
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

๐Ÿ’ป Frontend Setup (React.js)

1. Install Axios

npm install axios

2. Create the Payment Component (PaymentButton.js)

import React from 'react';
import axios from 'axios';
 
const PaymentButton = () => {
  const handlePayment = async () => {
    try {
      const { data } = await axios.post('http://localhost:5000/create-order', { amount: 500 });
      const options = {
        key: 'your_key_id', // Enter the Key ID generated from the Dashboard
        amount: data.amount,
        currency: data.currency,
        name: 'Your Company Name',
        description: 'Test Transaction',
        order_id: data.id,
        handler: function (response) {
          alert(`Payment successful! Payment ID: ${response.razorpay_payment_id}`);
        },
        prefill: {
          name: 'John Doe',
          email: 'john.doe@example.com',
          contact: '9999999999',
        },
        theme: {
          color: '#3399cc',
        },
      };
      const rzp = new window.Razorpay(options);
      rzp.open();
    } catch (error) {
      console.error(error);
    }
  };
 
  return <button onClick={handlePayment}>Pay โ‚น500</button>;
};
 
export default PaymentButton;

3. Load Razorpay Script

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

โœ… Testing the Integration

1. Start the Backend Server:

node server.js

2. Start the React Application:

npm start

3. Initiate Payment:

Navigate to your React app in the browser and click the "Pay โ‚น500" button to initiate the payment process.

๐Ÿ“š Additional Resources


If you need further assistance or have specific requirements, feel free to ask!