Created
August 6, 2020 18:51
-
-
Save afreeland/003026ee17ab0f6de8b3acc4b33f797b to your computer and use it in GitHub Desktop.
Chargify webhook verification middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.use("/chargify", (req, res, next) => { | |
// This request header contains the signature of the hmac sha 256 of the sites secret with the raw body of the request | |
const webhookSignature = | |
req.headers["x-chargify-webhook-signature-hmac-sha-256"]; | |
try { | |
// Your secret shared site key that you got from Chargify earlier | |
// This is a SECRET and should be stored/retrieved in a safe manner, not source control (Kube Secret, etc.,) | |
const sharedKey = "b65ca1b9a6eaea838b7c536ca0ca5fe634214b5d"; | |
// The first step is to create a sha256 of our shared site key | |
const hmac = crypto.createHmac("sha256", sharedKey); | |
// Next we need to update our hmac to utilize the raw body of the request from Chargify | |
hmac.update(req.rawBody); | |
// Now we can obtain the digest to be able to compare it against the signature provided in request header | |
const digest = hmac.digest("hex"); | |
if (digest !== webhookSignature) { | |
// Log/Throw error | |
throw new Error("Webhook signature mismatch"); | |
} | |
} catch (e) { | |
// Log/Throw Error | |
} | |
next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment