> ## Documentation Index
> Fetch the complete documentation index at: https://docs.myunite.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> Get a notification on your server when a pre-test finishes, fails or has its PDF ready, and verify the signature of each delivery.

Instead of calling `GET /pretests/{id}` from time to time, register an address on your server. Unite makes a signed `POST` to that address when something changes in a pre-test. The format follows the [Standard Webhooks](https://www.standardwebhooks.com) standard.

To manage endpoints through the API, the key needs the `webhooks:manage` scope. See [Authentication](https://docs.myunite.ai/en/authentication.md). Workspace administrators also register, test and remove endpoints in the workspace dashboard, without using a key.

## Events

| Event | When it happens |
| - | - |
| `pretest.completed` | The analysis finished and the result is available. |
| `pretest.failed` | The analysis could not be completed. The pre-test carries `error.code`. |
| `pretest.report_ready` | The analysis PDF is ready. For OOH and digital, it is usually generated on its own after `pretest.completed`. For email, it is only generated when someone asks for the PDF (`GET /pretests/{id}/report` or an export in the product), and the event arrives after that. Do not wait for this event for email without requesting the PDF. |

Each endpoint chooses the events it wants to receive. There is also the `ping` event, used only to [test the endpoint](#test-the-endpoint).

## Delivery body

The body is JSON:

```json theme={null}
{
  "id": "evt_0123456789abcdef0123456789abcdef",
  "type": "pretest.completed",
  "createdAt": "2026-11-16T14:32:08.000Z",
  "data": {
    "pretest": {
      "id": "PRETEST_ID",
      "object": "pretest",
      "status": "completed",
      "channel": "ooh",
      "title": "Summer · urban clock"
    }
  }
}
```

* `id`: identifies the event. It is the same value as the `webhook-id` header.
* `type`: the event type.
* `createdAt`: when the event happened, in ISO-8601 UTC.
* `data.pretest`: the pre-test, exactly as `GET /pretests/{id}` returns it at the time of the event (the example above shows only a few fields). See [Results](https://docs.myunite.ai/en/results.md).

The `ping` event arrives with an empty `data` (`{}`).

## Headers

| Header | Value |
| - | - |
| `webhook-id` | Event id. The same on every attempt of the same delivery. |
| `webhook-timestamp` | Time of sending, in seconds since 1970 (Unix). Changes on each attempt. |
| `webhook-signature` | `v1,` followed by the signature in base64. |
| `content-type` | `application/json` |
| `user-agent` | `Unite-Webhooks/1.0` |

## Create an endpoint

```bash curl theme={null}
curl -X POST https://myunite.ai/api/v1/webhook-endpoints \
  -H "Authorization: Bearer $UNITE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/webhooks/unite",
    "events": ["pretest.completed", "pretest.failed", "pretest.report_ready"],
    "description": "CRM integration"
  }'
```

```javascript JavaScript theme={null}
const res = await fetch("https://myunite.ai/api/v1/webhook-endpoints", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.UNITE_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    url: "https://example.com/webhooks/unite",
    events: ["pretest.completed", "pretest.failed", "pretest.report_ready"],
    description: "CRM integration",
  }),
});
const endpoint = await res.json();
console.log(endpoint.id, endpoint.secret); // store the secret now
```

```python Python theme={null}
import os
import requests

res = requests.post(
    "https://myunite.ai/api/v1/webhook-endpoints",
    headers={"Authorization": f"Bearer {os.environ['UNITE_API_KEY']}"},
    json={
        "url": "https://example.com/webhooks/unite",
        "events": ["pretest.completed", "pretest.failed", "pretest.report_ready"],
        "description": "CRM integration",
    },
)
endpoint = res.json()
print(endpoint["id"], endpoint["secret"])  # store the secret now
```

The response is `201` and carries the endpoint, with `id`, `status` (`enabled` or `disabled`) and the `secret` field, in the format `whsec_YOUR_SECRET_HERE`.

> [!WARNING]
>
> The secret is shown **only once**, in this response. The endpoint list never returns it. Keep it in an environment variable on your back end. If you lose it, delete the endpoint and create another one.

Address rules:

* It must use `https`, on port 443 (the default).
* It cannot include a username or password.
* It must resolve to a public internet address. Private and local addresses are refused.

A refused address responds [`webhook_url_rejected`](https://docs.myunite.ai/en/errors#webhook_url_rejected). Each workspace can have up to 5 endpoints, enabled or not. Beyond that, the response is [`webhook_endpoint_limit`](https://docs.myunite.ai/en/errors#webhook_endpoint_limit).

To list, use `GET /webhook-endpoints`. To delete, `DELETE /webhook-endpoints/{id}`: the endpoint and its delivery history are removed, and deliveries still waiting are discarded.

## Verify the signature

Every request is signed with the endpoint secret. **Verify the signature before trusting the content**: anyone who finds out your address can send a fake `POST`.

Use the official Standard Webhooks library. It checks the signature and rejects a `webhook-timestamp` more than 5 minutes off, which blocks the replay of an old request captured by a third party.

> [!WARNING]
>
> Sign and verify the body **exactly as it arrived** (the raw bytes). If your framework converts the JSON into an object and then back into text, the signature stops matching. Read the raw body before any conversion.

```javascript Node (Express) theme={null}
// npm install standardwebhooks express
import express from "express";
import { Webhook, WebhookVerificationError } from "standardwebhooks";

const app = express();
const wh = new Webhook(process.env.UNITE_WEBHOOK_SECRET); // whsec_YOUR_SECRET_HERE

// express.raw hands over the raw body, without converting the JSON
app.post("/webhooks/unite", express.raw({ type: "application/json" }), (req, res) => {
  let event;
  try {
    event = wh.verify(req.body.toString("utf8"), req.headers);
  } catch (err) {
    if (err instanceof WebhookVerificationError) return res.sendStatus(400);
    throw err;
  }

  // Respond first. Processing runs after the response and never
  // leaves a failure unhandled (a loose rejection brings Node down).
  res.sendStatus(200);
  handleEvent(event).catch((err) => console.error("failed to process the event", event.id, err));
});

app.listen(3000);
```

```python Python (Flask) theme={null}
# pip install standardwebhooks flask
import os
from flask import Flask, request
from standardwebhooks.webhooks import Webhook, WebhookVerificationError

app = Flask(__name__)
wh = Webhook(os.environ["UNITE_WEBHOOK_SECRET"])  # whsec_YOUR_SECRET_HERE

@app.post("/webhooks/unite")
def unite_webhook():
    try:
        # get_data() returns the raw body, without converting the JSON
        event = wh.verify(request.get_data(), dict(request.headers))
    except WebhookVerificationError:
        return "", 400

    # Respond fast and hand the event to your task queue
    enqueue(event)
    return "", 200
```

This only takes the processing out of the response. Real background work (writing to a database, calling other systems, retrying on error) belongs to your task queue: store the event, return `200` and let a worker process it.

`verify` returns the event already converted into an object and throws `WebhookVerificationError` if the signature does not match or if the `webhook-timestamp` is too old. Respond `400` in those cases.

### Without the library

If you prefer not to use the library, the signature is calculated like this:

1. Remove the `whsec_` prefix from the secret and decode the rest from base64. The result is the key.
2. Build the text `webhook-id` + `.` + `webhook-timestamp` + `.` + raw body.
3. Calculate the HMAC-SHA256 of that text with the key and encode it in base64.
4. Compare with each item in `webhook-signature` (separated by spaces, each in the format `v1,<base64>`), in constant time.
5. Reject the request if `webhook-timestamp` differs from your clock by more than 5 minutes.

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

function verify(secret, headers, rawBody) {
  const id = headers["webhook-id"];
  const timestamp = Number(headers["webhook-timestamp"]);
  const header = headers["webhook-signature"];
  if (typeof id !== "string" || typeof header !== "string") return false;
  if (!Number.isFinite(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > 300) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key)
    .update(`${id}.${timestamp}.${rawBody}`)
    .digest();

  return header.split(" ").some((item) => {
    const [version, signature] = item.split(",");
    if (version !== "v1" || !signature) return false;
    const received = Buffer.from(signature, "base64");
    return received.length === expected.length && timingSafeEqual(received, expected);
  });
}
```

The same calculation in Python:

```python theme={null}
import base64
import hashlib
import hmac
import time

def verify(secret, headers, raw_body):
    headers = {k.lower(): v for k, v in headers.items()}  # header names are case-insensitive
    msg_id = headers.get("webhook-id")
    header = headers.get("webhook-signature")
    try:
        timestamp = int(headers.get("webhook-timestamp"))
    except (TypeError, ValueError):
        return False
    if not msg_id or not header or abs(time.time() - timestamp) > 300:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body  # raw_body as bytes
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()

    for item in header.split(" "):
        version, _, signature = item.partition(",")
        if version == "v1" and signature and hmac.compare_digest(signature, expected):
            return True
    return False
```

Header names are case-insensitive (the Python above lowercases them before reading). In both examples, a format failure (missing or malformed header) returns `false` and never throws: respond `400`.

## Respond and process

* Respond with `2xx` within **10 seconds**. Beyond that, the attempt counts as a failure.
* Do the minimum before responding: verify the signature, store the event and return `200`. Process the rest in the background.
* Redirects (`3xx`) are **not** followed and count as a failure. Register the final address.
* Unite does not send from fixed IP addresses. **Do not** allowlist by IP: signature verification is what guarantees the origin.

## Retries

Any response that is not `2xx` (or no response within 10 seconds) causes a new attempt. There are up to 12 attempts per delivery, with an increasing interval from 30 seconds up to 1 hour, over about 5 to 6 hours. If all fail, the delivery is left as `failed`. A delivery that stays pending for more than 7 hours also shows as `failed`, with `lastError` equal to `expired`.

The exception is status `410`: it means "this address no longer exists". When your destination responds `410`, Unite **disables the endpoint** (`status: "disabled"`, `disabledReason: "gone"`) and does not try again. Another exception: if the address starts resolving to a private or blocked address, the delivery is closed without a new attempt, with `lastError` as `url_rejected:private_address`. If API access is turned off for the workspace, the delivery is also closed without a new attempt, with `lastError` as `feature_disabled`. A disabled endpoint no longer receives events and cannot be tested; create another one to receive again. Only respond `410` on purpose.

An endpoint is also disabled on its own, with `disabledReason: "creator_removed"`, when the person who created it leaves the workspace or loses access to it. It stops receiving events and cannot be tested; an administrator registers another endpoint. Revoking an API key does **not** affect endpoints: they belong to the workspace, and administrators manage them in the workspace dashboard.

## Order and repeats

* **There is no ordering guarantee.** `pretest.report_ready` can arrive before `pretest.completed`, and an old attempt can arrive after a newer one.
* **An event can arrive more than once.** Use the `webhook-id` to ignore what you already processed. Store the received ids and discard repeats.
* **The truth is in the `GET`.** The event tells you something changed. For the current state, call `GET /pretests/{id}`, and do not rely on arrival order.

```javascript theme={null}
const seen = new Set(); // in production, use a database with expiry

async function handleEvent(event) {
  if (seen.has(event.id)) return; // already processed
  seen.add(event.id);

  // fetch the current state instead of trusting only the event body
  const res = await fetch(
    `https://myunite.ai/api/v1/pretests/${event.data.pretest.id}`,
    { headers: { Authorization: `Bearer ${process.env.UNITE_API_KEY}` } },
  );
  const pretest = await res.json();
  // ...
}
```

## Test the endpoint

`POST /webhook-endpoints/{id}/test` sends a signed `ping` event, like the others. The response is `202`, with the delivery id and `status: "pending"`. The result shows up in the delivery list.

```bash curl theme={null}
curl -X POST https://myunite.ai/api/v1/webhook-endpoints/ENDPOINT_ID/test \
  -H "Authorization: Bearer $UNITE_API_KEY"
```

```javascript JavaScript theme={null}
const res = await fetch(
  "https://myunite.ai/api/v1/webhook-endpoints/ENDPOINT_ID/test",
  {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.UNITE_API_KEY}` },
  },
);
console.log(res.status, await res.json()); // 202
```

```python Python theme={null}
import os
import requests

res = requests.post(
    "https://myunite.ai/api/v1/webhook-endpoints/ENDPOINT_ID/test",
    headers={"Authorization": f"Bearer {os.environ['UNITE_API_KEY']}"},
)
print(res.status_code, res.json())  # 202
```

A disabled endpoint cannot be tested.

## Read the delivery list

`GET /webhook-endpoints/{id}/deliveries` returns the last 50 deliveries of that endpoint, newest first.

```bash curl theme={null}
curl https://myunite.ai/api/v1/webhook-endpoints/ENDPOINT_ID/deliveries \
  -H "Authorization: Bearer $UNITE_API_KEY"
```

```javascript JavaScript theme={null}
const res = await fetch(
  "https://myunite.ai/api/v1/webhook-endpoints/ENDPOINT_ID/deliveries",
  { headers: { Authorization: `Bearer ${process.env.UNITE_API_KEY}` } },
);
const { data } = await res.json();
for (const d of data) {
  console.log(d.eventType, d.status, d.attempts, d.lastStatusCode, d.lastError);
}
```

```python Python theme={null}
import os
import requests

res = requests.get(
    "https://myunite.ai/api/v1/webhook-endpoints/ENDPOINT_ID/deliveries",
    headers={"Authorization": f"Bearer {os.environ['UNITE_API_KEY']}"},
)
for d in res.json()["data"]:
    print(d["eventType"], d["status"], d["attempts"], d["lastStatusCode"], d["lastError"])
```

Each item carries:

| Field | Description |
| - | - |
| `id` | Delivery id. |
| `eventId` | The same as `webhook-id`. Use it to match against what your server received. |
| `eventType` | The event type, or `ping` in a test. |
| `status` | `pending` (still trying), `delivered` or `failed`. |
| `attempts` | How many attempts have been made. |
| `lastStatusCode` | HTTP status of the last attempt. `null` if there was no response. |
| `lastError` | Short reason for the last failure, for example `timeout`, `http_500`, `redirect`, `expired`, `url_rejected:private_address` or `feature_disabled`. `null` if there was no failure. |
| `createdAt` | When the delivery was created. |
| `deliveredAt` | When it was delivered. `null` until then. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.