Skip to content

Instantly share code, notes, and snippets.

@jamiesoncj jamiesoncj/gc-webhook.js
Last active Feb 14, 2018

What would you like to do?
GoCardless Node / Express signature verification middleware
const crypto = require('crypto');
* Express middleware to validate incoming webhook request from Gocardless
* @param {*} req Express request
* @param {*} res Express response
* @param {*} next Next middleware function if succeeds
function verifyGocardlessWebhook(req, res, next) {
if (!req.headers['webhook-signature']) {
// throw bad request
res.json({ message: '"Webhook-signature" header not set' });
return null;
// assuming req has been passed through express JSON bodyparser
const bodyAsString = JSON.stringify(req.body, null, 0); // needs to be stringified
const secret = config.gocardlessWebhookSecret; // get this from environment variables
const hash = crypto.createHmac('sha256', secret).update(bodyAsString).digest('hex');
if (hash !== req.headers['webhook-signature']) {
// signatures do not match
res.status(498); // 498 INVALID TOKEN
res.json({ message: 'Invalid token' });
return null;
// otherwise, looks good, continue to next middleware
return next();

This comment has been minimized.

Copy link

commented Feb 14, 2018

Looks good. I approve this snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.