# Verify webhook signatures

Source: https://snizu.dev/docs/connections/webhooks/verify-signatures

## How the signature is built [#how-the-signature-is-built]

Each request carries the topic, the API version its body is shaped for, the event's ID and a `shop-signature` header with a timestamp and one or more signatures:

```http title="Request headers" {9}
POST /hooks HTTP/1.1
Content-Type: application/json
shop-topic: order.created
shop-api-version: 2026-10
shop-event-id: evt_01k9w3m2c8f4z7d0q5n1t6v8bx
shop-delivery-id: whdel_01k9w3m2d1h5a8e2r6p0s4y7cz
shop-store-id: store_01k9w2t7q3x8c5n0b4m6v1k9hd
shop-attempt: 1
shop-signature: t=1762588920,v1=5f0c3e9d…a91b
```

`v1` is the hex HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the secret:

<Flow steps={[{"value":"1762588920","label":"t, in seconds"},{"join":".","value":"{ raw body }","label":"the body, unparsed"},{"join":"→","value":"HMAC-SHA256","label":"keyed with the secret","mark":true},{"join":"→","value":"v1=5f0c3e…a91b","label":"hex, compare in constant time"}]} />

Webhooks your app declares in its manifest are signed with the app's client secret. A webhook created through the Admin API has its own signing secret, returned once when you create it.

## Verify it in your server [#verify-it-in-your-server]

Read the body as bytes, check the timestamp, compute the HMAC, then compare it in constant time.

```js tab="Node.js" lineNumbers {9-10,18-22}
import { createHmac, timingSafeEqual } from "node:crypto";

const FIVE_MINUTES = 5 * 60;

/** rawBody: the request body exactly as it arrived, as a Buffer. */
export function verify(rawBody, header, secret) {
  const pairs = (header ?? "").split(",").map((kv) => kv.split("="));
  const t = Number(pairs.find(([key]) => key === "t")?.[1]);
  const age = Math.abs(Date.now() / 1000 - t);
  if (!Number.isInteger(t) || age > FIVE_MINUTES) return false;

  const expected = createHmac("sha256", secret)
    .update(`${t}.`)
    .update(rawBody)
    .digest();

  // After a rotation, two v1 values arrive: accept either.
  return pairs
    .filter(([key]) => key === "v1")
    .map(([, value]) => Buffer.from(value, "hex"))
    .some((given) => given.length === expected.length
      && timingSafeEqual(given, expected));
}
```

```php tab="PHP" lineNumbers {18,25-29}
<?php

const FIVE_MINUTES = 5 * 60;

/** $rawBody: file_get_contents('php://input'), not decoded. */
function verify(string $rawBody, ?string $header, string $secret): bool
{
    $t = null;
    $signatures = [];
    foreach (explode(',', $header ?? '') as $part) {
        [$key, $value] = array_pad(explode('=', $part, 2), 2, '');
        if ($key === 't' && ctype_digit($value)) {
            $t = (int) $value;
        } elseif ($key === 'v1') {
            $signatures[] = $value;
        }
    }
    if ($t === null || abs(time() - $t) > FIVE_MINUTES) {
        return false;
    }

    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);

    // After a rotation, two v1 values arrive: accept either.
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}
```

```python tab="Python" lineNumbers {14,22-26}
import hashlib
import hmac
import time

FIVE_MINUTES = 5 * 60

def verify(raw_body: bytes, header: str | None, secret: str) -> bool:
    """raw_body is the request body exactly as it arrived."""
    pairs = [kv.partition("=") for kv in (header or "").split(",")]
    t = next((value for key, _, value in pairs if key == "t"), "")
    if not (t.isascii() and t.isdigit()):
        return False
    if abs(time.time() - int(t)) > FIVE_MINUTES:
        return False

    message = f"{t}.".encode() + raw_body
    digest = hmac.new(secret.encode(), message, hashlib.sha256)
    expected = digest.hexdigest().encode()

    # After a rotation, two v1 values arrive: accept either.
    return any(
        hmac.compare_digest(expected, value.encode())
        for key, _, value in pairs
        if key == "v1"
    )
```

```go tab="Go" lineNumbers {32,42-46}
package webhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"
)

const fiveMinutes = 5 * 60

// Verify checks a delivery. rawBody is the body as it arrived.
func Verify(rawBody []byte, header, secret string) bool {
	t := int64(-1)
	var signatures [][]byte
	for _, part := range strings.Split(header, ",") {
		key, value, _ := strings.Cut(part, "=")
		switch key {
		case "t":
			if n, err := strconv.ParseInt(value, 10, 64); err == nil {
				t = n
			}
		case "v1":
			if signature, err := hex.DecodeString(value); err == nil {
				signatures = append(signatures, signature)
			}
		}
	}
	age := time.Now().Unix() - t
	if t < 0 || age > fiveMinutes || age < -fiveMinutes {
		return false
	}

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(strconv.FormatInt(t, 10) + "."))
	mac.Write(rawBody)
	expected := mac.Sum(nil)

	// After a rotation, two v1 values arrive: accept either.
	for _, signature := range signatures {
		if hmac.Equal(signature, expected) {
			return true
		}
	}
	return false
}
```

<Callout tone="warning" title="Use the raw body">
A framework that parses JSON before you see it changes the bytes, and the signature won't match. In Express, mount `express.raw({ type: "application/json" })` on the webhook route.
</Callout>

## Reject old deliveries [#reject-old-deliveries]

- Accept a timestamp up to five minutes from your clock, in either direction.
- Keep each event ID for a day and ignore repeats: a retry or a redelivery carries the same ID, in `shop-event-id` and in the body's `id`.
- Answer with a 2xx within ten seconds, then do the slow work in the background. A slower answer counts as a failure and is tried again.

## When you rotate the secret [#when-you-rotate-the-secret]

For 24 hours after a rotation, every delivery carries two `v1` signatures, one from the new secret and one from the old, so you can deploy the new secret without dropping events.

Rotate an app's client secret in the developer console, in the app's settings. Rotate a webhook's own secret with `POST /admin/v1/stores/{store_id}/webhooks/{webhook_id}/rotate-secret`.

<Callout tone="success" title="Deploy within the 24 hours">
A webhook's new secret is in the rotation's response and is never shown again. Put it in your environment and deploy before the old one stops signing.
</Callout>

## Test it [#test-it]

For a webhook created through the Admin API, queue a signed `webhook.test` delivery with `POST /admin/v1/stores/{store_id}/webhooks/{webhook_id}/test`, then read its result in the webhook's delivery log.

For your app's webhooks, follow the failed deliveries from the app's folder:

```shellsession title="Terminal"
$ snizu app logs --follow --state failed
2026-11-24T12:04:51Z failed 401 order.created · Siwa Grove
Following. Ctrl+C to stop.
```