DEV Community

aviral srivastava
aviral srivastava

Posted on

"Integrating Razor pay API in a React 18 App with Node.js Backend: A Complete Guide"

Step 1: Set Up Your Razorpay Account

  • To use Razorpay, you’ll need to create an account and set up your business information.

1.1. Create an Account

Razor pay Account Verification OR KYC Verifications: Easy Steps for Developers

  • Setting up your Razorpay account is simple! Follow these steps to get verified:

1. Navigate to Account Verification

  • Log in to your Razorpay dashboard.
  • Go to SettingsAccount Verification.

2. Enter Your Business Address

  • Provide your complete business address.

3. Select Your Business Category

  • Choose the appropriate Business Category (e.g., e-commerce, education, etc.).
  • Select a Subcategory and fill in any additional details.
  • Click Continue.

4. Upload Your Business Policy

  • Add your business policy details.
  • Review and edit if needed.
  • Click Create policy pagesPublish.

5. Upload Identity Proof

  • Upload documents like Aadhar Card, Passport, or Voter ID.
  • Ensure both front and back sides are uploaded.
  • Only JPG/PNG formats are allowed.
  • Alternatively, use DigiLocker to upload.

6. Provide PAN and Aadhaar Details

  • Upload your PAN, Aadhar, and Driving License as required.
  • Ensure both sides of documents are uploaded.

7. Add Bank Details

  • Enter your:
    • Account Number
    • IFSC Code
  • This account will be used for fund settlements.
  • Click Done.

8. Add GST Details (if applicable)

  • Your GSTIN may auto-fill after PAN verification.
  • If not, enter manually.
  • If you don’t have a GSTIN, select the appropriate checkbox.
  • Click Done.

9. Upload Business Documents

  • Provide any additional business documents based on your business type.

10. Submit KYC

  • Double-check all details.
  • Click Submit KYC to complete the process.

Complete Your KYC

Add KYC

Setting Up Razor pay: KYC Verification and Test Mode vs Live Mode Explained

  • If you’re setting up Razor pay for the first time, this guide will walk you through the KYC verification process and explain the differences between Test Mode and Live Mode.

1. Log in to Razor pay

  • Visit the Razor pay dashboard and log in using your account credentials. If you don’t have an account, sign up for free.

2. KYC Verification

  • To enable Live Mode (for accepting real payments), you need to complete KYC verification. This involves verifying your business and banking details.
  • You’ll see a prompt to Get KYC Verified for ₹199. This is a one-time, non-refundable fee for manual verification of your business.

    Why is KYC Verification Important?

  • It enables you to start collecting payments in Live Mode.

  • You gain access to all Razor pay payment products like Payment Links, Subscriptions, etc.

Steps:

  • Click on the Get KYC Verified button.
  • Complete the required steps and upload the necessary documents.
  • Razor pay will notify you once your KYC is approved.

Note: If you’re not ready to pay ₹199 or want to explore Razor pay before committing, you can use Test Mode.

3. Test Mode vs Live Mode

Test Mode

Test Mode is a sandbox environment where you can simulate payment flows without involving real money. It’s perfect for testing and debugging during development.

Key Features of Test Mode:

  • No real transactions: Payments made in Test Mode are simulated and don’t involve actual money.
  • Free to use: You don’t need to pay or complete KYC to access Test Mode.
  • Test cards available: Razor pay provides dummy card details, UPI, and wallets to simulate payments.

When to Use Test Mode?

  • During development to verify your integration works correctly.
  • For debugging payment flows and handling edge cases like payment failures or refunds.

How to Access Test Mode?

  • Log in to the Razor pay Dashboard.
  • Switch to Test Mode using the toggle at the top of the dashboard.

Live Mode

What is Live Mode?

  • Live Mode is the production environment where real transactions are processed using actual customer payments.

Key Features of Live Mode:

  • Real transactions: Payments are processed with actual money from your customers.
  • Requires KYC: You must complete Razor pay's KYC process to enable Live Mode.
  • Fees applied: Razor pay charges a transaction fee for each payment processed (typically 2%–3% depending on the payment method).

When to Use Live Mode?

  • Once your integration is fully tested in Test Mode.
  • For real-world transactions with actual customers.

How to Access Live Mode?

  • Log in to the Razor pay Dashboard.
  • Complete the KYC process to enable Live Mode.

Difference Between Test Mode and Live Mode

Feature Test Mode Live Mode
Purpose Simulate and test transactions without real money. Accept real payments from customers.
KYC Requirement No KYC required. KYC verification required (₹199 fee).
Payments Dummy transactions only. Real transactions with actual money.
When to Use? Use Test Mode when you’re building and testing your application to ensure everything works fine. Use Live Mode when your business is ready to go live and accept payments from customers.

How to Switch Between Test Mode and Live Mode

  1. Log in to your Razorpay Dashboard.

  2. Locate the toggle option:

    • On the top-right corner, you’ll find an option to toggle between Test Mode and Live Mode.
  3. Using Test Mode:

    • In Test Mode, you can use Razor pay's dummy API keys to simulate transactions.
  4. Using Live Mode:

    • In Live Mode, you’ll use actual API keys to process real transactions.

