Skip to content

Instantly share code, notes, and snippets.

@jamiesoncj jamiesoncj/gc-webhook.js
Last active Jun 14, 2019

Embed
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.status(httpStatus.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();
}
@geekygrappler

This comment has been minimized.

Copy link

commented Feb 14, 2018

Looks good. I approve this snippet.

@bensbenj

This comment has been minimized.

Copy link

commented Jun 14, 2019

Good job! Thank you

@jamiesoncj

This comment has been minimized.

Copy link
Owner Author

commented Jun 14, 2019

@bensbenj you are most welcome. Glad it helped you

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.