> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/api/en/preparation/message-webhook.md). Agents can also search and read this documentation through its [MCP server](https://docs.maiagent.ai/~gitbook/mcp).

# Message Webhook

Every time a customer message arrives or a reply is sent on a messaging platform, MaiAgent can push that message to a URL you specify. This page explains the difference between Incoming and Outgoing,

After you configure a message webhook on an inbox, MaiAgent pushes every message to your system proactively, so you don't need to poll. Common uses: show a "new message" indicator in your own system, sync customer messages to a CRM, and log AI replies to a data warehouse.

An inbox can have multiple message webhooks. Each one has its own type, URL, and format, and they push independently of each other.

{% hint style="info" %}
If you only want to be notified on **handoff to a human agent**, use [Handoff Webhook Events](https://docs.maiagent.ai/api/en/preparation/handoff-webhook.md): it pushes only when the handoff flow changes state, not for every message. The two are independent settings. You can enable both and handle them with the same receiver.
{% endhint %}

{% hint style="info" %}
For a conversation newly created through the conversation reply (completions) API, replies are pushed to the `Outgoing` webhook configured on that Agent's API inbox. This applies to `200`, `202`, and streaming responses. When you continue a conversation from another platform, replies are pushed according to that platform's settings. For how to match a pushed reply to your own question, how to deduplicate when you also poll after a `202`, which cases are not pushed, and a complete example, see [Receive replies with a webhook](https://docs.maiagent.ai/tech/api-integration/dui-hua-yu-xun-xi-hui-fu-chuan-liu-tong-bu#webhook-reply) in the technical handbook.
{% endhint %}

## Types: Incoming and Outgoing <a href="#directions" id="directions"></a>

| Type       | When it is pushed                                                                                               | `type` in the payload |
| ---------- | --------------------------------------------------------------------------------------------------------------- | --------------------- |
| `Incoming` | Each time the inbox receives a message from a customer (contact)                                                | `incoming`            |
| `Outgoing` | Each time a reply is sent to the customer's inbox, including AI automatic replies and replies from human agents | `outgoing`            |

* In the admin console, the description text for the `Incoming` option reads "Receive external requests", but its actual behavior is to **push every customer message to the URL you configured**.
* The `Receive` option in the same menu works the opposite way: an external platform sends messages into MaiAgent, which is outside the scope of this page. Messages that come in through `Receive` do not trigger `Incoming`/`Outgoing` pushes on the same inbox, which prevents messages from looping back and forth between the two systems.
* If you need both customer messages and replies, configure one `Incoming` and one `Outgoing` webhook. They can point to the same URL, and you can tell them apart by the payload's `type`.

## Setup <a href="#setup" id="setup"></a>

### Configure in the admin console <a href="#setup-admin" id="setup-admin"></a>

1. In the admin console, go to <mark style="color:blue;">Customer Service</mark> → <mark style="color:blue;">Inboxes</mark> → select an inbox → <mark style="color:blue;">Webhook Settings</mark> → <mark style="color:blue;">Add Webhook</mark>.
2. Fill in the <mark style="color:blue;">Name</mark>, set the <mark style="color:blue;">Type</mark> to <mark style="color:blue;">Incoming</mark> or <mark style="color:blue;">Outgoing</mark>, enter the <mark style="color:blue;">Webhook URL</mark>, and choose the <mark style="color:blue;">HTTP Method</mark> (default `POST`).
3. (Recommended) Add an authentication header under <mark style="color:blue;">Headers</mark>, for example `Authorization: Bearer <a random string you generate>`. The receiver uses it to confirm the request comes from MaiAgent (see [Verify the push source](#verify-source)).
4. Set the <mark style="color:blue;">Payload format</mark> to <mark style="color:blue;">MaiAgent Standard</mark> (see [Payload](#payload)); choose <mark style="color:blue;">Custom template</mark> if you need custom fields.
5. Make sure <mark style="color:blue;">Enabled</mark> is turned on, then save. Turning off Enabled pauses pushing; the settings are kept.

The settings page for WhatsApp inboxes currently has no <mark style="color:blue;">Webhook Settings</mark> tab. Use the API configuration below instead.

### Configure via the API <a href="#setup-api" id="setup-api"></a>

Message webhooks belong to an inbox:

| Action       | Method and path                                                                             |
| ------------ | ------------------------------------------------------------------------------------------- |
| List         | `GET /api/v1/inboxes/{inbox_id}/webhooks/`                                                  |
| Create       | `POST /api/v1/inboxes/{inbox_id}/webhooks/`                                                 |
| Retrieve one | `GET /api/v1/inboxes/{inbox_id}/webhooks/{id}/`                                             |
| Update       | `PATCH /api/v1/inboxes/{inbox_id}/webhooks/{id}/` (send only the fields you want to change) |
| Delete       | `DELETE /api/v1/inboxes/{inbox_id}/webhooks/{id}/`                                          |

The API key owner must be able to manage the inbox. For details, see [API Authentication → API key permission scope](https://docs.maiagent.ai/api/en/preparation/authentication.md#api-key-permissions).

| Field            | Required               | Description                                                                                                                                                                                               |
| ---------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`           | Yes                    | Name, for easy identification                                                                                                                                                                             |
| `direction`      | Yes                    | `incoming` or `outgoing`                                                                                                                                                                                  |
| `url`            | Yes                    | The URL that receives pushes. It must be reachable from the internet (`https://` recommended); URLs that point to internal network ranges or local addresses are refused                                  |
| `method`         | No                     | `POST` (default), `PUT`, or `PATCH`                                                                                                                                                                       |
| `headers`        | No                     | Custom headers sent with every push, as a JSON object, for example `{"Authorization": "Bearer ..."}`                                                                                                      |
| `templatePreset` | No                     | `maiagent_standard` (default), `custom`, or `genesys_cloud` for Genesys Cloud integration                                                                                                                 |
| `customTemplate` | Required when `custom` | A Jinja2 template whose rendered result must be JSON. It is test-rendered once when saved, and a format error returns 400                                                                                 |
| `secretToken`    | No                     | Signing secret. When set, every push carries an HMAC-SHA256 signature and a timestamp header (see [Verify the push source](#verify-source)). Write-only; it is not returned when you retrieve the webhook |
| `isEnabled`      | No                     | Whether the webhook is enabled. Defaults to `true`                                                                                                                                                        |

```bash
curl -X POST "https://api.maiagent.ai/api/v1/inboxes/YOUR_INBOX_ID/webhooks/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "New message notification",
    "direction": "incoming",
    "url": "https://example.com/webhooks/maiagent-message",
    "secretToken": "YOUR_RANDOM_SECRET"
  }'
```

On success it returns `201` with the new configuration (without `secretToken`). To receive replies as well, create another one with `"direction": "outgoing"`.

## Payload <a href="#payload" id="payload"></a>

Each message is pushed as one HTTP request:

* Headers: `Content-Type: application/json`, your custom headers, `X-MaiAgent-Delivery-Attempt` (which attempt this is; `1` for the first), and, when `secretToken` is set, `X-MaiAgent-Timestamp` and `X-MaiAgent-Signature-256`. If a custom header has the same name as one of these three (case-insensitive), it is removed before sending.
* Body: JSON generated according to the <mark style="color:blue;">Payload format</mark>.

### MaiAgent Standard format <a href="#standard-format" id="standard-format"></a>

Fields are always snake\_case (unlike the camelCase used in API responses). Below is the payload of an `Outgoing` (AI reply) push:

```json
{
  "id": "a0c49ae2-013c-4310-b00f-b4554bc9cd83",
  "type": "outgoing",
  "content": "Hello, we have received your order question. Please provide your order number.",
  "created_at": "2026-10-03T04:59:01.512340+00:00",
  "conversation": {
    "id": "e6b27044-4990-4129-ad8e-ac7649984e7d",
    "title": "Order address change",
    "type": "individual",
    "status": "open",
    "progress_status": "ai_processing",
    "auto_reply_enabled": true,
    "assignee": null
  },
  "inbox": { "id": "6571672b-2fae-4200-a4d0-cf12e86216c3", "name": "Website support", "channel_type": "web" },
  "contact": { "id": "350691e0-66a5-48ea-855c-d8bb90a7e24a", "name": "Wang Xiaoming", "email": null, "phone_number": null },
  "sender": { "id": "8a214fc3-75ad-43ba-93f6-567e9df97b76", "name": "Support Assistant", "type": "chatbot" },
  "attachments": [],
  "metadata": {}
}
```

| Field          | Description                                                                                                                                                                                       |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`           | Message id. Use it for deduplication, and to look up the message through the [Messages API](https://docs.maiagent.ai/api/en/api-reference/dui-hua-he-xun-xi.md)                                   |
| `type`         | `incoming` (customer message) or `outgoing` (reply). Use this field to determine direction                                                                                                        |
| `content`      | Message text                                                                                                                                                                                      |
| `created_at`   | Message creation time (ISO 8601, UTC)                                                                                                                                                             |
| `conversation` | The conversation it belongs to. A `progress_status` of `human_serving` means a human agent is currently handling it; `assignee` is the assigned agent `{ "id", "name" }`, or `null` if unassigned |
| `inbox`        | The inbox `{ "id", "name", "channel_type" }`; `channel_type` is for example `web`, `line`, or `messenger`                                                                                         |
| `contact`      | The customer (contact). `email` and `phone_number` are `null` when there is no data                                                                                                               |
| `sender`       | The sender. `type` is `contact` (customer), `chatbot` (Agent), or `user` (organization member, such as a human agent; messages sent on a customer's behalf with an API key are also `user`)       |
| `attachments`  | An array of attachments, each with `id`, `type` (`image`/`video`/`audio`/`sticker`/`other`), `filename`, and `source_url`                                                                         |
| `metadata`     | Additional information about the message; the content varies by inbox                                                                                                                             |

### Custom template <a href="#custom-template" id="custom-template"></a>

A <mark style="color:blue;">Custom template</mark> (`templatePreset: "custom"` in the API) uses Jinja2 syntax to build the JSON you want. Available variables: `message` (`id`, `type`, `content`, `created_at`, `metadata`), `conversation`, `inbox`, `contact`, `sender`, `sender_type` (`contact`/`chatbot`/`user`), `attachments`, and `now`. Output strings with the `tojson` filter so that quotes or line breaks don't break the JSON:

```
{
  "text": {{ message.content | tojson }},
  "direction": "{{ message.type }}",
  "conversation_id": "{{ conversation.id }}",
  "customer": {{ (contact.name if contact else none) | tojson }}
}
```

If the template fails to render at push time, that message is not sent.

## Verify the push source <a href="#verify-source" id="verify-source"></a>

After you set `secretToken` (the API field, or <mark style="color:blue;">Secret Token</mark> in the admin webhook form; the admin console does not show this field when the Payload format is Genesys Cloud), every push carries the following headers:

| Header                     | Content                                                                                              |
| -------------------------- | ---------------------------------------------------------------------------------------------------- |
| `X-MaiAgent-Timestamp`     | The Unix time (in seconds) when the request was sent                                                 |
| `X-MaiAgent-Signature-256` | `sha256=` followed by the hexadecimal value of `HMAC-SHA256(secretToken, "{timestamp}." + raw body)` |

Verification steps for the receiver:

1. Compute the signature over the **raw body bytes** you received. Don't parse it as JSON and re-serialize it first (the bytes would differ and the signature wouldn't match).
2. Compare it with `X-MaiAgent-Signature-256` using a constant-time comparison (for example, Python's `hmac.compare_digest`).
3. Reject the request if `X-MaiAgent-Timestamp` differs from the receiver's current time by more than an allowed tolerance (for example, 5 minutes), to prevent replay. Every attempt (including retries) recomputes the timestamp and signature at the time of sending.

For the full description, see [Verify the signature and timestamp](https://docs.maiagent.ai/tech/serve/webhook#webhook-signature) in the technical handbook.

* If you don't use signatures, you can also define your own authentication header in `headers` (for example, `Authorization: Bearer <random string>`). The values in `headers` are returned as-is when the webhook settings are retrieved, and any organization member who can view the inbox's settings can see them; `secretToken` is write-only and is never returned.
* When `secretToken` is set, the legacy `X-Webhook-Secret` header (whose value is the plain-text `secretToken`) is still sent for compatibility with existing receivers. New integrations should verify the signature instead.
* Use a sufficiently long random value as the secret, and receive pushes over HTTPS.

## Responses and retries <a href="#response-and-retry" id="response-and-retry"></a>

* Pushes are sent in the background after the message is written, and usually arrive within a few seconds. Different messages are sent independently, so **the arrival order is not guaranteed**. Sort by `created_at` and deduplicate by `id`.
* Your receiver must respond with 2xx within **30 seconds**. A timeout, a connection failure, or a non-2xx response counts as a failure.
* **Transient failures are retried automatically**: timeouts, connection failures, `5xx`, and `429` are retried after about 1, 5, and 15 minutes, up to 3 retries (4 attempts in total including the first). Other `4xx` responses, destinations blocked by security protection, and custom template rendering failures are not retried. A retried body is identical to the first one, and `X-MaiAgent-Delivery-Attempt` is `2`, `3`, `4` in turn. The intervals are fixed and the response's `Retry-After` is not read. If the webhook has been disabled or deleted, or the message has been deleted, before a retry, no retry is sent. For details, see [Automatic retries](https://docs.maiagent.ai/tech/serve/webhook#retry) in the technical handbook.
* Because of retries, delivery is "at least once": if the receiver actually processed a message but the response timed out or returned `5xx`, you will receive the same message again, so deduplicate by message `id`. We recommend persisting the content before returning 2xx and moving time-consuming work to the background. Return `4xx` only when you are certain you can never process it; if you temporarily can't process it (for example, a downstream service is down), return `5xx` or `429`.
* If all 3 retries fail, no further attempts are made, and message webhooks **do not guarantee delivery**. The polling approach in [Detect new messages](https://docs.maiagent.ai/api/en/preparation/detect-new-messages.md#polling) can make up for missed **customer messages** (Incoming) with low-frequency checks. However, AI or agent replies (Outgoing) are often generated after the customer message, so the polling example may not read them again and can't be relied on to recover replies whose push failed. To find the messages whose push failed, check the delivery records below: a `statusCode` that is not 2xx or is empty (timeout, connection failure) marks a failed push, and `requestBody` is the content that was pushed (in MaiAgent Standard format it contains the message `id` and `conversation.id`). Then read the first page of that conversation's message list to fill the gap.
* Every attempt (including retries) leaves its own delivery record with the URL, content, and response status code. You can query them with `GET /api/v1/chatbots/{chatbot_id}/webhook-records/` (requires edit permission on that Agent; `chatbot_id` is the Agent bound to the inbox). Note that this API's response is likewise converted to camelCase, while the content actually pushed is snake\_case.
* A failed push does not affect sending or receiving the message itself or the AI reply.

## Minimal receiver example <a href="#receiver-example" id="receiver-example"></a>

The following is a Python (Flask) receiver you can start right away. It verifies the signature and timestamp, deduplicates by message `id` (the same message arrives again on a retry), routes by `type`, and returns 2xx before processing. Replace `MESSAGE_WEBHOOK_SECRET` with the `secretToken` you configured; if you use a custom header for authentication instead, read that header.

{% code title="receiver.py" %}

```python
import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["MESSAGE_WEBHOOK_SECRET"]
TOLERANCE_SECONDS = 300
processed_ids: set[str] = set()  # In production, use a database or Redis and set a retention period


def is_valid_signature(timestamp: str, signature: str, body: bytes) -> bool:
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    expected = "sha256=" + hmac.new(SECRET.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)


@app.post("/webhooks/maiagent-message")
def message_webhook():
    if not is_valid_signature(
        request.headers.get("X-MaiAgent-Timestamp", ""),
        request.headers.get("X-MaiAgent-Signature-256", ""),
        request.get_data(),
    ):
        abort(401)

    message = request.get_json(force=True)
    if message["id"] in processed_ids:
        return "", 204
    processed_ids.add(message["id"])

    conversation_id = message["conversation"]["id"]
    if message["type"] == "incoming":
        notify_new_message(conversation_id, message["content"])  # For example, show "new message"
    elif message["type"] == "outgoing":
        archive_reply(conversation_id, message["content"])

    return "", 204  # Return 2xx within 30 seconds; a timeout or 5xx triggers a retry, so move slow work to the background


def notify_new_message(conversation_id, content):
    ...


def archive_reply(conversation_id, content):
    ...
```

{% endcode %}

```bash
MESSAGE_WEBHOOK_SECRET=your-secret flask --app receiver run --port 8080
```

To test locally, use the following commands to simulate a push with a correct signature:

```bash
BODY='{"id":"acadbd9c-0000-0000-0000-000000000001","type":"incoming","content":"I want to change my order address","created_at":"2026-10-03T04:58:55.262828+00:00","conversation":{"id":"e6b27044-0000-0000-0000-000000000002","title":"Order address change","type":"individual","status":"open","progress_status":"ai_processing","auto_reply_enabled":true,"assignee":null},"inbox":{"id":"6571672b-0000-0000-0000-000000000003","name":"Website support","channel_type":"web"},"contact":{"id":"350691e0-0000-0000-0000-000000000004","name":"Wang Xiaoming","email":null,"phone_number":null},"sender":{"id":"350691e0-0000-0000-0000-000000000004","name":"Wang Xiaoming","type":"contact"},"attachments":[],"metadata":{}}'
TS=$(date +%s)
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "your-secret" | sed 's/^.* //')
curl -X POST http://localhost:8080/webhooks/maiagent-message \
  -H "Content-Type: application/json" \
  -H "X-MaiAgent-Timestamp: $TS" \
  -H "X-MaiAgent-Signature-256: sha256=$SIG" \
  --data-raw "$BODY"
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/api/en/preparation/message-webhook.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
