Skip to main content

Razorpay Payment Integration Guide

This document provides a comprehensive guide on integrating Razorpay payment gateway into your React application.

Overview

The integration follows these main steps:

  1. Initialize the Razorpay script
  2. Create an order
  3. Open the Razorpay payment modal
  4. Handle payment success or failure

Prerequisites

  • A Razorpay account and API
  • A cart with some items

Implementation

1. Initializing Razorpay Script

Load the Razorpay script when the component/page mounts.

useEffect(() => {
initializeRazorPay();
}, []);

const initializeRazorPay = async () => {
if (!window.Razorpay) {
// Create and load script
const script = document.createElement("script");
script.src = "https://checkout.razorpay.com/v1/checkout.js";
script.async = true;

// Return a promise that resolves when script loads
await new Promise((resolve, reject) => {
script.onload = resolve;
script.onerror = reject;
document.body.appendChild(script);
});
}
};

2. Form Submission Handler

The process starts when a user submits a payment form.

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
console.log("handle Submit");
const orderId = await createOrder();
console.log("orderId", orderId);
await razorpay_fn(orderId);
};

3. Creating an Order

Then create an order.

const createOrder = async () => {
if (!cartObj) return;
const cartId = cartObj.id;
const customerId = cartObj.customerId;
const payload = {
cartId: cartId,
customerId: customerId,
channelType: "DEFAULT",
paymentMethod: "CVS",
buyerInfo: {
// Buyer information goes here
},
shippingDetail: {
// Shipping information goes here
},
address: {
// Address information goes here
},
extraData: {},
};
const res = await api.post("/order", payload);
const data = res.data.data;
console.log("result", data);
return data.razorpayOrderId;
};

4. Opening Razorpay Payment Modal

After creating an order, getting razorpayOrderId and ensuring the Razorpay script is loaded, open the payment modal.

const razorpay_fn = async (razorpayOrderId: string) => {
try {
// Check if Razorpay is already loaded
if (!window.Razorpay) {
// Create and load script
const script = document.createElement("script");
script.src = "https://checkout.razorpay.com/v1/checkout.js";
script.async = true;

// Return a promise that resolves when script loads
await new Promise((resolve, reject) => {
script.onload = resolve;
script.onerror = reject;
document.body.appendChild(script);
});
}

const options = {
key: "rzp_test_key", // Replace with your Razorpay key
currency: "INR",
amount: totalAmount * 100, // Amount in smallest currency unit (paise)
name: "Acme Corp", // Your business name
description: "Test Transaction", // your business description
image: "https://example.com/your_logo", // your business logo
order_id: razorpayOrderId, // razorpayOrderId is generated when we create an order
prefill: {
name: "John Smith", // Customer's name
email: "abc@gmail.com", // Customer's email
contact: "9000090000", // Customer's phone number
},
notes: {
address: "Razorpay Corporate Office",
},
theme: {
color: "#3399cc", // Customize the color theme
},
// Add handler for payment completion
handler: function (response) {
console.log("Payment successful", response);
// Handle successful payment here
setPaymentSuccess(true);
deleteCart();
},
};

const rzp1 = new window.Razorpay(options);
rzp1.on("payment.failed", function (response) {
console.log("response", response);
deleteCart();
});
await rzp1.open();
} catch (error) {
console.error("Razorpay initialization failed:", error);
deleteCart();
// Handle error appropriately
}
};

Configuration Options

The Razorpay configuration object accepts the following parameters:

ParameterTypeRequiredDescription
keyStringYesYour Razorpay API key
currencyStringYesCurrency code (e.g., INR, USD)
amountNumberYesAmount in smallest currency unit (paise)
nameStringYesYour business name
descriptionStringNoDescription of the payment
imageStringNoURL of your logo
order_idStringYesOrder ID received from your backend
prefillObjectNoCustomer details to prefill the checkout form
notesObjectNoAdditional notes for the transaction
themeObjectNoUI customization options
handlerFunctionYesCallback function for successful payment

Event Handlers

Success Handler

handler: function (response) {
console.log("Payment successful", response);
// The response object contains:
// - razorpay_payment_id
// - razorpay_order_id
// - razorpay_signature

// Perform post-payment actions (e.g., update order status)
setPaymentSuccess(true);
deleteCart();
}

Failure Handler

rzp1.on("payment.failed", function (response) {
console.log(response.error.code); // error code
// Handle payment failure
deleteCart();
});

Here are tables for both the success and error responses from Razorpay:

Success Response Parameters

ParameterTypeDescription
razorpay_payment_idStringUnique identifier for the payment transaction
razorpay_order_idStringIdentifier for the order this payment is associated with
razorpay_signatureStringCryptographic signature used to verify the payment authenticity

Error Response Parameters

Error FieldTypeDescription
codeStringError code representing the type of failure (e.g., BAD_REQUEST_ERROR)
descriptionStringHuman-readable description of what went wrong
sourceStringSource of the error (e.g., gateway, customer)
stepStringStep in the payment process where failure occurred (e.g., payment_authorization)
reasonStringSpecific reason for the failure (e.g., authentication_failed)
metadata.order_idStringThe order ID associated with the failed payment
metadata.payment_idStringThe payment ID if created before failure

Common Error Codes

Error CodeDescriptionPossible Solution
BAD_REQUEST_ERRORMissing or invalid parametersCheck all required fields are properly formatted
GATEWAY_ERRORIssue with payment gatewayRetry the payment or try a different payment method
NETWORK_ERRORNetwork connectivity issuesCheck internet connection and retry
INTERNAL_ERRORInternal Razorpay server errorContact Razorpay support if persistent
CARD_DECLINEDCard was declined by the bankTry a different card or payment method
AUTHENTICATION_ERROR3D Secure authentication failedAsk user to check with their bank

These tables provide a quick reference for handling both successful payments and various error scenarios that might occur during the Razorpay payment process.

Best Practices

  1. Always verify payments on your server: Never rely solely on client-side success callbacks for payment confirmation
  2. Use environment variables for API keys
  3. Implement proper error handling for both API calls and Razorpay initialization
  4. Test thoroughly using Razorpay test mode before going live

Additional Resources

For more details, refer to the official Razorpay documentation.

For error handling Error Response