# Webhooks

Monitor webhooks, every delivery's attempt log, verifying the PrimaryAPI-Signature header in Node and Python, retries, redelivery, how long events are kept, and the signing secret.

A [monitor](/docs/monitors) sends its results to its own webhook URL: `POST` requests with a JSON body, signed with your workspace's signing secret, retried on a fixed schedule and logged attempt by attempt.

## Monitor events

```http title="POST https://example.com/hooks/primaryapi"
Content-Type: application/json
User-Agent: PrimaryAPI-Webhooks/1.0
PrimaryAPI-Signature: t=1762689600,v1=5f2a…c41e
PrimaryAPI-Event-Id: evt_01jc8t3a0c2e4g6j8m0p2r4t6w
PrimaryAPI-Event-Type: monitor.run.succeeded
PrimaryAPI-Delivery-Id: whd_01jc8t3a0d4f6h8k0m2p4r6t8x
PrimaryAPI-Delivery-Attempt: 1

{
  "id": "evt_01jc8t3a0c2e4g6j8m0p2r4t6w",
  "type": "monitor.run.succeeded",
  "createdAt": "2026-11-09T12:00:01.204Z",
  "monitor": {
    "id": "mon_01jc8t2v6x0d4f6h8k0m2p4r6t",
    "customId": "crm-account-1042",
    "name": null,
    "sku": "instagram.profile"
  },
  "run": {
    "id": "mrun_01jc8t39yb1d3f5h7k9m1p3r5t",
    "requestId": "req_01jc8t39yc3e5g7j9m1p3r5t7v",
    "status": "succeeded",
    "reason": null,
    "changed": true,
    "credits": 3,
    "items": 1,
    "createdAt": "2026-11-09T12:00:00.012Z"
  },
  "output": {
    "found": true,
    "data": { "username": "natgeo", "followers": 283104512, "…": "…" }
  },
  "connection": null
}
```

| `type` | Sent when | `run` | `output` |
|---|---|---|---|
| `monitor.run.succeeded` | A run succeeded and the monitor notifies for it: the first result and every change with `notify: "change"`, every result with `notify: "always"` | the run | the API's output (`found`, `data`, `reason`), exactly as in the [run envelope](/docs/making-requests) |
| `monitor.run.failed` | A run failed, while the monitor's `notifyFailures` is on | the run, with `reason` | `null` |
| `monitor.test` | You asked for a test event | `null` | `null` |

`monitor.customId` is your own reference, so you can match the event to your record without storing our ids. `run.requestId` is the call the run made, the same id as in your request history.

