Hey there, fellow JavaScript dev! Ready to level up your Razorpay integration with webhooks? Let's dive right in and get those real-time updates flowing!
Webhooks are like your app's personal news feed from Razorpay. They'll ping you whenever something interesting happens, like a successful payment or a refund. Today, we're focusing on setting this up for your user-facing integration. Trust me, your users (and your sanity) will thank you!
Before we start, make sure you've got:
Got all that? Great! Let's code!
First things first, let's create a simple Express server to receive those juicy webhook events:
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.post('/webhook', (req, res) => { // We'll fill this in soon! console.log('Webhook received:', req.body); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));
Easy peasy, right? We've got our server up and running, ready to receive those webhook events.
Now, hop over to your Razorpay dashboard and let's tell it where to send those events:
https://your-domain.com/webhook
)payment.captured
, payment.failed
)Alright, time for the fun part! Let's verify that incoming webhook and process those events:
const crypto = require('crypto'); app.post('/webhook', (req, res) => { const shasum = crypto.createHmac('sha256', 'YOUR_WEBHOOK_SECRET'); shasum.update(JSON.stringify(req.body)); const digest = shasum.digest('hex'); if (digest === req.headers['x-razorpay-signature']) { console.log('Request is legit'); // Process the webhook event switch (req.body.event) { case 'payment.captured': console.log('Payment successful'); // Update your database, send a confirmation email, etc. break; case 'payment.failed': console.log('Payment failed'); // Notify the user, log the failure, etc. break; // Add more cases as needed } res.sendStatus(200); } else { console.log('Invalid signature'); res.sendStatus(400); } });
Time to put on your QA hat! Head to the Razorpay dashboard and use their webhook testing tool. Simulate some events and watch your server light up like a Christmas tree!
A few pro tips to keep your webhook game strong:
Running into problems? Here are some usual suspects:
And there you have it! You're now a Razorpay webhook wizard. Your app is ready to handle real-time payment updates like a champ. Remember, practice makes perfect, so keep experimenting and refining your implementation.
Want to see it all put together? Check out this GitHub repo for a complete example.
Happy coding, and may your payments always be successful! 🚀💰