Getting started overview
Integrating Razorpay for payment processing involves a sequence of steps designed to ensure secure and functional operation. This guide provides a structured approach, beginning with account setup and API key generation, progressing through the execution of a basic API request, and concluding with common next steps and troubleshooting advice. The primary goal is to enable developers to swiftly move from initial setup to a working integration, handling both test and live transactions securely.
Razorpay operates with a dual environment: a test mode for development and debugging, and a live mode for processing actual payments. All initial development should occur within the test environment to prevent accidental live transactions and to freely experiment with the API. The transition to live mode typically requires activation of the account and replacement of test API keys with live ones.
The core components of a Razorpay integration generally include server-side API calls for order creation and verification, and client-side integration for displaying the payment gateway and handling user interactions. Razorpay offers various SDKs for popular programming languages and platforms, which abstract much of the complexity of direct API interaction and secure handling of sensitive payment data. These SDKs are available for server-side integration languages like PHP, Node.js, Python, Ruby, and Java, as well as mobile and frontend platforms such as Android, iOS, React Native, and Flutter.
Create an account and get keys
The first step in integrating Razorpay is to create a merchant account. This process typically involves providing business details and undergoing a verification process. Upon successful registration, you gain access to the Razorpay Dashboard, which serves as the central hub for managing transactions, retrieving API keys, and configuring payment settings.
- Sign Up for a Razorpay Account: Navigate to the Razorpay homepage and click on 'Sign Up'. Complete the registration form with your business email and other required details. You may need to verify your email address.
- Complete Business Profile: After signing up, log in to your Razorpay Dashboard. You will be prompted to complete your business profile, which includes providing KYC (Know Your Customer) documents. While you can access the test mode without full KYC, activating live mode requires complete verification.
- Generate API Keys: In the Razorpay Dashboard, navigate to Settings > API Keys. Here, you can generate a new set of API keys. Each set consists of a Key ID and a Key Secret. It is crucial to treat the Key Secret as highly confidential, similar to a password, and never expose it in client-side code or public repositories. Razorpay provides separate keys for test mode and live mode. Ensure you are using the correct set of keys for your current development environment. For detailed steps, refer to the Razorpay API Key generation guide.
API Key Management Best Practices
Proper management of API keys is critical for security. Unauthorized access to your Key Secret can compromise your payment processing capabilities and expose sensitive data. Consider the following:
- Environment Variables: Store your API keys in environment variables rather than hardcoding them directly into your application's source code. This practice is widely recommended for sensitive credentials in production environments.
- Access Control: Restrict access to API keys to only those personnel and systems that explicitly require them. Implement role-based access control (RBAC) where possible.
- Key Rotation: Periodically rotate your API keys. Razorpay allows you to generate new keys and revoke old ones from the dashboard. This minimizes the risk associated with a compromised key over time.
- Secure Storage: If keys must be stored, use secure storage mechanisms, such as encrypted vaults or secrets management services, rather than plain text files.
Your first request
To make your first request, you'll typically create an order on your server-side using Razorpay's API and then use the Order ID to initiate a payment on the client-side. This example will use Node.js for the server-side component, as it's one of the primary language examples Razorpay provides, and a basic HTML/JavaScript client for simplicity. Ensure you have Node.js and npm installed.
Prerequisites:
- Node.js installed.
- Your Razorpay Test Key ID and Key Secret.
Step-by-step first request (Node.js & HTML/JS):
1. Server-side (Node.js) - Create an Order
First, set up a simple Node.js application to create an order. Install the Razorpay Node.js SDK:
npm install razorpay express body-parser
Create a file named server.js:
const Razorpay = require('razorpay');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(express.static('public')); // Serve static files from 'public' directory
const razorpay = new Razorpay({
key_id: 'YOUR_KEY_ID', // Replace with your Test Key ID
key_secret: 'YOUR_KEY_SECRET', // Replace with your Test Key Secret
});
app.post('/createOrder', async (req, res) => {
const options = {
amount: req.body.amount, // amount in smallest currency unit (e.g., paise for INR)
currency: 'INR',
receipt: 'order_rcptid_11',
payment_capture: 1 // 1 for automatic capture, 0 for manual
};
try {
const order = await razorpay.orders.create(options);
res.json(order);
} catch (error) {
console.error('Error creating order:', error);
res.status(500).send(error);
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Remember to replace 'YOUR_KEY_ID' and 'YOUR_KEY_SECRET' with your actual test keys. The amount should be in the smallest currency unit (e.g., 100 paise for ₹1 INR).
2. Client-side (HTML/JavaScript) - Initiate Payment
Create a directory named public and inside it, create an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Razorpay Payment Example</title>
</head>
<body>
<h1>Make a Payment</h1>
<button id="rzp-button1">Pay with Razorpay</button>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.getElementById('rzp-button1').onclick = async function (e) {
e.preventDefault();
try {
const response = await fetch('/createOrder', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ amount: 50000 }) // Example: ₹500.00
});
const order = await response.json();
const options = {
key: 'YOUR_KEY_ID', // Replace with your Test Key ID
amount: order.amount, // Amount in smallest currency unit
currency: order.currency,
name: 'Your Company Name',
description: 'Test Payment',
image: 'https://example.com/your_logo.jpg',
order_id: order.id, // This is the order ID obtained from the server
handler: function (response) {
alert('Payment ID: ' + response.razorpay_payment_id);
alert('Order ID: ' + response.razorpay_order_id);
alert('Signature: ' + response.razorpay_signature);
// Here, you would typically verify the payment signature on your server
},
prefill: {
name: 'Gaurav Kumar',
email: '[email protected]',
contact: '9999999999'
},
notes: {
address: 'Razorpay Corporate Office'
},
theme: {
color: '#3399cc'
}
};
const rzp1 = new Razorpay(options);
rzp1.on('payment.failed', function (response) {
alert('Payment Failed: ' + response.error.code);
alert('Description: ' + response.error.description);
alert('Source: ' + response.error.source);
alert('Step: ' + response.error.step);
alert('Reason: ' + response.error.reason);
alert('Order ID: ' + response.error.metadata.order_id);
alert('Payment ID: ' + response.error.metadata.payment_id);
});
rzp1.open();
} catch (error) {
console.error('Error initiating payment:', error);
alert('Failed to initiate payment.');
}
};
</script>
</body>
</html>
Again, replace 'YOUR_KEY_ID' with your Test Key ID. The checkout.js script is essential for displaying the Razorpay payment gateway.
3. Run the application:
node server.js
Open your browser to http://localhost:3000. Click the 'Pay with Razorpay' button to initiate a test payment. You will see the Razorpay checkout modal where you can use test card details to simulate a successful or failed transaction. For a list of test card numbers and details, refer to the Razorpay documentation.
| Step | What to do | Where |
|---|---|---|
| 1. Install Dependencies | npm install razorpay express body-parser |
Your project directory (terminal) |
| 2. Create Server Script | Set up server.js with API keys and /createOrder endpoint. |
server.js file |
| 3. Create Client HTML | Set up public/index.html to call /createOrder and open Razorpay checkout. |
public/index.html file |
| 4. Run Server | node server.js |
Your project directory (terminal) |
| 5. Test Payment | Open browser to http://localhost:3000 and click 'Pay'. |
Web browser |
Common next steps
After successfully completing your first test payment, several key areas require attention to transition to a production-ready system:
- Verify Payments (Server-side): The client-side
handlerfunction only provides payment details. It is critical to verify the payment signature on your server to ensure the payment is legitimate and has not been tampered with. This involves using your Key Secret to hash the payment details received from Razorpay and comparing it with the signature provided. This prevents fraudulent requests from marking payments as successful. - Handle Webhooks: Implement Razorpay webhooks to receive real-time notifications about payment status changes (e.g., successful payment, failed payment, refund processed). Webhooks are crucial for updating your internal order status, triggering fulfillment processes, and handling asynchronous payment flows. Similar to API calls, webhook payloads should be verified using a secret to ensure authenticity, as detailed in the Cloudflare webhook signature verification guide.
- Explore Advanced Features: Depending on your business needs, explore Razorpay's other offerings such as Subscriptions for recurring payments, Payment Links for sending payment requests, or Route for splitting payments in a marketplace model. The Razorpay comprehensive documentation provides detailed guides for each product.
- Go Live: Once your integration is thoroughly tested, complete your KYC documents in the Razorpay Dashboard and request to activate your live account. Generate and use your live API keys for production transactions.
- Error Handling and Logging: Implement robust error handling and logging mechanisms throughout your integration. This includes logging API request and response details, payment failures, and webhook processing issues to aid in debugging and support.
- Security Audit: Regularly review your integration for security vulnerabilities, especially concerning API key management and handling of sensitive payment information. Ensure compliance with relevant security standards like PCI DSS, which Razorpay itself is compliant with at Level 1.
Troubleshooting the first call
Encountering issues during the initial integration is common. Here are some typical problems and their solutions:
- Invalid API Keys:
- Symptom: API requests return authentication errors (e.g.,
401 Unauthorized). - Solution: Double-check that you are using the correct Key ID and Key Secret. Ensure you are using test keys for the test environment and live keys for the live environment. Copy-pasting errors are common. Verify there are no leading or trailing spaces.
- Symptom: API requests return authentication errors (e.g.,
- Incorrect Amount Format:
- Symptom: Payments fail or show unexpected amounts.
- Solution: Razorpay expects the amount in the smallest currency unit (e.g., paise for INR). For ₹500, the amount should be
50000. Verify your amount calculation logic.
- CORS Issues (Client-side):
- Symptom: Browser console shows Cross-Origin Resource Sharing errors when the client tries to communicate with your server or Razorpay.
- Solution: Ensure your server is correctly configured to handle CORS. If you're using Express, middleware like
corscan help. For direct Razorpay checkout.js calls, Razorpay handles CORS internally, but your server-side endpoints need proper configuration.
- Network Connectivity:
- Symptom: Requests time out or fail to connect.
- Solution: Verify your server has outbound internet access to reach Razorpay's API endpoints. Check firewall rules if applicable.
- Missing Required Parameters:
- Symptom: API requests return errors indicating missing fields.
- Solution: Consult the Razorpay API reference for the specific endpoint you are calling to ensure all mandatory parameters are included and correctly formatted.
- Webhook Signature Mismatch:
- Symptom: Your server rejects legitimate webhooks.
- Solution: Ensure your webhook secret is correctly configured in Razorpay Dashboard and that your server-side verification logic precisely matches Razorpay's webhook signature verification process. Even minor discrepancies in encoding or hashing can cause mismatches.
- Test Mode vs. Live Mode Confusion:
- Symptom: Payments are not showing up in the expected dashboard section, or live payments are processed with test card details.
- Solution: Always confirm which set of API keys (test or live) you are using and that your Razorpay Dashboard view corresponds to that environment. The dashboard usually has a clear toggle between 'Test Mode' and 'Live Mode'.