KYC Verification for 199 RS

Go To Razor pay for test mode

For More Details Follow This Link

Prerequisites

  • Make sure you have the following tools installed:

  • Node.js (v22.11.0 or above)

  • npm or yarn

  • Razorpay API Key

  • React 18

  • A basic understanding of React and Node.js

Project Structure

razorpay-api/  
├── backend/  
│   ├── server.js  
│   ├── package.json  
│   ├── .env  
└── frontend/  
    ├── src/  
    │   ├── App.js  
    │   ├── Payment.js  
    │   └── server.js  
    ├── package.json  
    └── .env  

Enter fullscreen mode Exit fullscreen mode

Backend Implementation

1. Initialize the Backend

mkdir backend && cd backend  
npm init -y
npm install express body-parser cors dotenv razorpay
Enter fullscreen mode Exit fullscreen mode

Create a server.js file in the backend folder:

const express = require("express");
const Razorpay = require("razorpay");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();

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

// Razorpay instance
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) => {
  const { amount } = req.body;

  try {
    const order = await razorpay.orders.create({
      amount: amount * 100, // amount in paise
      currency: "INR",
      receipt: `receipt_${Date.now()}`,
    });
    res.json({ orderId: order.id });
  } catch (error) {
    res.status(500).send(error);
  }
});

app.listen(5000, () => {
  console.log("Server running on Your_Localhost");[
});

Enter fullscreen mode Exit fullscreen mode

Environment Variables (.env)

RAZORPAY_KEY_ID=<your_test_key_id>
RAZORPAY_KEY_SECRET=<your_test_key_secret>
Enter fullscreen mode Exit fullscreen mode

Frontend Setup (React)

1.Initialize Frontend

npx create-react-app frontend
cd frontend
npm install axios dotenv

Enter fullscreen mode Exit fullscreen mode

2. Environment Variables (.env)

REACT_APP_RAZORPAY_KEY=<your_test_key_id>
REACT_APP_BACKEND_URL=<your_localhost>

Enter fullscreen mode Exit fullscreen mode

Create a Payment.js file in the src folder:

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

const Payment = () => {
  const [amount, setAmount] = useState(""); // State to track user-entered amount
  const [paymentDetails, setPaymentDetails] = useState(null); // State to track payment response

  const handlePayment = async () => {
    if (!amount || isNaN(amount) || amount <= 0) {
      alert("Please enter a valid amount.");
      return;
    }

    const backendURL = process.env.REACT_APP_BACKEND_URL;

    try {
      // Step 1: Create an order on the backend
      const { data } = await axios.post(`${backendURL}/create-order`, { amount });

      // Step 2: Define Razorpay checkout options
      const options = {
        key: process.env.REACT_APP_RAZORPAY_KEY, // Razorpay API Key
        amount: amount * 100, // Amount in paise
        currency: "INR",
        name: "Test Company",
        description: "Test Transaction",
        order_id: data.orderId, // Order ID from backend
        handler: (response) => {
          // Step 3: Handle successful payment
          alert("Payment Successful");
          console.log("Payment Response:", response);
          setPaymentDetails(response); // Update state with payment details
        },
        prefill: {
          name: "Test User",
          email: "testuser@example.com",
          contact: "9999999999",
        },
        theme: {
          color: "#3399cc",
        },
      };

      // Step 4: Open Razorpay checkout
      const razor = new window.Razorpay(options);
      razor.open();
    } catch (error) {
      console.error("Payment Failed:", error);
      alert("Payment Failed. Please try again.");
    }
  };

  return (
    <div>

      <div>
        <label>Enter Amount (): </label>
        <input
          type="number"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          placeholder="Enter amount to pay"
        />
        <button onClick={handlePayment}>Pay {amount || 0}</button>
      </div>

      {/* Display Payment Details */}
      {paymentDetails && (
        <div style={{ marginTop: "20px", border: "1px solid #ccc", padding: "10px" }}>
          <h3>Payment Details</h3>
          <p><strong>Payment ID:</strong> {paymentDetails.razorpay_payment_id}</p>
          <p><strong>Order ID:</strong> {paymentDetails.razorpay_order_id}</p>
          <p><strong>Signature:</strong> {paymentDetails.razorpay_signature}</p>
        </div>
      )}
    </div>
  );
};

export default Payment;

Enter fullscreen mode Exit fullscreen mode

Update App.js

  • Replace the contents of App.js with:
import React from "react";
import Payment from "./Payment";

const App = () => {
  return (
    <div>
      <h1>Razor pay  Integration</h1>
      <Payment />
    </div>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

Test the Integration

1. Start the backend server:

cd backend  
node server.js  

Enter fullscreen mode Exit fullscreen mode

2. Start the React app:

cd frontend  
npm start  

Enter fullscreen mode Exit fullscreen mode

Razor Pay Payment interface in react front end

Razor pay displaying details like payment id, order id,signature

customer details adding in razor pay dashboard

Top comments (0)