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:
- Initialize the Razorpay script
- Create an order
- Open the Razorpay payment modal
- 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
key | String | Yes | Your Razorpay API key |
currency | String | Yes | Currency code (e.g., INR, USD) |
amount | Number | Yes | Amount in smallest currency unit (paise) |
name | String | Yes | Your business name |
description | String | No | Description of the payment |
image | String | No | URL of your logo |
order_id | String | Yes | Order ID received from your backend |
prefill | Object | No | Customer details to prefill the checkout form |
notes | Object | No | Additional notes for the transaction |
theme | Object | No | UI customization options |
handler | Function | Yes | Callback 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
| Parameter | Type | Description |
|---|---|---|
razorpay_payment_id | String | Unique identifier for the payment transaction |
razorpay_order_id | String | Identifier for the order this payment is associated with |
razorpay_signature | String | Cryptographic signature used to verify the payment authenticity |
Error Response Parameters
| Error Field | Type | Description |
|---|---|---|
code | String | Error code representing the type of failure (e.g., BAD_REQUEST_ERROR) |
description | String | Human-readable description of what went wrong |
source | String | Source of the error (e.g., gateway, customer) |
step | String | Step in the payment process where failure occurred (e.g., payment_authorization) |
reason | String | Specific reason for the failure (e.g., authentication_failed) |
metadata.order_id | String | The order ID associated with the failed payment |
metadata.payment_id | String | The payment ID if created before failure |
Common Error Codes
| Error Code | Description | Possible Solution |
|---|---|---|
BAD_REQUEST_ERROR | Missing or invalid parameters | Check all required fields are properly formatted |
GATEWAY_ERROR | Issue with payment gateway | Retry the payment or try a different payment method |
NETWORK_ERROR | Network connectivity issues | Check internet connection and retry |
INTERNAL_ERROR | Internal Razorpay server error | Contact Razorpay support if persistent |
CARD_DECLINED | Card was declined by the bank | Try a different card or payment method |
AUTHENTICATION_ERROR | 3D Secure authentication failed | Ask 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
- Always verify payments on your server: Never rely solely on client-side success callbacks for payment confirmation
- Use environment variables for API keys
- Implement proper error handling for both API calls and Razorpay initialization
- 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