Create Order Flow
This document provides a comprehensive guide on integrating Create Order Api along with Razorpay integration in 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);
});
}
};
This initializes the Razorpay SDK in your application. It should be done on the final billing page, where you create the order.
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 totalAmount = await getTotalAmount(); // total amount
const razorPayOrderId = await createOrder(); //creating order
console.log("razorPayOrderId", razorPayOrderId);
await razorpay_fn(razorPayOrderId, totalAmount); // intializing transaction
localStorage.removeItem("cartId"); // once all the functions have successfully been called we will remove the cartId from our local storage as the cart is deleted from the backend when we have successfully created an order
};
This handler uses the following three functions:
-
getTotalAmount– This function fetches the total cart amount by calling yourget cartAPI. Alternatively, you can track the cart amount using state management. -
createOrder– This function creates a new order by calling your backend API and returns therazorpayOrderId. Refer to the linked documentation for more details. -
razorpay_fn– This function opens the Razorpay payment modal to initiate the transaction.
3. Opening Razorpay Payment Modal
After creating an order and obtaining the razorpayOrderId, use the following function to open the Razorpay payment modal. This assumes the Razorpay script is already loaded.
const razorpay_fn = async (razorpayOrderId: string, totalAmount: number) => {
try {
// 1. Load Razorpay SDK if not already loaded
if (!window.Razorpay) {
await initializeRazorPay();
}
// 2. Prepare Razorpay options
const options = {
key: "rzp_test_key", // Replace with your Razorpay key
currency: "INR",
amount: totalAmount * 100, // Amount in paise
name: "Acme Corp", // Business name
description: "Test Transaction", // 📝 Optional description
image: "https://example.com/your_logo", // 🖼 Logo URL
order_id: razorpayOrderId,
// 3. Prefill customer details
prefill: {
name: "John Smith",
email: "abc@gmail.com",
contact: "9000090000",
},
// 4. Optional custom notes
notes: {
address: "Razorpay Corporate Office",
},
// 5. Theme customization
theme: {
color: "#3399cc",
},
// 6. Handle success callback
handler: function (response) {
console.log("Payment successful", response);
// Add post-payment logic here (e.g., update DB, redirect)
},
};
// 7. Create and open Razorpay modal
const rzp1 = new window.Razorpay(options);
// 8. Handle payment failure
rzp1.on("payment.failed", function (response) {
console.error(" Payment failed", response);
});
// 9. Open modal
await rzp1.open();
} catch (error) {
console.error(" Razorpay initialization failed:", error);
// Handle Razorpay setup errors here
}
};
🔧 Razorpay Configuration Breakdown
| 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)
}
Failure Handler
rzp1.on("payment.failed", function (response) {
console.log(response.error.code); // error code
// Handle payment failure
});
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.