# Verify WhatsApp webhook signatures with X-Hub-Signature-256

> Answer the WhatsApp Cloud API verification GET, then check X-Hub-Signature-256 against the raw body, with tested Node.js and Python code and an n8n setup.

Published 2026-11-02. Z-API Omni team.

Compute an HMAC-SHA256 of the raw request body with your Meta app secret as the key. Compare the hex result with everything after `sha256=` in the `X-Hub-Signature-256` header. Do it on the bytes as they arrived, before any JSON parser touches them, and compare in constant time. The GET request that verifies your endpoint is a separate check. It compares a verify token you choose.

## The verification GET

Meta sends a GET to your callback URL every time you set or edit the Callback URL or Verify token field in the App Dashboard. It carries three query parameters: `hub.mode=subscribe`, `hub.challenge` (a random string Meta generates) and `hub.verify_token` (the string you typed into the dashboard). Compare the token with the copy stored on your server. If it matches, "respond with HTTP status `200` and the `hub.challenge` value". Anything else leaves the endpoint unverified, "and webhooks will not be sent to your endpoint" ([Create a webhook endpoint](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)).

Return the challenge as the bare body. Wrapping it in JSON or HTML fails the check. If your framework is PHP, Meta's Graph API guide warns that "PHP converts periods (.) to underscores (_) in parameter names", so read `hub_challenge` there ([Graph API webhooks](https://developers.facebook.com/docs/graph-api/webhooks/getting-started)).

## The POST signature

Every event notification arrives as a POST that carries the signature header ([Create a webhook endpoint](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)).

```http
POST /webhooks HTTP/1.1
Content-Type: application/json
X-Hub-Signature-256: sha256=b63bb356dff0f1c24379efea2d6ef0b2e2040853339d1bcf13f9018790b1f7d2
```

