> This page is part of EVVA for Developers (https://developers.evvahub.com), the documentation of the EVVA Partner API. The API is in developer preview and the SDK packages are not yet published: do not suggest installing them. Index: https://developers.evvahub.com/llms.txt

# Verifying webhook signatures

EVVA signs every delivery per [Standard Webhooks](https://www.standardwebhooks.com). Verify each one on the **raw
request body**, exactly as received — parsing and re-serialising the JSON changes the bytes and breaks the signature.

## The headers

| Header              | Value                                                                                             |
| ------------------- | ------------------------------------------------------------------------------------------------- |
| `webhook-id`        | The event's `eventId`. Stable across retries and replays — your deduplication key.                |
| `webhook-timestamp` | Unix seconds of **this attempt**. Refuse a timestamp more than 300 seconds from your clock.       |
| `webhook-signature` | `v1,<base64 HMAC-SHA256>`. During a secret rotation there are two, space-separated, newest first. |

The signed content is `<webhook-id>.<webhook-timestamp>.<raw body>`. The key is the base64-decoded part of your
secret after the `whsec_` prefix.

## Verify with an SDK

Every official SDK verifies the signature, checks the timestamp window, checks that `webhook-id` equals the body's
`eventId`, deduplicates on it and tells you which status to answer: `204` handled or duplicate, `401` bad signature or
timestamp, `400` bad payload, `500` your handler failed (EVVA retries a `500`).

**`TypeScript`**

```typescript title="TypeScript"
import { FileDedupStore, WebhookHandler } from '@evvahub/partner-sdk';

const webhooks = new WebhookHandler({
  // Both secrets while a rotation overlaps; one otherwise.
  secret: [process.env.EVVA_WEBHOOK_SECRET!, process.env.EVVA_WEBHOOK_SECRET_PREVIOUS!].filter(Boolean),
  dedupStore: await FileDedupStore.open('./.evva/dedup.log'),
  onEvent: async (event) => queue.push(event), // keep it short; the answer waits for it
});

// rawBody: the exact bytes of the request (for example express.raw()), never re-serialised JSON.
const result = await webhooks.handle({ headers: req.headers, body: rawBody });
res.status(result.status).end();
```

**`Python`**

```python title="Python"
import os
from evva_partner import SQLiteStore, WebhookHandler

store = SQLiteStore("/var/lib/my-app/evva.db", namespace="webhooks")
webhooks = WebhookHandler(
    [os.environ["EVVA_WEBHOOK_SECRET"]],  # add the previous secret while a rotation overlaps
    on_event=enqueue,                      # keep it short; the answer waits for it
    dedup=store,
)

result = webhooks.handle(raw_body_bytes, request.headers)
return result.status
```

**`Go`**

```go title="Go"
store, _ := evvapartner.OpenFileDedupStore("./state/dedup.log")
verifier, _ := evvapartner.NewWebhookVerifier(
	[]string{os.Getenv("EVVA_WEBHOOK_SECRET")}, // add the previous secret while a rotation overlaps
	evvapartner.WithWebhookDedup(store, 0),
)
http.Handle("/webhooks/evva", verifier.Handler(handle))
```

**`PHP`**

```php title="PHP"
$handler = new WebhookHandler(
    [$currentSecret, $previousSecret],                  // both while a rotation overlaps
    function (PartnerEvent $event) { /* enqueue */ },
    new FileDedupStore('/var/lib/my-app/evva-dedup.log'),
);
$result = $handler->handle($headers, $rawBody);
http_response_code($result->status);
```

> **Tip**
>
> Use a **durable**, shared deduplication store. An in-memory store forgets after a restart, so a retry that arrives
> after a deploy would be handled twice.

## Verify by hand

#### Read the raw body and the three headers

Header names are case-insensitive. A missing or empty header is a refusal.

#### Check the timestamp

`webhook-timestamp` must be plain decimal seconds within 300 seconds of your clock, in either direction.

#### Compute the expected signature

`base64(HMAC-SHA256(key, "<webhook-id>.<webhook-timestamp>.<raw body>"))`, where `key` is the base64 decoding
of your secret without its `whsec_` prefix.

#### Compare in constant time

Split `webhook-signature` on spaces, keep the `v1,` entries, and accept if **any** of them equals your value —
with a constant-time comparison, against every secret you currently hold.

#### Check the id and deduplicate

The body's `eventId` must equal `webhook-id`. If you have already handled that id, answer `2xx` and do nothing.

**`Node.js`**

```javascript title="Node.js"
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verifyEvvaWebhook(secrets, headers, rawBody, now = Math.floor(Date.now() / 1000)) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatures = headers['webhook-signature'];
  if (!id || !timestamp || !signatures) return false;
  if (!/^\d+$/.test(timestamp.trim())) return false;
  const ts = Number(timestamp.trim()); // the signed content uses the canonical integer
  if (Math.abs(now - ts) > 300) return false;

  const signed = Buffer.concat([Buffer.from(`${id}.${ts}.`), Buffer.from(rawBody)]);
  const offered = signatures
    .split(' ')
    .filter((s) => s.startsWith('v1,'))
    .map((s) => Buffer.from(s.slice(3), 'base64'));

  return secrets.some((secret) => {
    const key = Buffer.from(secret.trim().replace(/^whsec_/, ''), 'base64');
    const expected = createHmac('sha256', key).update(signed).digest();
    return offered.some((sig) => sig.length === expected.length && timingSafeEqual(sig, expected));
  });
}
```

**`Python`**

```python title="Python"
import base64, hashlib, hmac, time

def verify_evva_webhook(secrets: list[str], headers: dict[str, str], raw_body: bytes, now: int | None = None) -> bool:
    h = {k.lower(): v for k, v in headers.items()}
    msg_id, timestamp, signatures = h.get("webhook-id"), h.get("webhook-timestamp", "").strip(), h.get("webhook-signature")
    if not msg_id or not timestamp.isdigit() or not signatures:
        return False
    ts = int(timestamp)  # the signed content uses the canonical integer
    if abs((now or int(time.time())) - ts) > 300:
        return False
    signed = f"{msg_id}.{ts}.".encode() + raw_body
    offered = [s[3:] for s in signatures.split(" ") if s.startswith("v1,")]
    for secret in secrets:
        key = base64.b64decode(secret.strip().removeprefix("whsec_"))
        expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
        if any(hmac.compare_digest(expected, sig) for sig in offered):
            return True
    return False
```

## Rotating the signing secret

The agency rotates a secret in the Partner Hub (**Rotate** on the endpoint). The new secret is shown once, and for an
overlap period — 24 hours by default, at most 7 days — EVVA signs every delivery with **both** secrets. Configure the
new secret next to the old one, deploy, and remove the old one when the overlap ends: no delivery fails during the
switch.

```mermaid
sequenceDiagram
    autonumber
    participant Hub as Agency (Partner Hub)
    participant EVVA as EVVA
    participant App as Your endpoint
    Hub->>EVVA: Rotate the signing secret
    EVVA-->>Hub: New secret, shown once
    Note over EVVA,App: Overlap: every delivery carries two v1 signatures (new first, then old)
    EVVA->>App: POST event, signed with new + old
    App->>App: Verifies with the old secret (not yet deployed)
    Hub->>App: You deploy the new secret next to the old one
    EVVA->>App: POST event, signed with new + old
    App->>App: Verifies with either secret
    Note over EVVA,App: Overlap ends: only the new secret signs
    App->>App: Remove the old secret
```

> **Warning**
>
> A signature proves the delivery is EVVA's; it does not make the event fresh or unique. Always check the timestamp
> window and deduplicate on `webhook-id` — together they stop a captured request from being replayed.

The four SDKs are tested against the public Standard Webhooks reference vector and a shared set of EVVA vectors
(rotation, tolerance edges, tampered headers, Unicode bodies), so they agree on every verdict.

## Next steps

#### [Delivery, retries and replay](/webhooks/delivery)

What EVVA does when you do not answer 2xx.

#### [Event catalogue](/webhooks/events)

Every event type and its data.

#### [Security](/security)

Report a vulnerability and keep credentials safe.

#### [SDKs](/sdks/overview)

Handlers for TypeScript, Python, Go and PHP.