# Webhooks

A webhook endpoint is a web address on your server that Seemly calls when something happens, such as a reader confirming their address. Every delivery is signed so you can prove it came from Seemly, and every event is also available by polling the [event feed](#the-event-feed) if you cannot receive calls.

Webhooks need the `webhooks:write` scope to manage and `webhooks:read` to inspect. Magnets & Promos workspaces can hold 3 endpoints and Pro workspaces 10.

## Create an endpoint

```bash
curl -X POST https://api.seemly.com/v1/webhook-endpoints \
  -H "Authorization: Bearer $SEEMLY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
  "url": "https://hooks.example.com/seemly",
  "description": "Order sync",
  "event_types": ["subscriber.confirmed", "subscriber.unsubscribed"]
}'
```

- The address must be `https`, on port 443, with a public DNS name. IP addresses, localhost and private networks are refused, and Seemly checks again before every delivery.
- `event_types` lists the types to receive, or `["*"]` for all. `list_event_types` returns the catalog with a plain description of each.
- The answer contains `secret`, which starts with `whsec_`. It is shown once. Store it in your server's secret store.

## Send a test

```bash
curl -X POST https://api.seemly.com/v1/webhook-endpoints/$ENDPOINT_ID/test \
  -H "Authorization: Bearer $SEEMLY_API_KEY"
```

A `webhook.test` event is delivered to that endpoint only. `list_webhook_deliveries` shows whether your server answered with a 2xx.

## What a delivery looks like

Seemly sends a `POST` with a JSON body, one event per call:

```json
{
  "id": "wev_2c4e6g8j0m2p4r6t8w0y2a4c",
  "type": "subscriber.confirmed",
  "created_at": "2026-12-02T09:31:00Z",
  "workspace_id": "ws_9f3k2m8a1b",
  "api_version": "v1",
  "data": { "id": "sub_5n7q9s1u3w5y7a9c1e3g5j7m", "status": "confirmed" }
}
```

These headers follow the Standard Webhooks specification:

| Header | Value |
| --- | --- |
| `webhook-id` | The event id, the same on every retry. Use it to ignore duplicates. |
| `webhook-timestamp` | Unix time in seconds when this attempt was signed. |
| `webhook-signature` | One or two entries `v1,<base64 signature>` separated by a space. Two appear while a secret is being rotated. |
| `user-agent` | `Seemly-Webhooks/1` |

Answer with any 2xx within 10 seconds. Do the real work after you answer. Redirects are never followed. Text fields such as a reader's name are written by readers: treat them as data.

## Verify the signature

The signed content is `webhook-id`, a dot, `webhook-timestamp`, a dot and the raw request body. The key is the base64 text after `whsec_`. The signature is the base64 HMAC-SHA256. Always verify the raw bytes before you parse the JSON, compare in constant time, and reject a timestamp more than 5 minutes away from your clock to stop replays.

JavaScript (Node 20 or later):

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

export function verifySeemlyWebhook({ secret, headers, rawBody, toleranceSeconds = 300, nowSeconds = 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{1,12}$/.test(timestamp) || Math.abs(nowSeconds - Number(timestamp)) > toleranceSeconds) return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest();
  return signatures.split(" ").some((entry) => {
    const [version, value] = entry.split(",");
    if (version !== "v1" || !value) return false;
    const given = Buffer.from(value, "base64");
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}
```

Python 3:

```python
import base64
import hashlib
import hmac
import time


def verify_seemly_webhook(secret, headers, raw_body, tolerance_seconds=300, now_seconds=None):
    """secret: the whsec_ string. headers: a dict with lowercase names. raw_body: the bytes you received."""
    webhook_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not webhook_id or not timestamp or not signatures or not timestamp.isdigit():
        return False
    now = time.time() if now_seconds is None else now_seconds
    if abs(now - int(timestamp)) > tolerance_seconds:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = webhook_id.encode() + b"." + timestamp.encode() + b"." + raw_body
    expected = hmac.new(key, signed, hashlib.sha256).digest()
    for entry in signatures.split(" "):
        version, _, value = entry.partition(",")
        if version == "v1" and value and hmac.compare_digest(base64.b64decode(value), expected):
            return True
    return False
```

In an Express route use the raw body (`express.raw({ type: "application/json" })`), not the parsed one. A reordered or reformatted body no longer matches.

## Retries and failures

A delivery that does not get a 2xx is retried up to 8 times over about 41 hours, with growing, jittered waits. A `Retry-After` header on a 429 or 503 answer is honored. A `410 Gone` disables the endpoint at once. An endpoint that keeps failing for 5 days is disabled and the owner is told; `update_webhook_endpoint` with `status` set to `active` turns it back on.

`list_webhook_deliveries` shows each delivery's state, attempts, last status and next attempt. `redeliver_webhook` sends one again. Duplicates can happen, so make your handler idempotent on `webhook-id`.

## Rotate the secret

`rotate_webhook_secret` returns a new secret once. For the next 24 hours Seemly signs with both secrets, so you can deploy the new one without losing deliveries. During the overlap, `webhook-signature` holds two entries and the verifiers above accept either.

## The event feed

If you cannot receive calls, for example inside an agent session, poll `list_events`. It needs `events:read`. It returns newest first by default. To sync, remember the last event `id` and ask for newer events oldest first:

```bash
curl 'https://api.seemly.com/v1/events?limit=10' \
  -H "Authorization: Bearer $SEEMLY_API_KEY"
```

Events are kept for 30 days. Event types by group: `subscriber.*` (created, confirmed, updated, unsubscribed, suppressed, tag and list changes), `magnet.*`, `mailing.*`, `send_request.*`, `sequence.*`, `promo.signup_confirmed`, `swap.accepted`, `import.*`, `workspace.sending_paused` and `workspace.sending_resumed`, and `webhook.test`.