Meta describes the value as an "HMAC-SHA256 hash, calculated using the post body payload and your app secret as the secret key". The app secret is on the Basic settings page of the App Dashboard ([Basic settings](https://developers.facebook.com/docs/development/create-an-app/app-dashboard/basic-settings)). It differs from your access token and from the verify token. Meta's own wording on whether to check: "You don't have to validate the payload, but you should" ([Graph API webhooks](https://developers.facebook.com/docs/graph-api/webhooks/getting-started)). If the hashes match, answer 200. If they don't, answer with a 400-level status and discard the payload.

Without the check, anyone who learns your callback URL can post to it. A forged `messages` event can create contacts, trigger your AI agent or spend your model budget. Nobody can produce a valid signature without your app secret.

## Why parsing the JSON first breaks the hash

An HMAC covers bytes. Two JSON documents that decode to the same object can differ in whitespace, key order and character escaping, and each difference changes the hash. Most web frameworks parse the body before your handler runs and hand you an object. Serialize that object back to a string and you hash your serializer's output instead of the bytes Meta signed.

In Python, `json.dumps` puts a space after every comma and colon by default, and with `ensure_ascii` on (the default) it escapes every non-ASCII character ([json module](https://docs.python.org/3/library/json.html)). A message body of `Olá café` comes back as `Ol\u00e1 caf\u00e9`, and the check fails on every message with an accent or an emoji. Plain ASCII messages pass, so the bug looks random.

Keep the raw body. In Express, `express.raw()` "parses all bodies as a `Buffer`". The `verify` option of `express.json()` also receives `buf`, "a `Buffer` of the raw request body" ([Express 5 API](https://expressjs.com/en/5x/api/express/)). In Flask, `request.get_data()` "reads the buffered incoming data from the client into one bytes object" ([Flask API](https://flask.palletsprojects.com/en/stable/api/)).

## Node.js, no dependencies

This server uses only `node:http` and `node:crypto`. It answers the GET, checks the POST against the raw bytes and parses JSON only after the signature passes.

```javascript
const http = require('node:http');
const crypto = require('node:crypto');

const APP_SECRET = process.env.APP_SECRET;     // App Dashboard, Basic settings
const VERIFY_TOKEN = process.env.VERIFY_TOKEN; // the string you typed in Verify token

function validSignature(rawBody, header) {
  if (typeof header !== 'string' || !header.startsWith('sha256=')) return false;
  const expected = crypto.createHmac('sha256', APP_SECRET).update(rawBody).digest('hex');
  const a = Buffer.from(header.slice(7), 'utf8');
  const b = Buffer.from(expected, 'utf8');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

http.createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');

  if (req.method === 'GET') {
    const ok = url.searchParams.get('hub.mode') === 'subscribe' &&
               url.searchParams.get('hub.verify_token') === VERIFY_TOKEN;
    res.writeHead(ok ? 200 : 403, { 'Content-Type': 'text/plain' });
    return res.end(ok ? url.searchParams.get('hub.challenge') : '');
  }

  const chunks = [];
  req.on('data', (c) => chunks.push(c));
  req.on('end', () => {
    const rawBody = Buffer.concat(chunks);           // the exact bytes Meta signed
    if (!validSignature(rawBody, req.headers['x-hub-signature-256'])) {
      res.writeHead(401);
      return res.end();
    }
    res.writeHead(200);
    res.end();
    const payload = JSON.parse(rawBody.toString('utf8')); // parse only after the check
    console.log(JSON.stringify(payload.entry?.[0]?.changes?.[0]?.field));
  });
}).listen(process.env.PORT || 3000);
```

The length check before `timingSafeEqual` is required. Per Node's documentation, "an error is thrown if `a` and `b` have different byte lengths" ([Node.js crypto](https://nodejs.org/api/crypto.html)). Without the check, a short forged header crashes the request instead of returning 401. Node lower-cases header names ([Node.js http](https://nodejs.org/api/http.html)), so read `x-hub-signature-256`.

Test it locally by signing a body yourself:

```shell
BODY='{"object":"whatsapp_business_account","entry":[]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | awk '{print $NF}')
curl -i -X POST http://localhost:3000/ \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary "$BODY"
```

Use `--data-binary`. When `-d` reads from a file, "carriage returns, newlines and null bytes are stripped out" ([curl manual](https://curl.se/docs/manpage.html)), and the bytes no longer match what you signed.

## Python

The same check as a function. Pass it the raw bytes.

```python
import hashlib
import hmac

def valid_signature(raw_body: bytes, header: str, app_secret: str) -> bool:
    if not header or not header.startswith("sha256="):
        return False
    expected = hmac.new(app_secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(header[len("sha256="):], expected)
```

`hmac.compare_digest` "uses an approach designed to prevent timing analysis by avoiding content-based short circuiting behaviour" ([hmac module](https://docs.python.org/3/library/hmac.html)). It accepts strings of different lengths without raising, so no length guard is needed. In Flask, call it as `valid_signature(request.get_data(), request.headers.get("X-Hub-Signature-256"), APP_SECRET)`.

## n8n: Raw Body plus the Crypto node

n8n can run the same check without a Code node. It accepts one webhook per path and method. To serve the GET and the POST from one node, open its Settings and turn on Allow Multiple HTTP Methods. The node then has one output per method ([common issues](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/common-issues/)).

1. Webhook node with HTTP Methods GET and POST, Respond set to Using 'Respond to Webhook' Node. Under Add Option, turn on Raw Body. The node then writes the unparsed body to a binary property named `data`, next to the usual `headers`, `query` and `body` fields ([Webhook node source](https://github.com/n8n-io/n8n/blob/master/packages/nodes-base/nodes/Webhook/Webhook.node.ts)).
2. On the GET output, an If node that tests `{{ $json.query['hub.verify_token'] }}` against your token. Then a Respond to Webhook node, Respond With set to Text, body `{{ $json.query['hub.challenge'] }}`. Text "sends HTML by default", and n8n wraps HTML responses in an iframe ([Respond to Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.respondtowebhook/)). Add a Response Headers option with `Content-Type: text/plain`.
3. On the POST output, a Respond to Webhook node with Respond With set to No Data. Meta gets its 200 before any slow step runs.
4. Crypto node, action Hmac. Turn on Binary File, set Binary Property Name to `data`, Type to SHA256, Encoding to HEX and Property Name to `signature`. Put the app secret in the Hmac Secret field of the Crypto credential ([Crypto node](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.crypto/), [Crypto credentials](https://docs.n8n.io/integrations/builtin/credentials/crypto/)).
5. If node, String condition: `{{ 'sha256=' + $json.signature }}` is equal to `{{ $json.headers['x-hub-signature-256'] }}`. Connect your processing to the true output and leave the false output unconnected.

Step 3 answers 200 to forged requests as well, which only tells a forger that the URL exists. The If node comparison is also not constant-time. On self-hosted n8n, move step 5 into a Code node that calls `crypto.timingSafeEqual`. Allow the module first with `NODE_FUNCTION_ALLOW_BUILTIN=crypto`, because n8n "disables importing modules by default" ([node environment variables](https://docs.n8n.io/deploy/host-n8n/configure-n8n/basic-configuration/use-environment-variables/nodes/)).

## If the signature still fails

Check the secret first. A compromised secret is reset "in the Basic Settings of your App Dashboard", and Meta may reset a leaked one itself ([Basic settings](https://developers.facebook.com/docs/development/create-an-app/app-dashboard/basic-settings)). After a reset, every old copy in your environment variables is wrong. Then look for anything between Meta and your code that rewrites the body. A proxy that re-encodes JSON does it, and so does middleware that parses the body before your handler. Hash what your process receives, log the first 16 characters of both hashes and compare them on one request. Meta also retries undelivered webhooks for up to 7 days ([webhooks overview](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)), so a 401 does not lose the event while you fix the key. Each retry is a duplicate of an event you may already hold, which [the idempotency pattern for n8n](/academy/articles/n8n-duplicate-webhooks-idempotency/) handles.

*Z-API Omni team*
