Webhook signature validation in NodeJS
-
I’m trying to connect my NodeJS app with Woocommerce Webhooks and everything is working fine so far but when trying to validate the signature in the
x-wc-webhook-signatureheader it doesn’t match.Here is part of the code I’m using:
app.post('/webhook', express.raw({ type: 'application/json' }), (request, response) => {
const isWebhookValid = isWoocommerceWebhookValidated(request)
if (isWebhookValid) {
console.log('Webhook signature is valid')
response.status(200).send('Webhook signature is valid')
} else {
console.log('Webhook signature is invalid')
response.status(401).send('Webhook signature is invalid')
}
})Here is the logic behind the
isWoocommerceWebhookValidatedexport function isWoocommerceWebhookValidated(request: Request): boolean {
const WC_WEBHOOK_SIGNATURE_HEADER = 'x-wc-webhook-signature'
const signature = request.headers[WC_WEBHOOK_SIGNATURE_HEADER] ?? ''
const secret = process.env.WOOCOMMERCE_WEBHOOK_SECRET ?? ''
if (!signature || !secret) {
console.log('Missing signature or secret')
return false
}
const payload = request.body
const hash = crypto.createHmac('sha256', secret).update(payload, 'utf8').digest('base64')
return hash === signature
}These are the hash and signature result logged in console:
signature: 'QtVYdnEQDf0+lcxkjGgSXxtuAqkM/3L6GYvhgjY+DEE='hash: 'LUsjH1Gx2DaSLHIg5NkoTx03mUsHdL7+RlPiIYF6I0c='
I’m 100% sure that both secrets in Woocommerce and in my environment variable matches. Any ideas on how to solve the issue?
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
The topic ‘Webhook signature validation in NodeJS’ is closed to new replies.