How to Connect Razorpay Payment

How to Connect Razorpay Payment Razorpay is one of India’s most trusted and widely adopted payment gateways, enabling businesses of all sizes to accept online payments seamlessly across multiple channels — including credit cards, debit cards, UPI, net banking, wallets, and even EMIs. Connecting Razorpay to your website or application isn’t just a technical task; it’s a strategic move that can sign

Oct 30, 2025 - 13:44
Oct 30, 2025 - 13:44
 1

How to Connect Razorpay Payment

Razorpay is one of India’s most trusted and widely adopted payment gateways, enabling businesses of all sizes to accept online payments seamlessly across multiple channels — including credit cards, debit cards, UPI, net banking, wallets, and even EMIs. Connecting Razorpay to your website or application isn’t just a technical task; it’s a strategic move that can significantly enhance conversion rates, reduce cart abandonment, and improve customer trust. Whether you’re running an e-commerce store, a SaaS platform, a subscription service, or a digital marketplace, integrating Razorpay correctly ensures smooth, secure, and scalable payment processing.

This guide walks you through every critical step required to connect Razorpay payment to your platform — from initial setup and API configuration to testing, security, and optimization. You’ll learn not only how to integrate Razorpay, but also how to do it right, avoiding common pitfalls that lead to failed transactions, compliance issues, or poor user experiences. By the end of this tutorial, you’ll have a complete, production-ready integration that aligns with industry best practices and Razorpay’s latest standards.

Step-by-Step Guide

Prerequisites Before Integration

Before you begin connecting Razorpay, ensure you have the following:

  • A registered business with a valid PAN and bank account
  • A Razorpay merchant account (sign up at razorpay.com)
  • Access to your website or application’s backend codebase
  • Basic understanding of HTTP requests, JSON, and API communication
  • SSL certificate installed on your website (HTTPS is mandatory)

Razorpay requires HTTPS for all live transactions. If your site is still on HTTP, upgrade it immediately. Most hosting providers offer free SSL certificates via Let’s Encrypt.

Step 1: Create a Razorpay Account

Navigate to razorpay.com and click “Sign Up.” You’ll be prompted to enter your business details — including legal name, address, PAN, and bank account information. You’ll also need to verify your email and mobile number. Once verified, Razorpay will guide you through the KYC process, which typically takes 24–48 hours for small businesses and up to 7 days for enterprises.

After approval, log in to your Razorpay Dashboard. Here, you’ll find your API keys — a crucial component for integration. Go to Settings > API Keys to view or generate your Key ID and Key Secret. Keep these secure — they are your gateway to processing payments.

Step 2: Choose Your Integration Method

Razorpay offers multiple integration methods depending on your platform:

  • Checkout (Pre-built UI) — Ideal for websites using HTML, JavaScript, or CMS platforms like WordPress, Shopify, or Wix. This is the fastest way to start accepting payments.
  • API (Custom Integration) — Best for custom-built applications, mobile apps, or enterprise systems requiring full control over the payment flow.
  • SDKs — Razorpay provides official SDKs for Node.js, Python, PHP, Ruby, Java, and .NET. Use these if you’re building on a supported framework.

For beginners, we recommend starting with Razorpay Checkout. It requires minimal code and handles most security and compliance aspects automatically.

Step 3: Integrate Razorpay Checkout

Razorpay Checkout is a lightweight, responsive payment form that opens in a modal window. It supports all major payment methods and automatically handles OTP, 3D Secure, and UPI redirects.

Follow these steps to embed it:

  1. Include the Razorpay Checkout script in your HTML page before the closing </body> tag:
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
  1. Create a button to trigger the payment form:
<button id="payment-button">Pay Now</button>
  1. Add JavaScript to initialize the payment modal:
<script>

document.getElementById('payment-button').addEventListener('click', function(e){

var options = {

key: "YOUR_KEY_ID", // Replace with your Key ID

amount: 50000, // Amount in paise (₹500)

currency: "INR",

name: "Your Business Name",

description: "Payment for product/service",

image: "https://yourwebsite.com/logo.png",

order_id: "ORDER_ID_12345", // Generated on server

handler: function (response){

alert("Payment successful! Payment ID: " + response.razorpay_payment_id);

// Send this to your server to verify and fulfill the order

},

prefill: {

name: "John Doe",

email: "john@example.com",

contact: "9876543210"

},

theme: { color: "

3399cc"

}

};

var rzp = new Razorpay(options);

rzp.open();

});

