# Webhooks

> Have iMario tell your server when a study, report, download or audience is done, and verify each event it sends.

Source: https://imario.ai/docs/api/webhooks

## How webhooks work

When something your endpoint subscribes to happens, iMario sends it an HTTPS POST with a JSON event. Your server answers with a 2xx status, and the event counts as delivered. You no longer need to poll a study or a report to learn that it finished.

Owners and admins manage endpoints, in **Settings > MCP & API** or with the [webhook endpoints](https://imario.ai/docs/api/reference/webhooks) API.

## Add an endpoint

1. Open **Settings > MCP & API**. Under **Webhooks**, select **Add endpoint**.
2. Enter the **URL**: a public `https://` address. Add a **Description** if you like.
3. Choose the **Mode**: **Live** receives events from live work, **Test** only what test keys do in the [sandbox](https://imario.ai/docs/api/sandbox).
4. Under **Events**, keep **All events**, which includes event types added later, or choose the ones you want.
5. Select **Add endpoint**, then copy the **Signing secret** (`whsec_...`). It is shown once.

From code, `POST /v1/webhook-endpoints` with a key that holds `webhooks:write` does the same, and answers with the secret once. An endpoint made with a test key is a test endpoint. A workspace holds at most 20 endpoints, live and test together.

The address must be https and must resolve to public addresses only. iMario checks it when you save it and again before every delivery, and never follows a redirect.

Each endpoint's menu has **Send test event**, **Delivery log**, **Edit**, **Rotate secret** and **Delete**, and a switch turns it off and on.

## Events

| Event | When it is sent | `data.object` |
|---|---|---|
| `study.completed` | A study ended with results. Read `outcome`: it can still be `partial_answers` or `no_answers` | `study` |
| `study.failed` | A study failed. What it was charged is refunded; `error` says why | `study` |
| `report.completed` | A report finished writing, including a rewrite | `report` |
| `report.failed` | A report could not be written. Its charge is refunded; after a failed rewrite the earlier report stays readable | `report` |
| `export.completed` | A report download is ready. Its `download_url` is valid for one hour from the event; `GET /v1/exports/{id}` gives a fresh link | `export` |
| `audience.ready` | An audience can be used: its build has found enough people for a study to draw its respondents from. Sent once per build | `audience` |
| `audience.failed` | An audience could not be built, or, built from files, needs a person's choice: `status` is `failed` or `needs_review`, and `failure` says why | `audience` |
| `auto_study.paused` | An Auto study paused because the next step could not be paid for. Sent once per pause; it goes on only after Continue, in the web app or with `POST /v1/auto-studies/{id}/continue` | `auto_study` |
| `auto_study.completed` | An Auto study ended. `status` says whether it finished, was stopped or failed; `report_id` names its report | `auto_study` |
| `credits.low` | The balance that pays for the workspace fell below 100 credits or 10% of the last credits added (a purchase, a grant or a bonus), whichever is higher. Sent once each time it falls below, to live endpoints | `credit_balance`: `balance`, `threshold`, `paid_by` |
| `ping` | You chose **Send test event**, or called `POST /v1/webhook-endpoints/{id}/test`. Sent to that endpoint alone | `webhook_endpoint` |

`credits.low` watches the workspace's credit pool, or, in a workspace without a pool, its owner's wallet. `ping` cannot be subscribed to (naming it in `events` is refused): it is only sent on request. The object in an event has the same fields as the API returns for it; the [reference](https://imario.ai/docs/api/reference) describes each one.

## The event

```json
{
  "id": "evt_5f2c9a1e7b3d4c6a8e0f1b2d",
  "object": "event",
  "type": "study.completed",
  "created_at": "2026-11-24T10:06:42Z",
  "livemode": true,
  "data": {
    "object": {
      "object": "study",
      "id": "c41d7e2a-9b3f-4a5c-8e6d-0f1a2b3c4d5e",
      "livemode": true,
      "kind": "closed_question",
      "status": "completed",
      "outcome": "answers",
      "credits": { "estimated": 50, "charged": 50 }
    }
  }
}
```

The object is shortened here. Each delivery carries these headers, as the [Standard Webhooks](https://www.standardwebhooks.com) specification sets them:

| Header | Value |
|---|---|
| `webhook-id` | The event's id, the same as `id` in the body and the same on every attempt |
| `webhook-timestamp` | When this attempt was sent, in Unix seconds |
| `webhook-signature` | `v1,` and the signature. During a secret rotation, two signatures separated by a space |
| `content-type` | `application/json` |
| `user-agent` | `iMario-Webhooks/1.0` |

## Verify the signature

Check every event before you trust it. The signature is an HMAC-SHA256 of the event id, the timestamp and the body:

1. Read the body exactly as it arrived, as bytes. Do not parse and re-serialize the JSON first: the signature covers the original bytes.
2. Join `webhook-id`, `.`, `webhook-timestamp`, `.` and the body.
3. The key is the base64-decoded part of your secret after `whsec_`.
4. Compute the HMAC-SHA256 of the joined content with that key and base64-encode it.
5. Compare it with each signature after `v1,` in `webhook-signature`, in constant time. One match is enough.
6. Refuse the event if the timestamp is more than 5 minutes from your clock, so an old event cannot be replayed.

Python:

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


def verify(secret: str, headers: dict, body: bytes, tolerance: int = 300) -> bool:
    msg_id = headers["webhook-id"]
    timestamp = headers["webhook-timestamp"]
    if abs(time.time() - int(timestamp)) > tolerance:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    for part in headers["webhook-signature"].split(" "):
        version, _, signature = part.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return True
    return False
```

Node.js:

```js
import crypto from 'node:crypto';

export function verify(secret, headers, rawBody, toleranceSeconds = 300) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto.createHmac('sha256', key)
    .update(`${id}.${timestamp}.`)
    .update(rawBody)
    .digest();
  return headers['webhook-signature'].split(' ').some((part) => {
    const [version, signature] = part.split(',');
    if (version !== 'v1' || !signature) return false;
    const given = Buffer.from(signature, 'base64');
    return given.length === expected.length && crypto.timingSafeEqual(given, expected);
  });
}
```

In Node, read the raw body (for example `express.raw({ type: 'application/json' })`) and parse the JSON only after it verifies. A Standard Webhooks library for your language verifies these headers as well.

## Rotate the secret

**Rotate secret** (or `POST /v1/webhook-endpoints/{id}/rotate-secret`) shows a new secret once. For 24 hours each delivery carries two signatures, one with the new secret and one with the old, so a receiver that checks every signature keeps working while you switch. Put the new secret in place within those 24 hours.

## Answer quickly

Answer with any 2xx status within 10 seconds, then do the work, for example by putting the event on your own queue. Any other status, a timeout or a redirect counts as a failed attempt. Only the status matters, not what your answer contains.

## Retries and turning off

A failed attempt is tried again after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 12 hours: seven attempts over about 21 hours. Then the delivery is marked failed. Every attempt has the same `webhook-id` and a new timestamp and signature.

If every delivery to an endpoint has failed for 3 days, iMario turns the endpoint off (`disabled_reason` is `delivery_failures`) and tells the workspace's owners and admins. Deliveries still waiting are dropped. Fix the receiver, then turn the endpoint on again with its switch in Settings or with `PATCH /v1/webhook-endpoints/{id}` and `"enabled": true`. Events from the time it was off are not sent afterwards, so read the latest state with the API.

Deliveries are kept for 30 days. `GET /v1/webhook-endpoints/{id}/deliveries` pages through them; **Delivery log** in Settings shows the latest 50. Each has its status, attempts and the last status code.

## Delivered at least once

An event can arrive more than once, for example when your 2xx answer was lost on the way back. Deduplicate on `webhook-id`: it is the event's id, the same on every attempt and for a second report of the same change. Events can also arrive out of order; when order matters, ask the API for the object's current state.

## Test your receiver

**Send test event** (or `POST /v1/webhook-endpoints/{id}/test`) sends a `ping` to that endpoint alone, whatever events it subscribes to; the endpoint must be on. To see real event types without spending, create a test endpoint and run work with a test key: see [Sandbox and test keys](https://imario.ai/docs/api/sandbox).
