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

# Webhooks: signed call events

> Get a signed event each time a call moves on: event types, payloads, final results with the transcript, signature checks, retries and dedupe.

Pass `webhook_url` when you [create a call](https://docs.miraiminds.co/v2/calls.md#create-a-call) and we POST
a signed JSON event at each lifecycle transition. Webhooks are the intended way
to learn a call's outcome. Use polling only as a fallback. To show a call while
it runs, turn by turn, read its [live events](https://docs.miraiminds.co/v2/live-events.md).

Your endpoint must be **public HTTPS** and must return a **2xx** quickly. Any
other status, or a connection failure, triggers [retries](#retries).

> [!TIP]
>
> To receive events for every call of an agent or of your whole workspace, campaign
> events, low-balance alerts and payment notices without a URL on each call, use
> [webhook subscriptions](https://docs.miraiminds.co/v2/webhook-subscriptions.md).

## Event envelope

Every event has the same shape.

```json theme={"system"}
{
  "id": "evt_01JZQ9C5N9P4R7S3T6V8W2X4YB",
  "type": "call.completed",
  "created_at": "2026-07-26T09:16:38Z",
  "data": {
    "call": {
      "id": "call_01JZQ9B4M8N3P6R2S5T7V9W1YA",
      "object": "call",
      "agent_id": "agt_01JZQ8F3K7M2N5P9R4T6V8W0XZ",
      "to": "+919876543210",
      "status": "completed",
      "ended_reason": "assistant-ended-call",
      "started_at": "2026-07-26T09:15:02Z",
      "ended_at": "2026-07-26T09:16:38Z",
      "duration_secs": 96,
      "cost": { "amount_inr": 5, "per_min_inr": 3, "billing_block_secs": 10 }
    }
  }
}
```

| Field | Description |
| :- | :- |
| `id` | `evt_<ulid>`. Unique per delivery attempt group: retries of the same event reuse it. [Dedupe on this](#idempotency). |
| `type` | See [event types](#event-types). |
| `created_at` | When the event was generated, not when it was delivered. |
| `data.call` | The [call object](https://docs.miraiminds.co/v2/calls.md#the-call-object) as it stands at that moment, with its money in `cost`. A few fields come only when you read the call: `tier`, `cost_inr`, `recording_available` and `transcript_available`. On a `campaign.*` event this is `data.campaign` instead. |
| `data.call.metadata` | The [`metadata`](https://docs.miraiminds.co/v2/calls#metadata) you set when creating the call, unchanged, on every event for that call. On a campaign call, the contact's [`metadata`](https://docs.miraiminds.co/v2/campaigns#your-own-fields-metadata): the columns kept as extra info in the console. Absent when the call has none. |
| `data.call.call_settings` | The voice and languages of the call, with who chose each. `call.queued` has them before pre-call tools run; every later event has the ones the call used. See [call settings](https://docs.miraiminds.co/v2/calls.md#on-the-call-object). |
| `data.wallet` | Your wallet balance right after the call was billed. Only on the four terminal events. See [wallet balance](#wallet-balance-on-call-ending-events). |

Treat the envelope as **additive**: new fields appear without a version bump.
Ignore what you do not recognise.

## Event types

| Type | Fires when | `data.call.status` |
| :- | :- | :- |
| `call.queued` | The call is admitted to the queue. This event is opt-in: [ask us to enable it](mailto:help@miraiminds.co?subject=Enable%20call.queued). | `queued` |
| `call.started` | Media is live; the conversation has begun. | `in_progress` |
| `call.completed` | The call connected and finished normally. | `completed` |
| `call.processed` | Analysis and post-call tool processing finished for a call with those features enabled. For a call created with `final_results: true`, it fires when the [final results](#final-results) are ready. | Unchanged terminal status |
| `call.voicemail` | An answering machine answered. | `voicemail` |
| `call.failed` | The call did not connect, or the pipeline errored. | `no_answer`, `busy`, `failed`, `timeout` |
| `call.aborted` | You cancelled it with [`POST /abort`](https://docs.miraiminds.co/v2/calls#abort-a-call), whether it was queued, ringing or mid-conversation. | `aborted` |

Exactly one terminal event fires per call: `call.completed`, `call.voicemail`,
`call.failed` or `call.aborted`.

`call.processed` is a separate processing event, not another terminal event.
It includes `data.processing.version`, analysis status, and post-call tool status.
Explicit reruns produce a new version. Background on-call tools can finish
later; read their receipts separately. See [Tools: call.processed](https://docs.miraiminds.co/v2/tools.md#receive-call-processed).
For the finished transcript in the same event, create the call with
`final_results: true`. See [final results](#final-results).

A call run by a [node-based agent](https://docs.miraiminds.co/v2/node-agents.md) always sends
`call.processed` when it has a `webhook_url`, with the flow's outcome at
`data.call.flow`, unless the agent sets `emit_processed_webhook: false`. See
[final results](#final-results).

[Campaigns](https://docs.miraiminds.co/v2/campaigns.md) add five more event types. We deliver them to the
campaign's own `webhook_url`, signed with the same workspace secret and in the
same envelope, with `data.campaign` in place of `data.call`.

| Type | Fires when |
| :- | :- |
| `campaign.started` | The first `POST /start` takes effect. Once per campaign. |
| `campaign.paused` | You paused it, or the campaign paused itself: the money gate, its [connected-call limit](https://docs.miraiminds.co/v2/campaigns.md#pause-after-connected-calls) or its number. Read `data.campaign.pause_reason`. |
| `campaign.resumed` | Dialling resumed. |
| `campaign.completed` | Every contact reached a final state, or the date range ran out. An [always-on](https://docs.miraiminds.co/v2/campaigns.md#always-on-campaigns) campaign sends it only when the date range runs out. |
| `campaign.stopped` | You stopped it. |

A campaign's calls emit the ordinary `call.*` events as well, to the same URL.
For the payload, see [Webhooks](https://docs.miraiminds.co/v2/campaigns.md#webhooks) on the Campaigns page.

A campaign's URL also receives `phone_number.rested`, `phone_number.resumed`,
`phone_number.cooling`, `phone_number.alert` and `phone_pool.degraded` for the
numbers and pools it calls from. They carry `data.phone_number` or
`data.phone_pool` instead of `data.call`. See
[Phone numbers and pools](https://docs.miraiminds.co/v2/phone-numbers.md#webhook-events).

```mermaid theme={"system"}
sequenceDiagram
    participant You
    participant API as Voice Infra
    participant Phone as Customer

    You->>API: POST /v2/calls
    API-->>You: 202 {id, status:"queued"}
    API-->>You: call.queued (opt-in)
    API->>Phone: dial
    Phone-->>API: answer
    API-->>You: call.started
    Note over API,Phone: conversation
    Phone-->>API: hangup
    API-->>You: call.completed
```

### `call.failed`

Read `data.call.status` to tell the failure modes apart. A `no_answer` is
worth retrying the next day, while a `failed` is worth paging someone about.

```json theme={"system"}
{
  "id": "evt_01JZQ9E7Q3S6T9V5W8X1Y4Z6AC",
  "type": "call.failed",
  "created_at": "2026-07-26T09:15:44Z",
  "data": {
    "call": {
      "id": "call_01JZQ9B4M8N3P6R2S5T7V9W1YB",
      "object": "call",
      "agent_id": "agt_01JZQ8F3K7M2N5P9R4T6V8W0XZ",
      "to": "+919876543211",
      "status": "no_answer",
      "ended_reason": "customer-did-not-answer",
      "started_at": null,
      "ended_at": "2026-07-26T09:15:44Z",
      "duration_secs": 0,
      "cost": { "amount_inr": 0, "per_min_inr": 3, "billing_block_secs": 10 }
    }
  }
}
```

### `call.voicemail`

```json theme={"system"}
{
  "id": "evt_01JZQ9F8R4T7V2W5X8Y1Z4A6BD",
  "type": "call.voicemail",
  "created_at": "2026-07-26T09:18:20Z",
  "data": {
    "call": {
      "id": "call_01JZQ9B4M8N3P6R2S5T7V9W1YC",
      "object": "call",
      "agent_id": "agt_01JZQ8F3K7M2N5P9R4T6V8W0XZ",
      "to": "+919876543212",
      "status": "voicemail",
      "ended_reason": "voicemail",
      "started_at": "2026-07-26T09:18:02Z",
      "ended_at": "2026-07-26T09:18:20Z",
      "duration_secs": 18,
      "cost": { "amount_inr": 1, "per_min_inr": 3, "billing_block_secs": 10 }
    }
  }
}
```

`status: voicemail` always comes with `ended_reason: "voicemail"`. That reason
is how we identify the answering machine in the first place, so you will only
ever see the two together.

Voicemail calls are billed, because media was live. The 18-second call above
bills as two 10-second blocks: ₹1.00 on T3. See
[metering](https://docs.miraiminds.co/general/tiers.md#metering).

### `call.aborted`

```json theme={"system"}
{
  "id": "evt_01JZQ9G9S5V8W3X6Y9Z2A5B7CE",
  "type": "call.aborted",
  "created_at": "2026-07-26T09:14:51Z",
  "data": {
    "call": {
      "id": "call_01JZQ9B4M8N3P6R2S5T7V9W1YD",
      "object": "call",
      "agent_id": "agt_01JZQ8F3K7M2N5P9R4T6V8W0XZ",
      "to": "+919876543213",
      "status": "aborted",
      "ended_reason": "aborted-by-api",
      "started_at": null,
      "ended_at": "2026-07-26T09:14:51Z",
      "duration_secs": 0,
      "cost": { "amount_inr": 0, "per_min_inr": 3, "billing_block_secs": 10 }
    }
  }
}
```

`aborted-by-api` is the only `ended_reason` an abort produces, whether you
cancelled the call in the queue, mid-ring or mid-conversation. An aborted call is
billed for the time it was connected; one cancelled in the queue or while ringing
costs nothing.

### Wallet balance on call-ending events

`call.completed`, `call.failed`, `call.voicemail` and `call.aborted` carry your
wallet balance beside the call, so you can top up or hold back new calls
without polling the wallet.

```json title="call.completed with data.wallet" theme={"system"}
{
  "id": "evt_01K8Q2N6S8U0W2Y4A6C8E0G2J4",
  "type": "call.completed",
  "created_at": "2026-10-15T10:01:52Z",
  "data": {
    "call": {
      "id": "call_01K8Q2M4Q6S8T0V2X4Z6A8C0EG",
      "object": "call",
      "agent_id": "agt_01JZQ8F3K7M2N5P9R4T6V8W0XZ",
      "to": "+919876543210",
      "status": "completed",
      "ended_reason": "customer-ended-call",
      "started_at": "2026-10-15T10:00:16Z",
      "ended_at": "2026-10-15T10:01:52Z",
      "duration_secs": 96,
      "cost": { "amount_inr": 5, "per_min_inr": 3, "billing_block_secs": 10 }
    },
    "wallet": { "balance_inr": 18432.5 }
  }
}
```

`data.wallet.balance_inr` is the workspace balance in rupees, read right after
this call was billed. It is the number [`GET /v2/wallet`](https://docs.miraiminds.co/v2/wallet#get-balance)
would have answered at that moment. A call that cost nothing, such as a
`no_answer` or a `busy`, still reports the balance.

Calls end and are billed side by side, so the balance is a snapshot. A later
event can show a lower balance than one that arrived before it, and
[retries](#retries) can deliver events out of order. Compare each value with
your own threshold instead of with the previous event, and read
`GET /v2/wallet` when you need the current figure.

`data.wallet` is left out when we could not read the balance, for example when
the call's billing could not be recorded. We never send `0` in place of a
number we do not know, so treat a missing `wallet` as unknown. It appears only on
the four terminal events, never on `call.queued`, `call.started`,
`call.processed` or campaign events, and it is not part of the call object.

***

## Final results

Create a call with `final_results: true` to receive one `call.processed` event
with everything about the finished call: the call object, the transcript, and
the status of analysis and post-call tools. Start processing a conversation
when this event arrives. [Campaign](https://docs.miraiminds.co/v2/campaigns.md#webhooks) calls send it by
default.

```json title="call.processed with final_results: true" theme={"system"}
{
  "id": "evt_01K8B4R2T4V6X8Z0B2D4F6H8K0",
  "type": "call.processed",
  "created_at": "2026-09-27T10:10:41Z",
  "data": {
    "call": {
      "id": "call_01K8B2M4Q6S8T0V2X4Z6A8C0EG",
      "object": "call",
      "agent_id": "agt_01K7Q9F3K7M2N5P9R4T6V8W0XZ",
      "status": "completed",
      "ended_reason": "time-limit-close",
      "started_at": "2026-09-27T10:00:04Z",
      "ended_at": "2026-09-27T10:09:34Z",
      "duration_secs": 570,
      "cost": { "amount_inr": 28.5, "per_min_inr": 3, "billing_block_secs": 10 },
      "transcript_status": "ready",
      "metadata": { "session_id": "sess_8f2c41", "user_id": "usr_1042" }
    },
    "processing": {
      "transcript": "ready",
      "analysis": "not_enabled",
      "post_call_tools": "not_enabled",
      "version": 1
    },
    "transcript": {
      "status": "ready",
      "turns": [
        {
          "role": "assistant",
          "text": "Hi Asha, thanks for joining. Shall we start?",
          "start_ms": 380,
          "end_ms": 3120
        },
        { "role": "user", "text": "Yes, let's start.", "start_ms": 3900, "end_ms": 5010 }
      ]
    }
  }
}
```

| Field | Description |
| :- | :- |
| `data.call` | The [call object](https://docs.miraiminds.co/v2/calls.md#the-call-object) in its final state, with your `metadata` and the `analysis` result. |
| `data.transcript.status` | `ready`, `empty`, `failed` or `fetch_required`. See below. |
| `data.transcript.turns` | Present when `ready`: the final user and agent turns, in exactly the same shape as [`GET /v2/calls/{id}/transcript`](https://docs.miraiminds.co/v2/calls#get-the-transcript) (`role`, `text`, `start_ms`, `end_ms`). |
| `data.processing` | One status per part: `transcript`, `analysis` and `post_call_tools`, plus `version`. A part that is off for this call reports `not_enabled`. |

| `data.transcript.status` | Meaning |
| :- | :- |
| `ready` | The turns are inline. They are the same turns `GET /v2/calls/{id}/transcript` returns. |
| `empty` | Nobody spoke. There are no turns. |
| `failed` | The transcript could not be produced. |
| `fetch_required` | The transcript is larger than the 512 KB inline limit, so no turns are included. Fetch them with `GET /v2/calls/{id}/transcript`. The transcript is never truncated. |

`analysis` is `done`, `failed`, `skipped` or `not_enabled`. `post_call_tools` is
`done`, `partial` or `failed` when the agent has post-call tools. See
[Tools: call.processed](https://docs.miraiminds.co/v2/tools.md#receive-call-processed).

**Analysis and the follow-up message.** When the agent has
[analysis](https://docs.miraiminds.co/v2/analysis.md) enabled, `data.call.analysis` holds the summary,
`success` and your extracted `data`. If the agent also has
[`analysis.templates`](https://docs.miraiminds.co/v2/analysis#pick-a-follow-up-message), it holds the
template chosen for the follow-up message:

```json title="data.call.analysis on call.processed" theme={"system"}
{
  "status": "done",
  "state": "completed",
  "generation": 1,
  "agent_revision": 4,
  "completed_at": "2026-10-15T10:02:41Z",
  "summary": "The customer agreed to pay ₹1,499 online and asked for the link on WhatsApp.",
  "success": true,
  "data": { "payment_method": "online" },
  "template": {
    "status": "selected",
    "name": "payment_link_hi",
    "language": "hi",
    "variables": { "1": "Rahul", "2": "1499" },
    "missing": [],
    "reason": "The customer agreed to pay online and asked for the link on WhatsApp."
  }
}
```

`template.status` is `selected`, `none` or `failed`. A failed choice never
fails the analysis: `analysis.status` stays `done` and the summary still
arrives. Check `template.missing` before you send. See
[the result](https://docs.miraiminds.co/v2/analysis.md#the-result-analysis-template) for every field and
error code. Choosing the template happens before this event is sent, so it adds
the time of one model call, plus your template fetch when you use one.

**Node-based agents.** For a call run by a [node-based agent](https://docs.miraiminds.co/v2/node-agents.md),
`data.call.flow` holds the flow's outcome, in the ordinary `call.processed` and
in final results alike:

```json title="data.call.flow" theme={"system"}
{
  "final_node": "goodbye",
  "nodes_visited": ["Confirm the customer", "Offer the delivery slot", "Find a new day", "Close"],
  "variables": { "identity_confirmed": true, "slot_accepted": false, "preferred_day": "Saturday" },
  "status": "end_call",
  "tags": ["end_call"]
}
```

The fields are described in [flow outcome](https://docs.miraiminds.co/v2/calls.md#flow-outcome).
`nodes_visited` and `variables` are always present; `final_node`, `status` and
`tags` are omitted when unknown.

A node-based agent's call sends `call.processed` whenever the call has a
`webhook_url`, even without analysis, post-call tools or `final_results`.

The outcome is usually recorded within seconds of the call ending.
`call.processed` waits up to 2 minutes for it and is then sent without `flow`.
In that case, read [`GET /v2/calls/{id}`](https://docs.miraiminds.co/v2/calls#get-a-call) later.

**When it arrives.** It comes after the terminal event, once the transcript has
settled (within about 2 minutes of the call ending) and any analysis and
post-call tools have finished, which can take longer. Do not wait for it to
decide that a conversation is over.

**One event, stable ID.** With `final_results: true`, this is the call's
`call.processed`. It replaces the ordinary one, so you never get a second.
Retries keep its `id`, so dedupe on it as usual. An explicit
[post-call rerun](https://docs.miraiminds.co/v2/tools.md#rerun-post-call-tools) produces a new `version`.

Final results are delivered only to the call's `webhook_url`. Set one when you
set `final_results`.

### Which event to act on

| You want to | Use |
| :- | :- |
| Know the conversation ended | The terminal event: `call.completed`, `call.failed`, `call.aborted` (or `call.voicemail` on phone calls). It arrives promptly and is never delayed by processing. |
| Process the transcript now | `call.processed` from a call created with `final_results: true`, when `data.transcript.status` is `ready`. On `fetch_required`, fetch the transcript instead. |
| Send the follow-up message | `call.processed`, at `data.call.analysis.template`, when the agent has [analysis templates](https://docs.miraiminds.co/v2/analysis.md#pick-a-follow-up-message). |
| Watch your balance | `data.wallet.balance_inr` on the terminal event. |

For the whole browser-call flow, see
[Ending and results](https://docs.miraiminds.co/v2/web-calls.md#ending-and-results) on the Browser calls page.

***

## Signature verification

Every delivery carries a timestamped HMAC-SHA256 signature.

```http theme={"system"}
X-Mirai-Signature: t=1785057398,v1=771bca27e1647dfbe59ff5d8f32d9de69be246f6e604c05bddcbaefd8604ccb3
```

| Element | Meaning |
| :- | :- |
| `t` | Unix seconds when we signed the delivery. |
| `v1` | Lowercase hex `HMAC-SHA256(secret, "<t>.<raw_body>")`. |

The signed string is the timestamp, a literal `.`, then the **raw request body
bytes**. The secret is your API key's Call webhook secret, the `whsec_…` shown
once when your key is issued. If the `webhook_url` is also one of your
[destinations](https://docs.miraiminds.co/v2/webhook-subscriptions.md), the destination's secret signs it
instead. `X-Mirai-Signed-With` names the secret that signed each delivery:

```http theme={"system"}
X-Mirai-Signed-With: api_key
```

See [Which webhook secret do I use?](https://docs.miraiminds.co/v2/webhook-secrets.md)

Verification takes four steps:

1. Parse `t` and `v1` out of the header.
2. Reject the delivery if `|now − t| > 300` seconds. This is the
   [replay window](#replay-protection).
3. Recompute the HMAC over `t + "." + raw_body`.
4. Compare with `v1` in **constant time**.

> [tab] Python
>
> ```python theme={"system"}
> # verify.py — framework-independent core
> import hashlib
> import hmac
> import time
>
> TOLERANCE_SECS = 300
>
>
> def verify_signature(raw_body: bytes, signature_header: str, secret: str) -> bool:
>     """Return True iff the delivery is authentic and inside the replay window.
>
>     raw_body must be the exact bytes we sent. A parsed-and-re-serialised dict
>     will not match: key order and whitespace both change the digest.
>     """
>     if not signature_header:
>         return False
>
>     parts = dict(
>         p.split("=", 1) for p in signature_header.split(",") if "=" in p
>     )
>     t, v1 = parts.get("t"), parts.get("v1")
>     if not t or not v1:
>         return False
>
>     try:
>         sent_at = int(t)
>     except ValueError:
>         return False
>     if abs(time.time() - sent_at) > TOLERANCE_SECS:
>         return False
>
>     expected = hmac.new(
>         secret.encode("utf-8"),
>         t.encode("utf-8") + b"." + raw_body,
>         hashlib.sha256,
>     ).hexdigest()
>     return hmac.compare_digest(expected, v1)
> ```
>
> Flask:
>
> ```python theme={"system"}
> import os
> from flask import Flask, request
> from verify import verify_signature
>
> app = Flask(__name__)
> WEBHOOK_SECRET = os.environ["MIRAI_WEBHOOK_SECRET"]
>
>
> @app.post("/mirai/webhook")
> def mirai_webhook():
>     if not verify_signature(
>         request.get_data(),  # raw bytes, before any JSON parsing
>         request.headers.get("X-Mirai-Signature", ""),
>         WEBHOOK_SECRET,
>     ):
>         return {"error": "invalid signature"}, 401
>
>     event = request.get_json()
>     if already_processed(event["id"]):
>         return "", 200  # duplicate delivery, already handled
>
>     enqueue(event)          # do the slow work off the request
>     mark_processed(event["id"])
>     return "", 200          # any 2xx stops our retries
> ```
>
> FastAPI:
>
> ```python theme={"system"}
> import json
> import os
> from fastapi import FastAPI, Request, Response
>
> app = FastAPI()
> WEBHOOK_SECRET = os.environ["MIRAI_WEBHOOK_SECRET"]
>
>
> @app.post("/mirai/webhook")
> async def mirai_webhook(request: Request):
>     raw = await request.body()
>     if not verify_signature(
>         raw, request.headers.get("x-mirai-signature", ""), WEBHOOK_SECRET
>     ):
>         return Response(status_code=401)
>
>     event = json.loads(raw)
>     enqueue(event)
>     return Response(status_code=200)
> ```

> [tab] Node.js
>
> ```javascript theme={"system"}
> // verify.js — framework-independent core
> import crypto from "node:crypto";
>
> const TOLERANCE_SECS = 300;
>
> /**
>  * @param {Buffer} rawBody exact bytes as received, before JSON.parse
>  * @param {string} signatureHeader value of X-Mirai-Signature
>  * @param {string} secret your whsec_… webhook secret
>  */
> export function verifySignature(rawBody, signatureHeader, secret) {
>   if (!signatureHeader) return false;
>
>   const parts = Object.fromEntries(
>     signatureHeader.split(",").map((p) => {
>       const i = p.indexOf("=");
>       return i === -1 ? ["", ""] : [p.slice(0, i).trim(), p.slice(i + 1).trim()];
>     })
>   );
>   const { t, v1 } = parts;
>   if (!t || !v1) return false;
>
>   const sentAt = Number(t);
>   if (!Number.isFinite(sentAt)) return false;
>   if (Math.abs(Date.now() / 1000 - sentAt) > TOLERANCE_SECS) return false;
>
>   const expected = crypto
>     .createHmac("sha256", secret)
>     .update(`${t}.`)
>     .update(rawBody)
>     .digest("hex");
>
>   const a = Buffer.from(expected, "utf8");
>   const b = Buffer.from(v1, "utf8");
>   return a.length === b.length && crypto.timingSafeEqual(a, b);
> }
> ```
>
> Express (note `express.raw`, not `express.json`):
>
> ```javascript theme={"system"}
> import express from "express";
> import { verifySignature } from "./verify.js";
>
> const app = express();
> const WEBHOOK_SECRET = process.env.MIRAI_WEBHOOK_SECRET;
>
> app.post(
>   "/mirai/webhook",
>   express.raw({ type: "application/json" }),
>   async (req, res) => {
>     if (!verifySignature(req.body, req.get("X-Mirai-Signature") ?? "", WEBHOOK_SECRET)) {
>       return res.status(401).json({ error: "invalid signature" });
>     }
>
>     const event = JSON.parse(req.body.toString("utf8"));
>     if (await alreadyProcessed(event.id)) return res.sendStatus(200);
>
>     await enqueue(event);       // do the slow work off the request
>     await markProcessed(event.id);
>     res.sendStatus(200);        // any 2xx stops our retries
>   }
> );
>
> app.listen(3000);
> ```
>
> Next.js App Router:
>
> ```javascript theme={"system"}
> // app/api/mirai/webhook/route.js
> import { verifySignature } from "@/lib/verify";
>
> export async function POST(request) {
>   const raw = Buffer.from(await request.arrayBuffer());
>   const ok = verifySignature(
>     raw,
>     request.headers.get("x-mirai-signature") ?? "",
>     process.env.MIRAI_WEBHOOK_SECRET
>   );
>   if (!ok) return new Response(null, { status: 401 });
>
>   const event = JSON.parse(raw.toString("utf8"));
>   await enqueue(event);
>   return new Response(null, { status: 200 });
> }
> ```

### Test vector

Check your implementation against this test vector before you try a real call.

```text title="secret" theme={"system"}
whsec_7d4f1a09c2e58b36a1f0d7c93b2e64a8
```

```text title="raw body (177 bytes, exactly as shown — no trailing newline)" theme={"system"}
{"id":"evt_01JZQ9C5N9P4R7S3T6V8W2X4YB","type":"call.completed","created_at":"2026-07-26T09:16:38Z","data":{"call":{"id":"call_01JZQ9B4M8N3P6R2S5T7V9W1YA","status":"completed"}}}
```

```text title="header" theme={"system"}
X-Mirai-Signature: t=1785057398,v1=771bca27e1647dfbe59ff5d8f32d9de69be246f6e604c05bddcbaefd8604ccb3
```

Your HMAC must equal that `v1`. (The timestamp is in the past, so skip the
window check while testing this vector.)

```bash theme={"system"}
printf '%s' '1785057398.{"id":"evt_01JZQ9C5N9P4R7S3T6V8W2X4YB","type":"call.completed","created_at":"2026-07-26T09:16:38Z","data":{"call":{"id":"call_01JZQ9B4M8N3P6R2S5T7V9W1YA","status":"completed"}}}' \
  | openssl dgst -sha256 -hmac 'whsec_7d4f1a09c2e58b36a1f0d7c93b2e64a8' -hex
```

### Raw body

The most common integration bug is signing a re-serialised body.

```js theme={"system"}
// ✗ wrong — key order, spacing and unicode escaping all differ from what we sent
hmac(JSON.stringify(req.body));

// ✓ right — the bytes we sent
hmac(rawBodyBuffer);
```

Capture the raw bytes **before** any body parser touches them. In Express that
means `express.raw({ type: "application/json" })` on this route (mount it before
any global `express.json()`); in Django, `request.body`; in Rails,
`request.raw_post`; behind API Gateway, make sure the payload is not
base64-transformed on the way in.

### Replay protection

We do not reject deliveries on your behalf. The timestamp is there so that you
can: drop any delivery where `|now − t| > 300` seconds. Without that check,
anyone who captures one valid delivery can replay it forever.

If legitimate deliveries fail the window check, your server clock is wrong.
Keep it synced with NTP.

### Rotating the secret

Ask ops to rotate it. During rotation, the old and the new secret are both
valid for a short overlap, so verify against a list:

```python theme={"system"}
def verify_any(raw_body, header, secrets):
    return any(verify_signature(raw_body, header, s) for s in secrets)
```

***

## Retries

A delivery succeeds on any `2xx`. We retry anything else, including a `4xx`, a
`5xx`, a timeout, a TLS error or a DNS failure. You get **six attempts with
exponential backoff over roughly 36 minutes**. The first fires immediately, and
the gaps widen up to a half-hour cap.

Design for the whole window. The individual delays are an implementation detail
that we tune, so do not build around them. What we guarantee is that a brief
outage on your side will not lose the event, and that an endpoint that is down
for the whole 36 minutes will lose it.

After the sixth attempt, the event goes to a dead-letter queue (DLQ), and we can
replay it from there. A replayed event is byte-identical to the original,
including its `id`. It carries a fresh `t` and `v1`, so it passes your window
check.

Some consequences to plan for:

* **Order is not guaranteed.** A retried `call.started` can arrive after
  `call.completed`. Order your own state machine by `data.call.status`, not by
  arrival.
* **Slow endpoints get retried.** If your handler takes longer than our client
  timeout, we treat it as a failure and send again. Acknowledge first and do the
  work afterwards.
* **A `401` from your signature check is a retryable failure to us.** We do
  this on purpose, so that a transient secret-loading bug on your side does not
  lose the event.
  Every attempt is listed in the console under **Webhooks**, in the
  **Call webhook\_url** panel. For a failed check, see
  [A webhook failed its signature check](https://docs.miraiminds.co/v2/webhook-secrets.md#a-webhook-failed-its-signature-check).

## Linking an event to your own records

An event describes the call and carries nothing from your own database. Join
the two on `call_id`. You have it **before** any event can arrive, because
`POST /v2/calls` returns it synchronously in the `202`:

```python theme={"system"}
call = mirai.calls.create(agent_id=agent.id, to=customer.phone)
Order.objects.filter(pk=order.id).update(mirai_call_id=call.id)   # store it here
```

Do that write before you return from the request that placed the call. A
webhook can land while the placing request is still in flight, and a handler
that cannot find the call yet has to either drop the event or retry blindly.

`variables` are substituted into the prompt and are **not** echoed back on
the event. [`metadata`](https://docs.miraiminds.co/v2/calls#metadata) is echoed back. Set small
identifiers such as your `session_id` when you create the call, and every event
for the call carries them in `data.call.metadata`. This also handles a webhook
that lands before your own `call_id` write has finished. Store anything larger
in your own row, keyed by `call_id`.

## Idempotency

Assume at-least-once delivery. Dedupe on `id`:

> [tab] Python
>
> ```python theme={"system"}
> # Redis SETNX with a TTL longer than the full retry schedule (~36 min).
> def already_processed(event_id: str) -> bool:
>     return not redis.set(f"mirai:evt:{event_id}", "1", nx=True, ex=86_400)
> ```

> [tab] Node.js
>
> ```javascript theme={"system"}
> // Redis SETNX with a TTL longer than the full retry schedule (~36 min).
> async function alreadyProcessed(eventId) {
>   const set = await redis.set(`mirai:evt:${eventId}`, "1", "NX", "EX", 86_400);
>   return set === null;
> }
> ```

You can also make the handler naturally idempotent. A statement such as
`UPDATE orders SET call_status = ?
WHERE id = ?` needs no dedupe table at all.

## Local development

Webhooks need a public URL. To receive them on your laptop, open a tunnel:

```bash theme={"system"}
ngrok http 3000
# → https://a1b2c3d4.ngrok-free.app
```

Then pass `"webhook_url": "https://a1b2c3d4.ngrok-free.app/mirai/webhook"` when
creating a call. To iterate without spending wallet balance, replay a captured
delivery against your handler with `curl`:

```bash theme={"system"}
curl -X POST http://localhost:3000/mirai/webhook \
  -H "Content-Type: application/json" \
  -H "X-Mirai-Signature: t=$(date +%s),v1=$(printf '%s' "$(date +%s).$(cat event.json)" \
      | openssl dgst -sha256 -hmac "$MIRAI_WEBHOOK_SECRET" -hex | cut -d' ' -f2)" \
  --data-binary @event.json
```

## Checklist

* [ ] Endpoint is public HTTPS and returns 2xx in well under a second.
* [ ] Signature verified against the **raw** body, in constant time.
* [ ] Timestamp window enforced at 300 seconds.
* [ ] Events deduped on `id`.
* [ ] Unknown `type` values ignored, not crashed on.
* [ ] Handler does no slow work inline. It enqueues the work and returns.


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