Verify webhook signatures

Anyone who knows your webhook URL could send it fake requests. Every request from TijaraQ is signed with your webhook's signing secret. Check the signature, and ignore any request that doesn't match.

"A signing secret is generated automatically once this webhook is created - use it to verify the X-Webhook-Signature header on requests you receive."

How it's signed

Header

X-Webhook-Signature: sha256=<signature>

Algorithm

HMAC-SHA256

Signed content

The raw request body, exactly as received

Key

Your webhook's Signing secret

Verify it

  1. Read the raw body. Don't parse and re-encode the JSON first.

  2. Calculate the HMAC-SHA256 of the body, using your signing secret.

  3. Add sha256= in front, and compare it with the header using a constant-time comparison.

  4. If they don't match, reply with 401 and ignore the request.

Node.js

const crypto = require('crypto');

function isValid(rawBody, header, secret) {
  const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
  return header && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(header));
}

PHP

$expected = 'sha256=' . hash_hmac('sha256', $rawBody, $secret);
$valid = hash_equals($expected, $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '');

Python

import hmac, hashlib

expected = 'sha256=' + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
valid = hmac.compare_digest(expected, header)

Tips