Back

Quick Guide to Implementing Webhooks in GoCardless

Sep 14, 20247 minute read

Hey there, fellow JavaScript dev! Ready to supercharge your GoCardless integration with webhooks? Let's dive right in and get those real-time updates flowing!

Introduction

Webhooks are like the cool kids of API integrations - they bring the party to you instead of making you constantly check for updates. In GoCardless, they're your ticket to instant notifications about payments, mandates, and more. We'll focus on setting this up for your user-facing integration, so you can keep your customers in the loop without breaking a sweat.

Prerequisites

Before we start, make sure you've got:

  • A GoCardless account with API credentials (you're probably already sorted here)
  • Node.js installed (because, duh, we're JavaScript devs)
  • A basic grasp of Express.js (we'll use it to handle those incoming webhooks)

Got all that? Great! Let's code.

Setting Up Webhook Endpoints

First things first, let's create a simple Express server to catch those webhook events:

const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.post('/webhooks', (req, res) => { // We'll handle the magic here soon console.log('Webhook received!', req.body); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));

Easy peasy, right? This sets up a basic endpoint at /webhooks that'll receive POST requests from GoCardless.

Configuring Webhooks in GoCardless

Now, hop over to your GoCardless Dashboard and let's tell it where to send those juicy webhook events:

  1. Navigate to Developer > Webhooks
  2. Click "Add endpoint"
  3. Enter your webhook URL (e.g., https://your-domain.com/webhooks)
  4. Select the events you want to receive (pro tip: start with all of them and narrow down later)

Want to do this programmatically? Here's a quick snippet using the GoCardless Node.js library:

const gocardless = require('gocardless-nodejs'); const client = gocardless( process.env.GOCARDLESS_ACCESS_TOKEN, gocardless.environments.sandbox // or .live for production ); client.webhooks.create({ url: 'https://your-domain.com/webhooks', actions: ['payments', 'mandates', 'subscriptions'] }).then(webhook => console.log('Webhook created:', webhook));

Handling Webhook Events

Now for the fun part - actually doing something with those events! First, let's verify that the webhook is legit:

const crypto = require('crypto'); app.post('/webhooks', (req, res) => { const signature = req.headers['webhook-signature']; const body = JSON.stringify(req.body); const computedSignature = crypto .createHmac('sha256', process.env.GOCARDLESS_WEBHOOK_SECRET) .update(body) .digest('hex'); if (computedSignature !== signature) { return res.status(401).send('Invalid signature'); } // Process the webhook handleWebhook(req.body); res.sendStatus(200); });

Processing Different Event Types

Now let's handle those events like a pro:

function handleWebhook(payload) { const { events } = payload; events.forEach(event => { switch(event.resource_type) { case 'payments': handlePaymentEvent(event); break; case 'mandates': handleMandateEvent(event); break; // Add more cases as needed default: console.log('Unhandled event type:', event.resource_type); } }); } function handlePaymentEvent(event) { console.log(`Payment ${event.action}:`, event.links.payment); // Update your database, notify the user, etc. } function handleMandateEvent(event) { console.log(`Mandate ${event.action}:`, event.links.mandate); // Update your database, notify the user, etc. }

Error Handling and Retries

Nobody's perfect, so let's plan for when things go wrong:

app.post('/webhooks', async (req, res) => { try { // Verification and processing logic here res.sendStatus(200); } catch (error) { console.error('Webhook processing failed:', error); // Respond with 500 to trigger a retry from GoCardless res.sendStatus(500); } });

GoCardless will automatically retry failed webhooks, so make sure your logic can handle duplicate events gracefully!

Testing Webhooks

Want to test without waiting for real events? GoCardless has got your back with their webhook tester. But for local testing, you can also mock events:

const mockWebhook = { events: [{ id: 'EV123', created_at: '2023-04-20T12:00:00.000Z', resource_type: 'payments', action: 'created', links: { payment: 'PM123' } }] }; // Use this to test your handleWebhook function handleWebhook(mockWebhook);

Security Considerations

Keep it locked down, folks:

  • Always use HTTPS for your webhook endpoint
  • Consider IP whitelisting if your setup allows it
  • Rotate your webhook secret periodically

Conclusion

And there you have it! You're now ready to handle GoCardless webhooks like a champ. Remember, webhooks are your friends - they'll keep your app in sync and your users happy with real-time updates.

Additional Resources

Want to dive deeper? Check out:

Now go forth and webhook all the things! Happy coding! 🚀