Developers

Webhook Signature Verification: How to Check That a Webhook Is Genuine

How webhook signature verification works and how to implement it correctly: HMAC signatures, using the raw body, constant-time comparison, timestamps against replay attacks, secret rotation, and code in Node.js, PHP and Python.

Webhook Signature Verification: How to Check That a Webhook Is Genuine
On this page
  1. How webhook signatures work
  2. The rules that make it work
  3. 1. Sign the raw body
  4. 2. Compare in constant time
  5. 3. Match the provider's format exactly
  6. 4. Reject before doing anything
  7. Code examples
  8. Node.js (Express)
  9. PHP
  10. Python (Flask)
  11. Shared-secret headers
  12. Protect against replay
  13. Managing the secret
  14. Testing verification
  15. After verification
  16. A worked example

A webhook endpoint is a public URL that does something important when it receives a request: marks an order paid, sends a reply, updates a booking. Anyone who finds that URL can send it requests too. Webhook signature verification is how your server tells a genuine event from a forged one. It takes a few lines of code, and it's one of the most common things developers get subtly wrong.

How webhook signatures work#

The provider and your server share a secret. For each webhook, the provider computes an HMAC, a keyed hash of the request body using that secret, and sends it in a header. Your server computes the same HMAC over the body it received and accepts the request only if the two match.

Because only you and the provider know the secret, nobody else can produce a valid signature, and any change to the body, even one character, produces a different one. HMAC itself is defined in RFC 2104; most providers use HMAC with SHA-256.

The rules that make it work#

1. Sign the raw body#

Compute the HMAC over the exact bytes you received, before any parsing. If your framework parses the JSON and you re-encode it, spacing, key order or escaping can change, and the signature won't match even for a genuine request. This is the number one cause of "signature always fails".

2. Compare in constant time#

A normal string comparison stops at the first different character, which can leak information through timing. Use your language's constant-time comparison: crypto.timingSafeEqual in Node.js, hash_equals in PHP, hmac.compare_digest in Python.

3. Match the provider's format exactly#

Check the documentation for the header name, whether the value has a prefix such as sha256=, and whether it's hex or base64 encoded. A correct HMAC in the wrong encoding still fails.

4. Reject before doing anything#

Verify first, then parse and act. Return 401 or 403 for an invalid signature and do nothing else.

Code examples#

These follow the SMS Gora format, where the header X-SmsGora-Signature holds sha256= followed by a hex HMAC-SHA256 of the raw body.

Node.js (Express)#

import crypto from 'node:crypto';

app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  const expected = 'sha256=' + crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET)
    .update(req.body)                      // raw Buffer
    .digest('hex');
  const got = req.get('X-SmsGora-Signature') || '';
  const ok = got.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected));
  if (!ok) return res.sendStatus(401);

  res.sendStatus(200);
  queue.add(JSON.parse(req.body));        // process later
});

Note express.raw on this route instead of express.json, so the body stays as raw bytes.

PHP#

$raw = file_get_contents('php://input');
$expected = 'sha256=' . hash_hmac('sha256', $raw, getenv('WEBHOOK_SECRET'));
if (!hash_equals($expected, $_SERVER['HTTP_X_SMSGORA_SIGNATURE'] ?? '')) {
    http_response_code(401);
    exit;
}
$event = json_decode($raw, true);

Python (Flask)#

import hmac, hashlib, os
from flask import request, abort

raw = request.get_data()
expected = "sha256=" + hmac.new(os.environ["WEBHOOK_SECRET"].encode(), raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("X-SmsGora-Signature", "")):
    abort(401)
event = request.get_json()

Shared-secret headers#

Some providers don't compute an HMAC; they send your webhook secret itself in a header, and you compare it with the stored value. WAservix, for example, sends the device's webhook secret in X-Webhook-Signature. It's simpler, and it still proves the request knows the secret, but it doesn't prove the body wasn't altered, and anyone who sees one request's headers learns the secret. Compare it in constant time, keep it off logs, and always use HTTPS so headers are encrypted in transit.

Protect against replay#

A valid signed request can be captured and sent again later. Two defences:

  • Timestamps: if the provider signs a timestamp along with the body, reject requests older than a few minutes.
  • Event IDs: store each event's unique ID and ignore any you've already processed. This also handles the provider's own retries, which are normal.

Idempotent handling, where processing the same event twice has no extra effect, is good practice whether or not anyone attacks you.

Managing the secret#

  • Store it in an environment variable or secret manager, never in code or a repository.
  • Use a different secret per environment: development, staging, production.
  • Rotate it if it may have leaked, and on a schedule. During rotation, accept both old and new secrets briefly, then remove the old one.
  • Never log it, or full headers that contain it.

Testing verification#

  1. Send a real event from the provider and confirm it passes.
  2. Change one character of the body and resend it: it must fail.
  3. Send it with no signature header: it must fail.
  4. Send it with the wrong secret: it must fail.
  5. Replay an old event: your duplicate check should skip it.

Our API testing guide covers tunnelling a provider's webhooks to your machine for tests like these.

After verification#

Verification says the request is genuine. It doesn't make the handler safe by itself. Answer quickly with a 2xx status, put the work in a queue, and validate the event's content before acting on it. Our guides to receiving SMS by webhook and WhatsApp webhooks show complete handlers. If you build your own integrations on Tekservix, the developer platform documents webhooks for your account.

A worked example#

Imagine a developer whose webhook signature check fails for every request, even though the secret is right. The framework is parsing JSON globally before the route runs, so the code signs JSON.stringify(req.body), which differs from the original bytes. Switching that route to receive the raw body fixes it immediately. While testing, they also add a table of processed event IDs, which quietly absorbs the provider's occasional retries that had been creating duplicate replies to customers.

Frequently asked questions

What is webhook signature verification?

It's checking that an incoming webhook request really came from the service that claims to have sent it, and wasn't changed on the way, by recomputing a signature from the request body and a shared secret and comparing it with the signature in the request header.

Why does my webhook signature check fail?

The most common cause is computing the signature over a parsed and re-encoded body instead of the exact raw bytes received. Other causes are the wrong secret, a missing prefix such as 'sha256=', and comparing hex with base64.

Do I need to verify webhooks if the URL is secret?

Yes. URLs leak through logs, browser history, screenshots and shared code. Signature verification is the only reliable way to know a request came from the provider, and it takes a few lines of code.

Share this article
Written by

The team behind Tekservix

The Tekservix Team builds and supports Tekservix: WhatsApp and SMS APIs, AI tools, invoicing, PDF and SEO tools for growing businesses. We write practical, tested guides based on what we see our customers do every day.

More articles from the Tekservix Team

Get new guides in your inbox

One short email when we publish something useful: WhatsApp and SMS marketing, AI tools, SEO and running a business online. No spam, unsubscribe anytime.