`monitorPaused` appears on one event only: the `monitor.run.failed` of the run that made us pause the monitor, the 10th failed run in a row ([When runs keep failing](/docs/monitors#when-runs-keep-failing)). Every other event leaves it out, so treat a missing field as "not paused".

```json title="The failure event that paused the monitor (excerpt)"
{
  "type": "monitor.run.failed",
  "run": { "status": "failed", "reason": "all_sources_failed", "…": "…" },
  "output": null,
  "monitorPaused": {
    "reason": "failing",
    "failingSince": "2026-11-05T09:00:00.000Z",
    "consecutiveFailures": 10
  }
}
```

`failingSince` is when the failures began, and `consecutiveFailures` how many runs in a row failed. The monitor stays paused until you resume it. With `notifyFailures` off no failure event is sent, but the monitor is still paused. When the 10th failure is a webhook that was never delivered (your endpoint didn't answer through every retry), there is no event to carry the pause: it shows on the monitor, in the dashboard and in the API.

## The attempt log

Every delivery keeps a log of its attempts:

`GET https://api.primaryapi.com/v1/monitors/{id}/deliveries/{deliveryId}`

Auth: API key with run, view or full access, or a dashboard session

It answers the delivery with `attemptLog`, one entry per attempt, oldest first.

| Field | Type | Description |
|---|---|---|
| `attempt` | integer | `1` for the first attempt, up to `11`. |
| `startedAt` | string | When the attempt started. |
| `durationMs` | integer or null | Until your endpoint answered, or we gave up (timeout). `null` when the request never left: a blocked URL, a host that doesn't resolve, an event no longer kept. |
| `responseStatus` | integer or null | Your endpoint's HTTP status, or `null` when there was no response. |
| `error` | string or null | Why the attempt failed (below); `null` on a `2xx`. |
| `responseSnippet` | string or null | The first 1,024 bytes of your endpoint's response body, as text. `null` when the body was empty or not text. |
| `nextAttemptAt` | string or null | When the next attempt is due after this one; `null` after the last or a successful one. |

| `error` | What happened |
|---|---|
| `http_<status>` | Your endpoint answered with a status that isn't `2xx`, for example `http_503`. A `3xx` counts too (`http_301`): redirects are not followed. |
| `timeout` | No answer within 10 seconds. |
| `connection_refused` | Your server refused the connection: nothing is listening on that host and port. |
| `connection_reset` | Your server closed the connection before answering. |
| `tls_failed` | The secure connection failed: an expired, self-signed or wrong-host certificate, or no TLS version in common. |
| `connect_failed` | Any other failure to connect, for example a host that can't be reached. |
| `dns_failed` | The URL's host doesn't resolve. Not sent. |
| `blocked_url` | The URL points to a private, local or reserved address. Not sent. |
| `invalid_url` | The URL is not valid. Not sent. |
| `response_too_large` | Your endpoint answered with a body over 1 MB. |
| `event_unavailable` | The event's body was no longer kept, so nothing was sent. |
| `internal_error` | We could not sign or build the request. Not sent; it is retried. |

```json title="GET /v1/monitors/{id}/deliveries/{deliveryId} (excerpt)"
{
  "id": "whd_01jc8t3a0d4f6h8k0m2p4r6t8x",
  "eventType": "monitor.run.succeeded",
  "status": "succeeded",
  "attempts": 3,
  "attemptLog": [
    {
      "attempt": 1,
      "startedAt": "2026-11-09T12:00:01.230Z",
      "durationMs": 212,
      "responseStatus": 503,
      "error": "http_503",
      "responseSnippet": "{\"error\":\"maintenance\"}",
      "nextAttemptAt": "2026-11-09T12:00:06.442Z"
    },
    {
      "attempt": 2,
      "startedAt": "2026-11-09T12:00:06.442Z",
      "durationMs": 10004,
      "responseStatus": null,
      "error": "timeout",
      "responseSnippet": null,
      "nextAttemptAt": "2026-11-09T12:00:46.446Z"
    },
    {
      "attempt": 3,
      "startedAt": "2026-11-09T12:00:46.446Z",
      "durationMs": 87,
      "responseStatus": 200,
      "error": null,
      "responseSnippet": "ok",
      "nextAttemptAt": null
    }
  ]
}
```

The log is kept as long as its delivery ([How long events are kept](#how-long-events-are-kept)). The delivery lists keep their shape: `lastResponseStatus` and `lastError` (a short line) describe the last attempt only.

## Answer with a 2xx, quickly

Any `2xx` status within 10 seconds counts as delivered; anything else, a timeout or a refused connection is a failed attempt, which is retried. Answer first and do the work afterwards, for example by putting the event on a queue. Keep the response body short and free of secrets: we keep its first 1,024 bytes in the attempt log, where everyone who can see your deliveries can read it.

- Redirects are not followed: a `3xx` is a failed attempt. Point the monitor at the final URL.
- The URL must be `https://` and public. Private, local and internal addresses are refused when you save the URL, and again on every attempt, so an address that later resolves to a private network is never contacted.
- Events can arrive in a different order than they happened (a retry can land after a newer event). Order by `createdAt` (or `run.createdAt`) if it matters, and ignore an `id` you have already handled.

## Verify the signature

The `PrimaryAPI-Signature` header is `t=<timestamp>,v1=<signature>`: `<timestamp>` is when this attempt was signed, in Unix seconds, and `<signature>` is the hex HMAC-SHA256 of `<timestamp>.<raw body>`, keyed with your signing secret (the whole `whsec_…` string). To check a request:

Read the **raw** body, exactly the bytes you received. Parsing the JSON and serialising it again changes the bytes, and the signature no longer matches.

Split the header on `,` and each part on the first `=`: take `t`, and every `v1` (there is one today; accept a match with any of them).

Compute HMAC-SHA256 of `t + "." + rawBody` with the secret, as hex, and compare it with `v1` in constant time.

Refuse a `t` more than 5 minutes away from your clock: that stops someone from replaying an old request they captured.

```ts tab="Node.js"
import crypto from 'node:crypto';
import express from 'express';

const SECRET = process.env.PRIMARYAPI_WEBHOOK_SECRET!; // whsec_…
const TOLERANCE_SECONDS = 300;

export function verifyPrimaryApiSignature(rawBody: string, header: string | undefined): boolean {
  if (!header) return false;
  let timestamp = '';
  const signatures: string[] = [];
  for (const part of header.split(',')) {
    const i = part.indexOf('=');
    const key = part.slice(0, i).trim();
    const value = part.slice(i + 1).trim();
    if (key === 't') timestamp = value;
    if (key === 'v1') signatures.push(value);
  }
  if (!/^\d+$/.test(timestamp)) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
  const expected = crypto.createHmac('sha256', SECRET).update(`${timestamp}.${rawBody}`).digest();
  return signatures.some((s) => {
    const got = Buffer.from(s, 'hex');
    return got.length === expected.length && crypto.timingSafeEqual(got, expected);
  });
}

const app = express();

// express.raw keeps the exact bytes: never verify a body that went through express.json().
app.post('/hooks/primaryapi', express.raw({ type: 'application/json' }), (req, res) => {
  const rawBody = req.body.toString('utf8');
  if (!verifyPrimaryApiSignature(rawBody, req.get('PrimaryAPI-Signature'))) {
    return res.status(400).send('invalid signature');
  }
  const event = JSON.parse(rawBody);
  res.sendStatus(200); // answer first…
  handleEvent(event); // …then work. Skip an event.id you have already handled.
});
```

```python tab="Python"
import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

SECRET = os.environ["PRIMARYAPI_WEBHOOK_SECRET"].encode()  # whsec_…
TOLERANCE_SECONDS = 300

def verify_primaryapi_signature(raw_body: bytes, header: str | None) -> bool:
    if not header:
        return False
    timestamp, signatures = "", []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            timestamp = value
        elif key == "v1":
            signatures.append(value)
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(SECRET, timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, s) for s in signatures)

app = Flask(__name__)

@app.post("/hooks/primaryapi")
def primaryapi_webhook():
    raw_body = request.get_data()  # the exact bytes we sent
    if not verify_primaryapi_signature(raw_body, request.headers.get("PrimaryAPI-Signature")):
        abort(400)
    event = request.get_json()
    enqueue(event)  # do the work after answering; skip an event["id"] you have already handled
    return "", 200
```

Each attempt is signed afresh, so a retry carries a new `t` and `v1` for the same body.

## Retries

A failed attempt is retried after these waits, each counted from the attempt before:

| Attempt | Waits after the previous one | Total since the first |
|---|---|---|
| 1 | — | right after the run or the change |
| 2 | 5 seconds | 5 s |
| 3 | 30 seconds | 35 s |
| 4 | 2 minutes | 2 min 35 s |
| 5 | 5 minutes | 7 min 35 s |
| 6 | 15 minutes | 22 min 35 s |
| 7 | 1 hour | 1 h 23 min |
| 8 | 4 hours | 5 h 23 min |
| 9 | 12 hours | 17 h 23 min |
| 10 | 24 hours | 1 day 17 h |
| 11 | 48 hours | 3 days 17 h |

After the 11th failed attempt the delivery is marked `failed` and nothing more is sent for it. Every attempt carries the same `PrimaryAPI-Event-Id`. Retries continue while you fix your endpoint, so a short outage on your side loses nothing. The deliveries list (`GET /v1/monitors/{id}/deliveries` and the monitor's page in the dashboard) shows each delivery's status, its attempts, the next attempt's time and the last response; the [attempt log](#the-attempt-log) shows every attempt.

A monitor's webhook that is still undelivered after every retry counts as a failed run ([When runs keep failing](/docs/monitors#when-runs-keep-failing)). Deleting a monitor gives up the deliveries still waiting for a retry.

## Redeliver

`POST https://api.primaryapi.com/v1/monitors/{id}/deliveries/{deliveryId}/redeliver`

Auth: API key with run or full access, or a dashboard session (owners, admins, developers)

Sends the same event again as a new delivery: the same body and `PrimaryAPI-Event-Id`, a new `PrimaryAPI-Delivery-Id`, attempts counted from 1, to the monitor's **current** URL. Use it after fixing an endpoint, or to replay an event you lost. **201 Created**: the new delivery after its first attempt.

Redelivery needs the event's body, which is kept only as long as your plan says (below). Once it is gone the answer is `422 unprocessable` with `details.reason: "event_body_deleted"`.

## How long events are kept

An event's body is kept by the workspace's plan, fixed when the event is made: a later plan change doesn't shorten or extend what was already decided.

| Plan | Event bodies are kept | Redelivery |
|---|---|---|
| Pay as you go | Until its delivery is done (delivered, or retries used up) | Only while a delivery of the event is still pending or retrying |
| Builder | 7 days | Within 7 days |
| Pro | 30 days | Within 30 days |
| Scale | 90 days | Within 90 days |
| Enterprise | 90 days, or as agreed | Within that time |

- Deliveries and their attempt logs are listed for 30 days, or as long as the event's body is kept when that is longer. The delivery's status, attempts and times stay listed after the body is gone.
- A body is never deleted while a delivery of it is still pending or retrying.

## Test events

`POST https://api.primaryapi.com/v1/monitors/{id}/test`

Auth: API key with run or full access, or a dashboard session (owners, admins, developers)

Sends a `monitor.test` event, signed like any other, to check your endpoint and your signature check. It is free and runs nothing. **201 Created**: the delivery after its first attempt. Test events and redeliveries are capped together at 60 per minute per workspace (`429 rate_limited`).

## The signing secret

Every workspace has one signing secret for all its webhooks. Owners and admins see it in the dashboard (on the **Monitors** page); with the API it takes a key with full access:

`GET https://api.primaryapi.com/v1/webhooks/secret`

Auth: API key with full access, or a dashboard session (owners and admins)

**200 OK**: `{ "secret": "whsec_…", "createdAt": "…" }`, made on first use.

`POST https://api.primaryapi.com/v1/webhooks/secret/rotate`

Auth: API key with full access, or a dashboard session (owners and admins)

Replaces the secret. **200 OK**: the new `{ secret, createdAt }`. The new secret is in force at once: every later attempt, retries included, is signed with it. Deploy it to your endpoint right away; attempts your endpoint refuses in the meantime are retried on the schedule above. Treat the secret like a password: keep it out of source control and logs, and rotate it if it may have leaked.
