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 is not just a technical task; it’s a strategic move that enhance

Nov 10, 2025 - 09:05
Nov 10, 2025 - 09:05
 2

How to Connect Razorpay Payment

Razorpay is one of Indias 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 is not just a technical task; its a strategic move that enhances customer experience, reduces cart abandonment, and accelerates revenue growth. Whether youre running an e-commerce store, a SaaS platform, a subscription service, or a marketplace, integrating Razorpay correctly ensures secure, reliable, and scalable payment processing.

This guide provides a comprehensive, step-by-step walkthrough on how to connect Razorpay payment systems to your digital platform. We cover everything from account setup and API integration to testing, security best practices, and real-world implementation examples. By the end of this tutorial, youll have the confidence and knowledge to deploy Razorpay confidently whether youre a developer, business owner, or technical project manager.

Step-by-Step Guide

Step 1: Create a Razorpay Account

Before you can integrate Razorpay, you need an active merchant account. Visit razorpay.com and click on Sign Up in the top-right corner. Youll be prompted to enter your business details, including your legal business name, email address, phone number, and industry type.

Choose the appropriate account type Individual for freelancers or sole proprietors, or Business for registered companies. If youre registering as a business, youll need to upload supporting documents such as your PAN card, GST certificate, bank account details, and proof of business address. Razorpay typically verifies these documents within 2448 hours.

Once your account is approved, youll be redirected to the Razorpay Dashboard. This is your control center for managing payments, viewing transaction reports, setting up webhooks, and generating API keys. Take a moment to familiarize yourself with the dashboard layout youll return here frequently during integration and troubleshooting.

Step 2: Generate API Keys

API keys are the credentials your application uses to communicate securely with Razorpays servers. To generate them, navigate to the Settings section in your dashboard, then select API Keys.

Youll see two keys:

  • Key ID A public identifier used to authenticate your requests.
  • Key Secret A private key that must be kept secure and never exposed in client-side code.

Click Generate Key to create a new pair. Razorpay will display both keys only once make sure to copy and store them securely. We recommend using a password manager or encrypted configuration file. Never commit these keys to public repositories like GitHub.

For security, you can also create separate keys for test and live environments. This allows you to test integrations without affecting real transactions.

Step 3: Choose Your Integration Method

Razorpay offers multiple integration options depending on your technical setup and requirements. The three primary methods are:

  1. Checkout (Hosted Payment Page) A pre-built, responsive payment form hosted by Razorpay. Ideal for non-developers or businesses seeking quick deployment.
  2. API Integration (Custom Checkout) Full control over the payment UI using Razorpays REST APIs. Best for advanced developers building custom experiences.
  3. Plugins and SDKs Pre-built integrations for platforms like WordPress, Shopify, Magento, WooCommerce, and more.

For most users, we recommend starting with the Checkout method due to its simplicity and built-in compliance with PCI-DSS standards. If you need a fully branded experience or complex logic, proceed with API integration.

Step 4: Integrate Razorpay Checkout

Integrating Razorpay Checkout involves embedding a small JavaScript snippet into your website. Heres how:

First, locate the HTML page where you want to add the payment button typically a checkout or product purchase page. Add the following code inside the <body> tag:

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

<button id="payment-button">Pay Now</button>

<script>

var options = {

key: "YOUR_KEY_ID", // Enter your Key ID here

amount: 50000, // Amount in paise (e.g., ?500 = 50000 paise)

currency: "INR",

name: "Your Business Name",

description: "Product Purchase",

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

order_id: "", // Will be generated via backend

handler: function (response) {

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

// Send this payment_id to your server for verification

},

prefill: {

name: "John Doe",

email: "john@example.com",

contact: "9876543210"

},

theme: { color: "

3399cc"

}

};

var rzp1 = new Razorpay(options);

document.getElementById('payment-button').onclick = function(e){

rzp1.open();

e.preventDefault();

}

</script>

Important: Replace YOUR_KEY_ID with your actual Key ID from the Razorpay dashboard. The amount field must be in paise (1 INR = 100 paise). For dynamic pricing, youll need to fetch the amount from your backend server.

