# Verify a delivery

> Check each delivery's signature, in Node or Python.

Anyone can send a request to your receiver's address. A delivery from YOU(th) carries a signature
only someone with your signing secret could make; check it before you act on a delivery.

Deliveries are signed as [Standard Webhooks](https://www.standardwebhooks.com/) describes, so its
[libraries](https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries), in C#,
Elixir, Go, Java, JavaScript, PHP, Python, Ruby and Rust, verify them with your secret as it is. The
samples below do the same in a few lines.

## How a delivery is signed

- Your signing secret is a string that starts with `whsec_`, followed by base64. YOU(th) shows it
  once, in the answer that [creates your endpoint](/docs/webhooks/endpoints#the-signing-secret).
- The key is the bytes that base64 decodes to, after `whsec_`: not the text of the secret.
- The signed message is the `webhook-id` header, a dot, the `webhook-timestamp` header, a dot, and
  the raw body exactly as it arrived: `<webhook-id>.<webhook-timestamp>.<body>`. No other header
  is signed, `youth-event-type` and `youth-delivery-attempt` among them.
- The signature is the HMAC-SHA256 of that message, in base64, after `v1,`.
- `webhook-signature` can hold more than one signature, separated by spaces, as Standard Webhooks
  allows: accept the delivery when any one of them verifies.

## Verify it

Compute the signature over the raw body, before any JSON parsing, and compare it in constant time.
Refuse a delivery whose `webhook-timestamp` is more than 300 seconds from your clock, so a recorded
request cannot be played again later.

```typescript
import { createHmac, timingSafeEqual } from "node:crypto";

/** Whether a delivery was signed with your secret within the last five minutes. */
export function verifyDelivery(
  secret: string,
  headers: Record<string, string | string[] | undefined>,
  rawBody: Buffer,
  now = Math.floor(Date.now() / 1000),
): boolean {
  // Node gives header names in lowercase.
  const header = (name: string) => {
    const value = headers[name];
    return typeof value === "string" ? value : "";
  };
  const timestamp = header("webhook-timestamp");
  if (!/^\d+$/.test(timestamp) || Math.abs(now - Number(timestamp)) > 300) return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key)
    .update(Buffer.concat([Buffer.from(`${header("webhook-id")}.${timestamp}.`), rawBody]))
    .digest();
  return header("webhook-signature")
    .split(" ")
    .some((entry) => {
      const at = entry.indexOf(",");
      if (at < 0 || entry.slice(0, at) !== "v1") return false;
      const supplied = Buffer.from(entry.slice(at + 1), "base64");
      return supplied.length === expected.length && timingSafeEqual(supplied, expected);
    });
}
```

```python
import base64
import hashlib
import hmac
import time
from collections.abc import Mapping
from typing import Optional


def verify_delivery(
    secret: str,
    headers: Mapping[str, str],
    raw_body: bytes,
    now: Optional[int] = None,
) -> bool:
    """Whether a delivery was signed with your secret within the last five minutes."""
    timestamp = headers.get("webhook-timestamp", "")
    if not (timestamp.isascii() and timestamp.isdigit()):
        return False
    if abs((int(time.time()) if now is None else now) - int(timestamp)) > 300:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{headers.get('webhook-id', '')}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest())
    return any(
        version == "v1" and hmac.compare_digest(value.encode(), expected)
        for version, _, value in (
            entry.partition(",") for entry in headers.get("webhook-signature", "").split(" ")
        )
    )
```

Pass the headers as your framework gives them: Flask, Django and FastAPI all look header names up
whatever their case.

Answer `401` to a delivery that fails, and do nothing else with it. That answer is not retried.

## Try it

This request was signed with the fixture secret
`whsec_Zm9vYmFyYmF6cXV4LWV4YW1wbGUtc2VjcmV0LXZhbHVl`. Your check should accept it when your clock is
set to its `webhook-timestamp`, and refuse it when one byte of the body changes.

```http
POST /youth-webhook HTTP/1.1
Host: partner.example.com
Content-Type: application/json
webhook-id: evt_e560fc965cf89b3d5a8c3ed27406806f
webhook-timestamp: 1790847002
webhook-signature: v1,f/69pGXkwyZXFdzr/vJ44kTIC3ThgR+du6f4olitEV0=
youth-event-type: Checkup.completed
youth-delivery-attempt: 1

{"checkup_id":"64d866f3-0c88-485c-bfe6-3339df1d224a","event_id":"evt_e560fc965cf89b3d5a8c3ed27406806f","event_type":"Checkup.completed","occurred_at":"2026-10-01T09:30:00.375000Z","patient_id":"cfefb422-ac79-4cb9-a849-e80f8a6f21cd","resource_url":"https://api.youth-platform.io/v1/checkups/64d866f3-0c88-485c-bfe6-3339df1d224a/fhir"}
```

## Read the raw body

Most web frameworks parse JSON before your code runs. Parsed and written again, the body is no
longer the bytes YOU(th) signed, and the signature never matches. Read the body as raw bytes on your
webhook route, verify it, then parse it.