</script>

Important: The order_id must be generated on your server using Razorpay’s Orders API. You cannot hardcode it in frontend code for security reasons.

Step 4: Generate Orders on the Server

To create an order, make a POST request to Razorpay’s Orders API endpoint:

POST https://api.razorpay.com/v1/orders

Use your Key ID and Key Secret for authentication (Basic Auth). Here’s an example in Node.js using Express:

const express = require('express');

const app = express();

const Razorpay = require('razorpay');

const razorpay = new Razorpay({

key_id: 'YOUR_KEY_ID',

key_secret: 'YOUR_KEY_SECRET'

});

app.post('/create-order', async (req, res) => {

const { amount } = req.body; // amount in paise

const options = {

amount: amount,

currency: "INR",

receipt: "receipt_" + Date.now()

};

try {

const order = await razorpay.orders.create(options);

res.json(order);

} catch (error) {

res.status(500).json({ error: error.message });

}

});

From your frontend, call this endpoint to fetch the order_id before opening the Checkout modal:

fetch('/create-order', {

method: 'POST',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({ amount: 50000 })

})

.then(response => response.json())

.then(data => {

options.order_id = data.id;

const rzp = new Razorpay(options);

rzp.open();

});

Step 5: Verify Payment Success

After a successful payment, Razorpay redirects the user back to your site and triggers the handler function in the Checkout script. This function receives a payment_id, but do not rely on this alone to confirm payment. Fraudsters can fake frontend callbacks.

Instead, use Razorpay’s Webhook system or server-to-server verification. Webhooks are HTTP POST requests sent by Razorpay to your server whenever an event occurs — like a payment success, failure, or refund.

Set up a webhook endpoint in your server:

app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {

const payload = req.body;

const signature = req.headers['x-razorpay-signature'];

const isVerified = crypto.createHmac('sha256', 'YOUR_KEY_SECRET')

.update(payload.toString())

.digest('hex');

if (isVerified === signature) {

const event = JSON.parse(payload);

if (event.event === 'payment.captured') {

const paymentId = event.payload.payment.entity.id;

const orderId = event.payload.payment.entity.order_id;

// Update your database: mark order as paid

// Send confirmation email

// Fulfill the order

}

res.status(200).send('Webhook received');

} else {

res.status(400).send('Invalid signature');

}

});

Register this webhook URL in your Razorpay Dashboard under Settings > Webhooks. Use HTTPS and avoid localhost during testing.

Step 6: Test in Sandbox Mode

Before going live, test your integration using Razorpay’s test mode. Use test API keys (available in your dashboard) and test card details:

  • Card Number: 4111111111111111
  • Expiry: 01/25
  • CVV: 123
  • Amount: Any value under ₹10,000

Use the Razorpay Test Dashboard to simulate payment failures, timeouts, and refunds. Check your server logs and webhook events to ensure your system handles all scenarios correctly.

Step 7: Go Live

Once testing is complete, switch to live keys in your code. Update:

  • API keys from test to live
  • Checkout script URL to production
  • Webhook endpoint to your live domain

Also, ensure your business information in the Razorpay dashboard matches your website’s branding. Mismatches can cause payment declines or customer confusion.

Best Practices

1. Always Validate Amounts Server-Side

Never trust frontend values for payment amounts. A malicious user can modify the amount in browser DevTools. Always calculate and validate the total on your server before creating an order. Store the expected amount in your database and compare it with the amount received in the webhook.

2. Use Webhooks, Not Redirects, for Order Fulfillment

Payment success pages can be bypassed. Relying solely on the handler function to update order status is risky. Webhooks are server-to-server, encrypted, and immutable. They are the only reliable source of truth for payment confirmation.

3. Implement Retry Logic for Failed Payments