The order_id field is critical. Razorpay requires a unique order ID for every transaction. You cannot hardcode this it must be generated server-side. Well cover this in the next step.

Step 5: Create an Order on Your Server

For security and accuracy, Razorpay mandates that all payment orders be created on your backend server not from the frontend. This prevents tampering with amounts or currency.

Heres an example using Node.js and 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, currency = 'INR' } = req.body;

const options = {

amount: amount * 100, // Convert to paise

currency: currency,

receipt: 'receipt_' + Date.now(),

payment_capture: 1 // Auto-capture payment

};

try {

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

res.json({

id: order.id,

currency: order.currency,

amount: order.amount

});

} catch (error) {

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

}

});

On the frontend, before opening the checkout, make an API call to your server to fetch the order ID:

fetch('/create-order', {

method: 'POST',

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

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

})

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

.then(data => {

options.order_id = data.id;

const rzp1 = new Razorpay(options);

rzp1.open();

});

This ensures that the amount and currency are validated by your server before payment initiation.

Step 6: Handle Payment Success and Webhooks

After a successful payment, Razorpay redirects the user back to your site and triggers the handler function in your JavaScript. However, relying solely on frontend callbacks is insecure users can manipulate them.

To ensure payment authenticity, implement Razorpay webhooks. A webhook is an HTTP POST request that Razorpay sends to your server whenever a payment event occurs such as success, failure, or refund.

To set up a webhook:

  1. Go to your Razorpay Dashboard > Settings > Webhooks.
  2. Click Add Webhook.
  3. Enter the URL where you want to receive notifications (e.g., https://yourdomain.com/webhook).
  4. Choose events to subscribe to: payment.captured, payment.failed, refund.created, etc.
  5. Generate a webhook secret and save it securely.

On your server, create an endpoint to verify and process webhook data:

const crypto = require('crypto');

app.post('/webhook', (req, res) => {

const webhookSecret = 'YOUR_WEBHOOK_SECRET';

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

const sha256Hash = crypto

.createHmac('sha256', webhookSecret)

.update(JSON.stringify(req.body))

.digest('hex');

if (signature === sha256Hash) {

// Process the payment event

const event = req.body.event;

const payload = req.body.payload;

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

const paymentId = payload.payment.entity.id;

const orderId = payload.payment.entity.order_id;

// Update your database: mark order as paid

console.log(Payment ${paymentId} captured for order ${orderId});

}

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

} else {

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

}

});

Always validate the webhook signature this prevents malicious actors from sending fake events.

Step 7: Test in Sandbox Mode

Before going live, test your integration thoroughly using Razorpays test mode. In your dashboard, toggle the switch to Test Mode. Youll receive test API keys (starting with rzp_test_) and can use test cards and UPI IDs provided in Razorpays documentation.

Test scenarios to cover:

  • Successful payment
  • Failed payment (insufficient funds, expired card)
  • Cancelled payment
  • Webhook delivery and verification
  • Refund initiation

Use Razorpays test card numbers:

  • Card: 4111 1111 1111 1111
  • Expiry: Any future date
  • CVC: 123
  • OTP: 123456 (for UPI or net banking)

Verify that your backend correctly updates order status and sends confirmation emails or SMS after a successful test payment.

Step 8: Go Live

Once testing is complete and all scenarios pass, switch to live mode in your Razorpay dashboard. Replace your test API keys with your live keys (starting with rzp_live_).

Update your server-side code and frontend scripts to use live endpoints. Double-check:

  • All API keys are switched
  • Webhook URL is correct and accessible over HTTPS
  • SSL certificate is active on your domain
  • Payment amounts are in INR (or your supported currency)

Monitor your dashboard closely for the first few transactions. Check for errors, failed payments, or webhook delivery issues. Enable email alerts for payment events to stay informed.

Best Practices

Always Use HTTPS

Razorpay requires all integrations to use HTTPS. Never deploy payment forms over HTTP. Modern browsers block mixed content, and insecure connections compromise PCI-DSS compliance. Obtain an SSL certificate from a trusted provider like Lets Encrypt, Cloudflare, or your hosting provider.

Never Expose Secret Keys

