Skip to main content

Version: v1

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:

  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);
});
}
};

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:

  1. getTotalAmount – This function fetches the total cart amount by calling your get cart API. Alternatively, you can track the cart amount using state management.

  2. createOrder – This function creates a new order by calling your backend API and returns the razorpayOrderId. Refer to the linked documentation for more details.

  3. 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

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)
}

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

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.