Network issues, bank timeouts, or UPI app crashes can cause payment failures. Instead of showing a generic “Payment Failed” message, offer users the option to retry. Log the failure reason and, if appropriate, auto-retry after 2–5 minutes. Razorpay’s API provides failure codes — use them to guide user actions (e.g., “Try another bank” or “Use UPI instead”).

4. Enable 3D Secure and Strong Customer Authentication

For cards, enable 3D Secure (3DS) in your Razorpay dashboard. This adds an extra authentication layer (like OTP or biometric verification) and reduces fraud liability. Razorpay automatically handles 3DS for eligible cards, but ensure your checkout UI supports pop-ups and redirects.

5. Optimize for Mobile

Over 70% of Indian online payments happen on mobile. Test your integration on Android and iOS devices using Chrome, Safari, and Samsung Internet. Ensure the Checkout modal is responsive, buttons are tappable, and input fields auto-focus. Avoid pop-up blockers — use inline payment forms where possible.

6. Display Clear Payment Instructions

Before the payment modal opens, inform users what to expect: “You’ll be redirected to a secure payment page,” “You may need to authenticate via your bank app,” or “UPI payments may take up to 30 seconds.” Transparency reduces support queries and abandonment.

7. Monitor Transaction Logs Daily

Set up alerts for failed payments, high refund rates, or duplicate orders. Use Razorpay’s Dashboard analytics or export data to Google Sheets or a BI tool. Look for patterns — e.g., failures from a specific bank or device type — and optimize accordingly.

8. Comply with RBI Guidelines

India’s Reserve Bank of India mandates strict data handling rules. Never store card numbers or CVVs. Razorpay handles PCI-DSS compliance for you, but you must ensure your server doesn’t log sensitive data. Use tokenization where possible — Razorpay returns a payment token after successful transactions, which you can reuse for subscriptions.

Tools and Resources

Official Razorpay Documentation

Always refer to the latest official documentation at razorpay.com/docs. It includes code samples in multiple languages, API reference guides, and migration notes for version updates.

Razorpay Test Dashboard

Use the test dashboard to simulate transactions, view mock webhooks, and debug integration issues without real money.

Postman Collection

Razorpay provides a ready-to-use Postman collection for testing API endpoints. Download it from their GitHub repository or import directly via the Postman library. This is invaluable for developers debugging order creation or refund flows.

Browser Developer Tools

Use Chrome DevTools or Firefox Developer Tools to inspect network requests during checkout. Look for failed API calls, CORS errors, or blocked scripts. Pay attention to the console and network tabs — they often reveal the root cause of integration issues.

Webhook Testing Tools

Use tools like webhook.site or ngrok to test webhook endpoints during development. Ngrok creates a secure public URL for your local server, allowing Razorpay to send real POST requests to your machine.

Payment Analytics Platforms

Integrate Razorpay data with tools like Google Analytics, Mixpanel, or Amplitude to track payment conversion rates. Set up custom events for “Payment Initiated,” “Payment Successful,” and “Payment Failed” to measure funnel drop-offs.

Code Libraries and Templates

GitHub hosts open-source templates for integrating Razorpay with popular platforms:

These repositories include full working examples, environment variables, and deployment instructions.

SSL Certificate Providers

Ensure your site uses HTTPS. Free SSL certificates are available from:

  • Let’s Encrypt (via cPanel, Cloudflare, or Certbot)
  • Cloudflare (free plan includes SSL)
  • ZeroSSL

Real Examples

Example 1: E-commerce Store Using WooCommerce

A small business selling handmade jewelry on WordPress/WooCommerce integrated Razorpay via the official plugin. They enabled UPI and wallet payments, which increased conversions by 32% in the first month. By setting up webhooks, they automated inventory updates and sent SMS confirmations via Twilio. The plugin handled all PCI compliance, and they only needed to configure API keys and test transactions.

Example 2: SaaS Subscription Platform

A B2B startup offering monthly analytics dashboards used Razorpay’s recurring payments feature. They created subscription plans with monthly billing cycles and used webhooks to trigger user access upgrades upon successful payment. When a payment failed, their system sent an email with a retry link and paused service after three failed attempts. This reduced churn by 20% compared to their previous gateway.

Example 3: Food Delivery App with UPI Optimization