Your Key Secret and Webhook Secret must never appear in client-side code, public repositories, or logs. Use environment variables (e.g., .env files) and restrict access to your server. In Node.js, use dotenv; in PHP, use $_ENV; in Python, use python-dotenv.

Validate Amounts Server-Side

Always recalculate the payment amount on your server before capturing funds. Never trust the amount sent from the frontend. A malicious user could alter the value in browser DevTools. Your backend should fetch the price from your database or product catalog.

Implement Order ID Uniqueness

Each order must have a unique ID. Use UUIDs or timestamp-based IDs to avoid collisions. Never reuse order IDs even for failed payments. Razorpay treats duplicate order IDs as errors.

Handle Timeouts and Retries Gracefully

Network issues can cause delays in payment confirmation. Implement retry logic on your server for webhook processing. If a webhook fails, retry up to 3 times with exponential backoff. Log all failures for debugging.

Use Razorpays SDKs When Possible

While raw API calls work, Razorpay provides official SDKs for popular languages: Node.js, Python, PHP, Ruby, Java, and .NET. These SDKs handle authentication, error responses, and serialization automatically. They reduce bugs and save development time.

Enable Two-Factor Authentication (2FA)

Secure your Razorpay dashboard by enabling 2FA. Go to Settings > Security and link your phone number or authenticator app. This prevents unauthorized access even if your password is compromised.

Monitor Transaction Reports Daily

Check your Razorpay dashboard daily for anomalies: duplicate payments, unusually large transactions, or failed payments from the same IP. Set up custom alerts for high-value transactions or sudden drops in success rates.

Keep Your Integration Updated

Razorpay frequently updates its APIs and SDKs. Subscribe to their developer newsletter and check the Razorpay Documentation regularly. Outdated integrations may break due to deprecated endpoints or security patches.

Comply with RBI and PCI-DSS Guidelines

As a merchant in India, you must comply with Reserve Bank of India (RBI) guidelines on payment aggregation. Razorpay handles PCI-DSS compliance for you when using Checkout or their APIs, but you must ensure your server doesnt store card data. Never log or store full card numbers, CVV, or magnetic stripe data.

Tools and Resources

Razorpay Official Documentation

The most reliable source for integration details is Razorpays official documentation: https://razorpay.com/docs. It includes code samples in multiple languages, API reference guides, error codes, and migration guides.

Razorpay Dashboard

Your primary interface for managing payments, generating reports, setting up webhooks, and viewing transaction history. Accessible at https://dashboard.razorpay.com.

Razorpay Test Cards and UPI IDs

For testing without real money, use the following:

  • Card: 4111 1111 1111 1111 (Visa), 5555 5555 5555 4444 (Mastercard)
  • Expiry: Any future date
  • CVC: 123
  • UPI: test@upi
  • OTP: 123456

Postman Collection

Download Razorpays official Postman collection to test API endpoints without writing code: https://documenter.getpostman.com/view/11023216/TzZsJX9W.

Webhook Tester 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 webhooks to your development machine.

Browser Developer Tools

Use Chrome DevTools or Firefox Developer Tools to inspect network requests, check for JavaScript errors, and verify that the Razorpay script loads correctly. Look for failed API calls or CORS errors.

Code Repositories and GitHub Examples

Razorpay maintains official GitHub repositories with working examples:

These repositories include sample apps, error handling patterns, and deployment scripts.

Analytics and Monitoring Tools

Integrate your payment system with tools like Google Analytics, Mixpanel, or Datadog to track conversion rates, drop-off points, and payment success metrics. This helps optimize your checkout flow over time.

Payment Gateway Comparison Tools

Before choosing Razorpay, compare it with alternatives like PayU, CCAvenue, Stripe, or PayPal using tools like G2 or Trustpilot. Look at fees, uptime, support, and feature sets.

Real Examples

Example 1: E-Commerce Store Using WooCommerce

A small online fashion retailer uses WooCommerce to sell clothing. They installed the official Razorpay for WooCommerce plugin from the WordPress plugin directory. After activating the plugin, they entered their live Key ID and Key Secret in the settings.

The plugin automatically adds Razorpay as a payment option at checkout. Customers can pay via UPI, cards, or wallets without leaving the site. The store owner receives real-time notifications and order updates in their WordPress dashboard.

