# Webhooks

Webhooks send [events](/docs/api-reference/events/) to your endpoint as they happen, instead of waiting for you to poll. Each delivery is an HTTPS `POST` whose body is the same event object returned by `GET /api/v1/events`.

## Creating a webhook

Create a webhook in **Settings → Webhooks**, or with the API using a key with `webhooks:manage` and the read scope for each event type:

```sh
curl https://optlo.com/api/v1/webhooks \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 7d0c1f2e-5b8a-4c51-9a63-2f1e8d4b7a90" \
  --data '{"url":"https://example.com/optlo/webhooks","types":["conversation.created","message.created"]}'
```

The response includes `signingSecret`. Store it securely: it is returned only when the webhook is created, and by retries of that request with the same idempotency key.

Endpoints must use HTTPS and a public hostname. URLs with credentials or fragments, and private or local addresses, are rejected. A workspace can have up to 50 webhooks; creating more returns `402 limit_exceeded`.

A webhook receives events created after it is active. Use the [event feed](/docs/api-reference/events/) to read earlier events.

## Requests

Each delivery includes these headers:

| Header                   | Value                                                                     |
| ------------------------ | ------------------------------------------------------------------------- |
| `Content-Type`           | `application/json`                                                        |
| `Optlo-Signature`        | Timestamp and one or more signatures, for example `t=1793438043,v1=5f2b…` |
| `Optlo-Delivery-Id`      | Stable ID for this event and webhook, the same on every attempt           |
| `Optlo-Delivery-Attempt` | Attempt number, starting at `1`                                           |

Respond with any `2xx` status within 5 seconds to acknowledge the delivery. Redirects are not followed; a `3xx` response counts as a failure and is not retried. Do slow work after responding, for example by placing the event on a queue.

## Verifying signatures

Verify every request before trusting it. The signature is an HMAC-SHA256 of the timestamp, a period, and the raw request body, keyed with the signing secret and encoded as lowercase hex.

1. Read the raw request body exactly as received. Parsing and re-serializing JSON changes the bytes and breaks verification.
2. Split `Optlo-Signature` on commas. Take the `t=` value as the timestamp and every `v1=` value as a candidate signature.
3. Compute `HMAC-SHA256(secret, timestamp + "." + body)` as hex.
4. Accept the request if the computed value equals any candidate, using a constant-time comparison.
5. Reject timestamps more than five minutes from your current time to limit replay of captured requests.

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

export function verifyOptloSignature(header, rawBody, secret, toleranceSeconds = 300) {
  let parts = header.split(",").map((part) => part.split("="));
  let timestamp = parts.find(([name]) => name === "t")?.[1];
  let signatures = parts.filter(([name]) => name === "v1").map(([, value]) => value);
  if (!timestamp || !signatures.length) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;

  let expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest();
  return signatures.some((signature) => {
    let candidate = Buffer.from(signature, "hex");
    return candidate.length === expected.length && timingSafeEqual(candidate, expected);
  });
}
```

Each attempt is signed with a fresh timestamp, so a retry delivered hours later still verifies.

## Duplicates and ordering

Delivery is at least once. A delivery can arrive more than once — for example, when your endpoint processed it but the response did not reach Optlo in time. Deduplicate using `Optlo-Delivery-Id`, or the event's `id` if one handler serves several webhooks, and treat repeats as success.

Deliveries are not guaranteed to arrive in order, especially when retries are involved. Use each event's `createdAt` and the resource's current state, rather than arrival order, to decide what is newest. To fetch the latest state, read the resource from the API.

Optlo sends at most five concurrent requests to each webhook subscription. Further deliveries wait until an earlier one completes, so a slow endpoint receives its backlog gradually rather than all at once.

## Retries

A delivery is retried when your endpoint returns `408`, `429`, or a `5xx` status, times out, or cannot be reached. Other `4xx` statuses are not retried.

Optlo makes up to eight attempts within 24 hours of the event. Retries wait about 1 minute, 5 minutes, 15 minutes, 1 hour, 3 hours, 6 hours, and 8 hours, each varied by up to 20% so that retries spread out. A `Retry-After` header on a retried response can lengthen the next delay, up to 24 hours, but never shortens it. Deliveries that have not succeeded after the last attempt, or 24 hours after the event, are marked failed.

View recent deliveries and their attempts in the dashboard or with `GET /api/v1/webhooks/{webhookId}/deliveries`. History is kept for 30 days. An attempt with error `unknown` has no confirmed outcome, so your endpoint may have received it. Failed deliveries can be resent from the dashboard while their event is still available.

## Disabled webhooks

A webhook is disabled automatically when:

- your endpoint responds `410 Gone`, which signals that the endpoint no longer exists, or
- automatic deliveries have failed at least 10 times in a row over at least 24 hours.

A successful delivery resets the failure count. Disabled webhooks show `disabledReason` (`manual`, `gone`, or `failures`) and receive no new events. Re-enable a webhook in the dashboard after fixing the endpoint; events created while it was disabled are not delivered.

## Rotating signing secrets

Rotate a signing secret in **Settings → Webhooks** if it may have been exposed, or on a schedule. When rotating, choose how long the previous secret stays active: 2, 6, 12, or 24 hours, or immediately.

While more than one secret is active, each delivery carries one `v1=` signature per active secret. An endpoint that accepts any matching signature, as in the example above, keeps working throughout. Update your endpoint to the new secret before the previous one expires. A webhook can have at most three active secrets.
