Razorpay is one of the leading payment gateways, offering developers tools to integrate online payments seamlessly into their applications. Webhooks in Razorpay allow the application to receive real-time notifications for payment-related events like payment.captured, refund.processed, or order.paid. This feature is crucial for automating workflows like order updates, sending payment confirmations, or initiating refunds.
This guide walks us through the complete process of setting up Razorpay webhooks with Node.js, including creating and configuring webhook endpoints, signature verification for security, and practical examples.
1. Setting Up Razorpay Webhooks
Step 1: Generate API Keys
- Log in to a Razorpay Dashboard.
- Navigate to Settings > API Keys.
- Generate and save key ID and Key Secret. These credentials will be used to authenticate API calls.
Step 2: Install Required Packages
Install the necessary Node.js packages:
npm install express razorpay crypto body-parser
Step 3: Initialize Razorpay in Node.js
Create a Razorpay instance using wer API credentials:
const Razorpay = require('razorpay');
const razorpay = new Razorpay({
key_id: 'weR_KEY_ID',
key_secret: 'weR_KEY_SECRET',
});
2. Creating a Webhook Endpoint
Step 1: Setup a Basic Express Server
Create an Express server to handle incoming webhook requests:
const express = require('express');
const app = express();
app.use(express.json()); // Parse JSON payloads
Step 2: Add Webhook Endpoint with Signature Verification
Razorpay sends a x-razorpay-signature header with each webhook to verify its authenticity. Use this header to validate incoming requests:
const crypto = require('crypto');
app.post('/webhook', (req, res) => {
const secret = 'weR_WEBHOOK_SECRET';
// Compute HMAC signature
const sign = crypto.createHmac('sha256', secret);
sign.update(JSON.stringify(req.body));
const digest = sign.digest('hex');
// Verify signature
if (digest === req.headers['x-razorpay-signature']) {
console.log('Webhook verified:', req.body);
// Handle event logic here
if (req.body.event === 'payment.captured') {
console.log('Payment Captured:', req.body.payload.payment.entity);
}
} else {
console.log('Invalid signature');
}
res.status(200).send('OK');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
3. Configuring Webhooks in Razorpay Dashboard
- Log in to the Razorpay Dashboard.
- Go to Settings > Webhooks and click Add New Webhook.
- Add the URL of a webhook endpoint, e.g., https://werdomain.com/webhook.
- Set the Webhook Secret (same as in wer code) for signature verification.
- Select events like payment.captured or order.paid to listen to.
- Save the configuration.
4. Testing Webhooks
To test a webhook:Use ngrok to expose wer local development server:
ngrok http 3000
5. Examples
Example 1: Logging Payment Captured Events
if (req.body.event === 'payment.captured') {
const payment = req.body.payload.payment.entity;
console.log('Payment Details:', {
id: payment.id,
amount: payment.amount,
status: payment.status,
});
}
Example 2: Updating Order Status in the Database
if (req.body.event === 'order.paid') {
const orderId = req.body.payload.order.entity.id;
// Update order status in the database
console.log(`Order ${orderId} marked as paid`);
}
Example 3: Idempotency for Duplicate Events
const processedEvents = new Set();
if (!processedEvents.has(req.body.id)) {
processedEvents.add(req.body.id);
// Process the event
}
Conclusion
Integrating Razorpay webhooks with a Node.js application automates the payment processing workflow. By validating signatures and handling idempotency, we can ensure secure and reliable event handling. With this setup, wer application can respond to payment events in real-time, streamlining operations and improving user experience.
This guide ensures we have the foundational setup to handle Razorpay webhooks effectively. For additional details, refer to the Razorpay Documentation.