They enabled webhooks to sync payment status with their inventory system. When a payment is captured, the plugin reduces stock automatically and sends an order confirmation email.

Example 2: SaaS Subscription Platform Using Node.js

A startup offering a monthly subscription service for project management tools integrated Razorpay using the Node.js SDK. They created a recurring billing system using Razorpays subscriptions API.

When a user signs up, the backend creates a subscription plan (e.g., ?499/month) and links it to the customers email. Razorpay automatically charges the customer every 30 days. If a payment fails, the system sends a retry notification and suspends access after 3 failed attempts.

They use webhooks to update user subscription status in their database. Failed payments trigger a customer support email with a payment link. Successful payments unlock premium features instantly.

Example 3: Food Delivery App Using React Native

A food delivery startup built a mobile app using React Native. They used the Razorpay React Native SDK to embed a payment screen directly in the app.

When a user places an order, the app sends a request to their backend to generate an order ID. The backend returns the order details, which the app uses to launch the Razorpay payment modal. After payment, the app receives a success callback and updates the order status.

The team implemented fingerprint and face ID authentication for returning users to improve conversion. They also added a Pay Later option using Razorpays EMI feature, increasing average order value by 22%.

Example 4: Educational Platform with Multiple Currencies

An online learning platform serving students across India and Southeast Asia uses Razorpay to accept payments in INR, USD, and SGD. They configured multiple currency support in their backend and dynamically set the currency based on the users location.

Razorpays auto-conversion feature handles exchange rates in real time. The platform displays prices in the users local currency while settling funds in INR. They use webhooks to reconcile payments and generate tax invoices automatically.

FAQs

Can I connect Razorpay without a business registration?

Yes, individuals can register as sole proprietors using their PAN card and bank account. However, certain features like recurring payments or international transactions may require a registered business entity.

What are Razorpays transaction fees?

Razorpay charges 2% per transaction for domestic payments (cards, UPI, wallets) and 3% for international payments. These rates may vary based on volume. Check the official pricing page for updated rates.

How long does it take to get paid?

Razorpay settles funds to your bank account within 23 business days after payment capture. For high-volume merchants, faster settlement (T+1) can be requested.

Can I accept international payments?

Yes, Razorpay supports payments in 10+ currencies. However, you must apply for international payment enablement through your dashboard and comply with additional KYC requirements.

What happens if a payment fails?

Failed payments are logged in your dashboard. You can retry manually or use Razorpays automatic retry feature for recurring payments. Notify customers via email or SMS to update their payment method.

Do I need to store card details?

No. Razorpay handles all sensitive data securely. You only receive a tokenized reference after payment. Never store card numbers it violates PCI-DSS rules and exposes you to legal risk.

Can I customize the payment page?

Yes, with Razorpay Checkout, you can customize the logo, color theme, and pre-filled customer details. For full control, use API integration to build a custom UI.

Is Razorpay compatible with mobile apps?

Yes. Razorpay provides SDKs for Android, iOS, React Native, and Flutter. You can embed payments directly into your native or hybrid apps.

How do I issue refunds?

You can initiate partial or full refunds from your Razorpay dashboard or via API. Refunds are processed within 57 business days and credited to the original payment method.

What if my webhook isnt firing?

Check that your server is accessible over HTTPS, the webhook URL is correctly entered, and your firewall isnt blocking Razorpays IP addresses. Use webhook.site to test if requests are reaching your server.

Conclusion

Connecting Razorpay payment systems to your digital platform is a powerful way to unlock faster conversions, improve customer trust, and scale your business with confidence. By following the steps outlined in this guide from account creation and API key generation to server-side order creation and webhook validation you ensure a secure, reliable, and seamless payment experience for your users.

Remember: integration is not a one-time task. Regularly monitor transactions, update your code, test new features, and stay informed about Razorpays evolving offerings. Whether youre a startup founder or a seasoned developer, Razorpay provides the tools to turn payment complexity into competitive advantage.

Start small test with a single product or service. Once youre confident, expand to subscriptions, multi-currency support, and automated reconciliation. With the right setup, Razorpay doesnt just process payments it becomes the engine of your digital commerce growth.