Verify webhook signatures

Check that a delivery really came from us and wasn't changed on the way, with ready-to-paste code for Node.js, Python and PHP.

On this page

Anyone who learns your endpoint's address can send it a request. The signature proves a delivery came from us and that its body wasn't changed: check it before you act on an event.

How it works

Each endpoint has a signing secret (whsec_ followed by base64), shown when you add the endpoint and on its Settings tab. Every delivery carries three headers, following the Standard Webhooks spec:

HeaderWhat it is
webhook-idThe event's id: the same on every retry and resend.
webhook-timestampWhen this attempt was signed, in Unix seconds.
webhook-signatureOne or more v1,<signature> entries, separated by spaces.

The signature is the base64 HMAC-SHA256 of webhook-id, webhook-timestamp and the raw body, joined by dots, keyed with the bytes of the secret (the base64 after whsec_, decoded):

text
signature = base64( HMAC-SHA256( key, "<webhook-id>.<webhook-timestamp>.<raw body>" ) )

To verify a delivery:

  1. Compute the signature yourself, from the body exactly as received (before any JSON parsing).
  2. Compare it, in constant time, with each v1 entry of webhook-signature. One match is enough: during a secret rotation there are two entries.
  3. Refuse a timestamp more than 5 minutes away from your clock, so a recorded delivery can't be replayed later.

The functions below do exactly that, without any library. They're tested against our own signer on every change.

Node.js

Works in Node.js 18+, Bun and Deno, with no dependencies.

js
import crypto from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

/** True when the delivery is ours and recent. `rawBody`: a string or Buffer. */
export function verifyWebhook(rawBody, headers, secret) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) return false;
  const sent = Number(timestamp);
  const now = Math.floor(Date.now() / 1000);
  if (!Number.isInteger(sent) || Math.abs(now - sent) > TOLERANCE_SECONDS)
    return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = crypto
    .createHmac("sha256", key)
    .update(`${id}.${timestamp}.`)
    .update(rawBody)
    .digest();
  return signatures.split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    if (version !== "v1" || !signature) return false;
    const given = Buffer.from(signature, "base64");
    return (
      given.length === expected.length &&
      crypto.timingSafeEqual(given, expected)
    );
  });
}

With Express, take the body raw on that route:

js
app.post(
  "/webhooks",
  express.raw({ type: "application/json" }),
  (req, res) => {
    if (!verifyWebhook(req.body, req.headers, process.env.WEBHOOK_SECRET))
      return res.sendStatus(401);
    const event = JSON.parse(req.body);
    // Skip it if you already handled event.id; then store it and answer.
    res.sendStatus(200);
  },
);

Python

Python 3.9+, standard library only.

python
import base64
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 5 * 60


def verify_webhook(raw_body: bytes, headers, secret: str) -> bool:
    """True when the delivery is ours and recent."""
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        return False
    try:
        sent = int(timestamp)
    except ValueError:
        return False
    if abs(time.time() - sent) > TOLERANCE_SECONDS:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest())
    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature.encode(), expected):
            return True
    return False

With Flask:

python
@app.post("/webhooks")
def webhooks():
    if not verify_webhook(request.get_data(), request.headers, WEBHOOK_SECRET):
        abort(401)
    event = request.get_json()
    # Skip it if you already handled event["id"]; then store it and answer.
    return "", 200

In Django, pass request.body and request.headers.

PHP

PHP 7.4+, no extensions beyond the defaults.

php
<?php
const WEBHOOK_TOLERANCE_SECONDS = 300;

/** True when the delivery is ours and recent. */
function verify_webhook(string $rawBody, array $headers, string $secret): bool
{
    $headers = array_change_key_case($headers, CASE_LOWER);
    $id = $headers['webhook-id'] ?? '';
    $timestamp = $headers['webhook-timestamp'] ?? '';
    $signatures = $headers['webhook-signature'] ?? '';
    if ($id === '' || $signatures === '' || !ctype_digit($timestamp)) {
        return false;
    }
    if (abs(time() - (int) $timestamp) > WEBHOOK_TOLERANCE_SECONDS) {
        return false;
    }
    $key = base64_decode(preg_replace('/^whsec_/', '', $secret), true);
    if ($key === false) {
        return false;
    }
    $expected = base64_encode(
        hash_hmac('sha256', $id . '.' . $timestamp . '.' . $rawBody, $key, true)
    );
    foreach (explode(' ', $signatures) as $entry) {
        $parts = explode(',', $entry, 2);
        if ($parts[0] === 'v1' && isset($parts[1]) && hash_equals($expected, $parts[1])) {
            return true;
        }
    }
    return false;
}

In a plain script:

php
<?php
$body = file_get_contents('php://input');
if (!verify_webhook($body, getallheaders(), getenv('WEBHOOK_SECRET'))) {
    http_response_code(401);
    exit;
}
$event = json_decode($body, true);
// Skip it if you already handled $event['id']; then store it and answer.
http_response_code(200);

In Laravel, pass $request->getContent() and $request->headers->all() flattened to strings, or use the same function in a middleware.

Common mistakes

  • Verifying a re-encoded body. Many frameworks parse JSON before your code runs. Parsing and encoding it again changes spaces and key order, and the signature no longer matches. Always use the raw bytes.
  • Comparing with ==. Use a constant-time comparison (timingSafeEqual, compare_digest, hash_equals), as above.
  • Using the whole secret as the key. The key is the base64 after whsec_, decoded, not the text itself.
  • Checking only the first signature. During a rotation the header holds two; accept a match on either.
  • A slow clock. The 5-minute window needs your server's clock to be right (NTP).

Try it

Choose Send test event on the endpoint: the test event is signed like a real one, so it's the quickest way to check your code. Its delivery shows the exact body that was signed.

Still stuck?

Ask us. We read every message.

Privacy