A regional food delivery app noticed high cart abandonment during card payments. They switched to Razorpay and prioritized UPI as the default option. They pre-filled user phone numbers (with consent) to reduce typing errors. They also added a “Pay Later” option via Razorpay’s EMI partners. Within two months, payment success rate jumped from 71% to 92%.

Example 4: Educational Platform with Multi-Currency Support

An online learning platform serving students in Nepal and Bangladesh used Razorpay’s multi-currency API to accept USD and BDT. They displayed prices in local currency using real-time exchange rates and allowed users to pay via international cards. Razorpay handled currency conversion and settlement in INR. This expanded their user base by 40% without requiring separate payment processors.

Example 5: Non-Profit Donation Portal

A charity organization wanted to accept recurring donations. They embedded Razorpay’s Checkout button with a “Monthly Donation” toggle. Users could select ₹100, ₹500, or ₹1000/month. The system auto-generated recurring orders and sent thank-you emails with tax receipts. Donations increased by 65% after simplifying the payment flow and adding QR code options for mobile users.

FAQs

Can I use Razorpay without a business account?

No. Razorpay requires a registered business with valid KYC documentation. Personal accounts are not supported for payment processing.

How long does it take to get paid after a transaction?

Settlements typically take T+2 business days (2 days after the transaction date). For example, a payment made on Monday will be credited to your bank account by Wednesday. Some banks may take longer due to processing delays.

Does Razorpay support international payments?

Yes, but only for businesses registered in India. You can accept payments in USD, EUR, GBP, and other currencies, but settlements occur in INR. International cards are supported, but not bank transfers from foreign accounts.

What’s the difference between a payment and an order?

An order is a request you create on your server to define the amount, currency, and description of the transaction. A payment is the actual transfer of funds initiated by the customer. One order can have multiple payment attempts, but only one payment succeeds.

Can I refund a payment manually?

Yes. In your Razorpay Dashboard, go to Payments > Select Transaction > Refund. You can refund partially or fully. Refunds are processed within 5–7 business days and returned to the original payment method.

What happens if a customer’s bank declines the payment?

Razorpay returns a failure code (e.g., “insufficient_funds,” “invalid_card,” “bank_timeout”). Your system should display a user-friendly message and allow retry. Do not block the user — encourage them to try another payment method.

Is Razorpay PCI-DSS compliant?

Yes. Razorpay is certified Level 1 PCI-DSS compliant. You do not need to handle card data directly. All sensitive data is transmitted directly to Razorpay’s servers via encrypted channels.

Can I customize the checkout page?

You can customize the color, logo, and pre-filled user details. However, you cannot modify the core UI elements (like card fields or UPI QR) for security reasons. Full customization requires using Razorpay’s API with a custom frontend.

Do I need to host the payment page on my domain?

No. Razorpay Checkout opens in a secure iframe hosted on Razorpay’s domain. This enhances trust and ensures PCI compliance. Your domain only needs to load the script and handle callbacks.

How do I handle failed webhooks?

Razorpay retries failed webhooks up to 10 times over 48 hours. If your server is down, ensure it’s back online within this window. Use monitoring tools like UptimeRobot to alert you of server outages.

Conclusion

Connecting Razorpay payment to your platform is more than a technical configuration — it’s a gateway to growth, trust, and scalability. By following the step-by-step guide outlined above, you’ve not only integrated a payment system; you’ve built a reliable, secure, and user-friendly transaction pipeline that meets modern digital commerce standards.

Remember: success lies not just in getting payments to go through, but in ensuring they go through smoothly, securely, and with minimal friction for your customers. Use webhooks religiously, validate everything server-side, test exhaustively in sandbox mode, and optimize for mobile. These aren’t optional — they’re essential.

With Razorpay, you’re not just accepting payments — you’re enabling experiences. Whether it’s a student buying an online course, a small business selling handcrafted goods, or a startup scaling its SaaS product, every successful transaction starts with a well-connected payment flow.

Now that you’ve completed this guide, you’re equipped to integrate Razorpay confidently — and to iterate, improve, and expand based on real user behavior. Keep monitoring your analytics, listen to customer feedback, and stay updated with Razorpay’s evolving features. The digital economy moves fast. With the right integration, your business won’t just keep up — it will lead.