> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qwairy.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify webhook signatures

> Verify the X-Qwairy-Signature of integration webhook requests in Node.js or Python, reject stale timestamps, and accept two signatures during rotation.

Verify every integration webhook request before you trust it. Qwairy signs each attempt
with the secret of the endpoint, so a valid signature shows that the request came from
Qwairy and that the body was not changed.

Do not rely on a token embedded in the endpoint URL instead. Every key of the team that
can read its webhooks, read-only keys included, receives the full URL.

## How the signature works

The `X-Qwairy-Signature` header is `sha256=` followed by the hexadecimal HMAC-SHA256,
keyed with your signing secret, of this string:

```text theme={null}
<X-Qwairy-Timestamp>.<raw request body>
```

* Use the **raw bytes** of the body, before any JSON parsing. A parsed and re-serialized
  body produces a different signature.
* `X-Qwairy-Timestamp` is the Unix time in seconds when this attempt was signed. Each
  retry is signed again with a new timestamp.
* Compare in constant time.
* Reject requests whose timestamp is more than **5 minutes** from your clock. This limits
  replays of a captured request.

## Check your code with a test vector

This synthetic example lets you confirm your implementation. It uses the secret
`synthetic-signing-secret` and the timestamp `1793610000`.

```text theme={null}
{"id":"evt_3f2a9c1e-5b7d-4e08-8a41-0c9d6e2b7f10","event":"webhook.test","createdAt":"2026-11-02T09:00:00Z","teamId":"team_synthetic_01","brandId":null,"data":{"message":"Test event from Qwairy."}}
```

```text theme={null}
X-Qwairy-Timestamp: 1793610000
X-Qwairy-Signature: sha256=e4f863963bfe0d0ea94861fd4790f23aacadfc496015ed8bd4127807a8d9be1f
```

The timestamp tolerance rejects this example on a real clock, so pass a fixed "now" in
your test.

## Node.js

```js theme={null}
import crypto from 'node:crypto';

const TOLERANCE_SECONDS = 300;

export function verifyQwairySignature({ rawBody, timestamp, signatureHeader, secret, now = Date.now() / 1000 }) {
  if (!/^\d+$/.test(timestamp ?? '')) return false;
  if (Math.abs(now - Number(timestamp)) > TOLERANCE_SECONDS) return false;

  const expected = Buffer.from(
    'sha256=' +
      crypto
        .createHmac('sha256', secret)
        .update(timestamp + '.')
        .update(rawBody)
        .digest('hex'),
  );

  // Right after a rotation the header holds two comma-separated values.
  return (signatureHeader ?? '').split(',').some((candidate) => {
    const received = Buffer.from(candidate.trim());
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}
```

Use it with a raw body parser, for example in Express:

```js theme={null}
import express from 'express';

const app = express();

app.post('/qwairy/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  const valid = verifyQwairySignature({
    rawBody: req.body, // a Buffer, because of express.raw
    timestamp: req.get('X-Qwairy-Timestamp'),
    signatureHeader: req.get('X-Qwairy-Signature'),
    secret: process.env.QWAIRY_WEBHOOK_SECRET,
  });
  if (!valid) return res.status(401).end();

  const event = JSON.parse(req.body.toString('utf8'));
  // Deduplicate on event.id, queue the work, then answer quickly.
  res.status(204).end();
});
```

## Python

```python theme={null}
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300


def verify_qwairy_signature(raw_body: bytes, timestamp: str, signature_header: str, secret: bytes, now=None) -> bool:
    if not timestamp or not timestamp.isascii() or not timestamp.isdigit():
        return False
    now = time.time() if now is None else now
    if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    expected = "sha256=" + hmac.new(
        secret, timestamp.encode() + b"." + raw_body, hashlib.sha256
    ).hexdigest()

    # Right after a rotation the header holds two comma-separated values.
    return any(
        hmac.compare_digest(candidate.strip().encode(), expected.encode())
        for candidate in (signature_header or "").split(",")
    )
```

Use it with the raw body, for example in Flask:

```python theme={null}
import os

from flask import Flask, request

app = Flask(__name__)


@app.post("/qwairy/webhooks")
def qwairy_webhook():
    valid = verify_qwairy_signature(
        raw_body=request.get_data(),  # the unparsed bytes
        timestamp=request.headers.get("X-Qwairy-Timestamp", ""),
        signature_header=request.headers.get("X-Qwairy-Signature", ""),
        secret=os.environ["QWAIRY_WEBHOOK_SECRET"].encode(),
    )
    if not valid:
        return "", 401

    event = request.get_json()
    # Deduplicate on event["id"], queue the work, then answer quickly.
    return "", 204
```

## Rotate the secret

After [Rotate the signing secret](https://docs.qwairy.co/developers/endpoints/webhooks/rotate-secret.md), the
`X-Qwairy-Signature` header carries **two** values separated by a comma for 24 hours.
The first is signed with the new secret and the second with the previous secret:

```text theme={null}
X-Qwairy-Signature: sha256=<signed with the new secret>,sha256=<signed with the previous secret>
```

Both examples above split the header and accept the request when any value matches the
secret you hold. To rotate without losing events:

1. Rotate the secret and store the new value.
2. Deploy the new secret to your receiver. Requests keep passing during the overlap,
   whichever secret you hold.
3. After 24 hours, requests carry a single signature again.

`previousSecretExpiresAt` in the [endpoint](https://docs.qwairy.co/developers/endpoints/webhooks/get.md) gives
the end of the overlap.

## Troubleshooting

* **Every request fails.** Check that you sign the raw body and not a re-serialized one,
  and that no middleware changes it before your handler.
* **Only some requests fail.** Check your server clock against the 5-minute tolerance.
* **A request fails after a rotation.** Confirm that you use the new secret, and that you
  compare every value of the header.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.