> 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/preparation/handoff-webhook.md).

# 轉真人 Webhook 事件

對話轉真人的生命週期（AI 判定轉真人、指派給客服、轉回 AI、排隊逾時）以 Webhook 推送到你指定的系統端點，本篇說明事件種類與格式、簽章驗證與重試行為

對話進入轉真人流程的每個階段——AI 判定需要真人、指派給客服、轉回 AI、排隊逾時——MaiAgent 都會以 HTTPS POST 推送一筆事件到你設定的端點，讓派工、告警、CRM 或你自己的客服系統自動接手，不需輪詢。事件名稱描述轉真人的狀態轉移，是固定的公開契約；每個事件在對話事件紀錄 API（`GET /api/v1/conversations/{id}/events/`）都有對應的 `event_type`（見下表），用於對帳或改以輪詢取得同一份資訊。

## 啟用方式

由客戶的管理者或串接人員在後台自助完成，毋需工程協助：

1. 後台「客服對話」→「對話平台」→ 編輯要串接的對話平台 →「客服轉真人設定」→「通知」分頁
2. 開啟「Webhook 通知（系統串接）」開關，填入接收端網址（僅接受 `https://` 開頭）
3. （選填但建議）填入簽章密鑰，啟用來源驗證（見下方「簽章驗證」）

Webhook 與通知中心、Email 是三個獨立開關，互不影響；預設關閉、逐收件匣啟用。此通道與收件匣既有的「訊息 Webhook」（訊息收送）互不相干。

## 事件種類 <a href="#event-types" id="event-types"></a>

| event                    | 事件紀錄 API 的 `event_type` | 何時送出                                               | 備註                                                                                                                                                                                   |
| ------------------------ | ----------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `handoff.requested`      | `transfer_triggered`    | AI 判定需要真人：對話進入排隊、AI 停止自動回覆                         | 每次轉真人流程的第一筆事件；`assignee` 為 `null`。真人客服在你自己的系統時，這就是接手的訊號                                                                                                                              |
| `handoff.assigned`       | `human_assigned`        | 對話被指派給 MaiAgent 後台的客服成員（含手動指派、自行認領、轉接、自動指派）        | `assignee` 為被指派客服；轉接給另一位客服會再送一筆（事件 `id` 不同）                                                                                                                                          |
| `handoff.returned_to_ai` | `returned_to_ai`        | 客服在後台按「轉回 AI Agent」或透過 `return-to-ai` API 將對話交回 AI | `assignee` 為 `null`（對話已無負責客服）                                                                                                                                                        |
| `handoff.queue_timeout`  | `queue_timeout`         | 排隊超過收件匣設定的「等待超時時間」仍無人接手，MaiAgent 自動把對話轉回 AI        | `assignee` 為 `null`。真人客服在你自己的系統時，收到它代表 MaiAgent 已在你不知情下恢復 AI 回覆——請視為需要告警的異常；或在派工設定選「接手制」並勾選「不逾時」（API 為 `dispatchMode: "handover"`、`assignmentQueueTimeout: 0`；自動派工模式下送 0 會被改成 300 秒） |

四種事件的 payload 鍵集、簽章與重試行為完全相同，接收端**依 `event` 欄位分流**；未來可能新增事件種類，遇到不認識的 `event` 請回 2xx 並忽略，不要當成錯誤。

`handoff.returned_to_ai` 與 `handoff.queue_timeout` 都代表「AI 恢復自動回覆」，差別在前者是人（專員或你的系統）主動、後者是逾時自動。兩者都不等於「對話已結案」：客服直接把對話標為「已解決」、或客服因失去收件匣權限而使對話重新排隊時，不會送出事件。需要完整的結案訊號時，請以對話 API 查詢 `status`，或在訊息 Webhook 的 `conversation.progress_status` 觀察狀態變化。

## 事件格式

```
POST <你設定的網址>
Content-Type: application/json
```

```json
{
  "event": "handoff.assigned",
  "id": "9f0e1d2c-...",
  "occurred_at": "2026-09-09T02:30:00.123456+00:00",
  "conversation": {
    "id": "6c2b7c1e-...",
    "url": "https://admin.maiagent.ai/..."
  },
  "inbox": { "id": "0f9a3d42-..." },
  "organization": { "id": "b1d20c77-..." },
  "contact": { "id": "a4c1f6b3-..." },
  "assignee": { "id": "3e8f5a90-..." }
}
```

| 欄位               | 類型                 | 說明                                                                                       |
| ---------------- | ------------------ | ---------------------------------------------------------------------------------------- |
| event            | string             | 事件名稱（見上方「事件種類」）                                                                          |
| id               | string (uuid)      | 事件識別碼，與事件紀錄 API 回傳的 `id` 相同；重試送出的內容完全一樣，**以它去重**                                         |
| occurred\_at     | string (date-time) | 事件發生時間（ISO 8601）；推送不保證依序到達，**以它排序**                                                      |
| conversation.id  | string (uuid)      | 對話識別碼                                                                                    |
| conversation.url | string (uri)       | 後台對話頁連結                                                                                  |
| inbox.id         | string (uuid)      | 收件匣識別碼                                                                                   |
| organization.id  | string (uuid)      | 組織識別碼                                                                                    |
| contact          | object \| null     | 客戶（聯絡人）`{ "id" }`；對話無聯絡人時為 `null`                                                        |
| assignee         | object \| null     | **事件當下**被指派客服 `{ "id" }`——是事件的快照，不會因為推送延遲或之後的轉接而改變；只有 `handoff.assigned` 有值，其餘事件為 `null` |

欄位命名與巢狀結構和收件匣「訊息 Webhook」的 MaiAgent 標準格式一致（snake\_case、關聯物件以 `{ "id" }` 巢狀），同一支接收端可以同時處理兩組 Webhook。Payload 只含識別資訊、事件時間與後台連結，**不含對話文字內容與轉真人理由**；需要對話內容時，請以識別碼呼叫對話與訊息 API 查詢。

## 簽章驗證（建議啟用）

在後台設定簽章密鑰後，每次推送會帶下列標頭：

```
X-MaiAgent-Signature-256: sha256=<hex digest>
```

值為以密鑰對 **原始 request body bytes** 計算的 HMAC-SHA256 十六進位摘要。驗證時務必使用收到的原始 bytes，不要先解析再重新序列化（欄位順序與空白差異會使摘要不一致）。

```python
import hashlib
import hmac


def verify_signature(raw_body: bytes, header_value: str, secret: str) -> bool:
    expected = 'sha256=' + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header_value)
```

密鑰為 write-only：儲存後不回顯，後台僅顯示「已設定」；欄位留空儲存代表維持既有密鑰，更換直接輸入新值，移除請使用「清除密鑰」操作。未設定密鑰時，推送不帶簽章標頭。

## 接收端最小範例 <a href="#receiver-example" id="receiver-example"></a>

以下是一支可直接啟動的 Python（Flask）接收端：讀取原始 bytes 驗章、依 `event` 分流、先回 2xx 再做耗時處理。把 `HANDOFF_WEBHOOK_SECRET` 換成後台設定的簽章密鑰即可。

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

```python
import hashlib
import hmac
import os

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["HANDOFF_WEBHOOK_SECRET"]


def verify_signature(raw_body: bytes, header_value: str | None) -> bool:
    if not header_value:
        return False
    expected = "sha256=" + hmac.new(SECRET.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header_value)


@app.post("/webhooks/handoff")
def handoff_webhook():
    raw = request.get_data()  # 原始 bytes，不要用 request.json 再序列化
    if not verify_signature(raw, request.headers.get("X-MaiAgent-Signature-256")):
        abort(401)

    event = request.get_json(force=True)
    if already_processed(event["id"]):  # 重試會送完全相同的內容，以事件 id 去重
        return "", 204

    conversation_id = event["conversation"]["id"]
    if event["event"] == "handoff.requested":
        # AI 已停止回覆；真人客服在你的系統時，在這裡開單、派客服
        open_ticket(conversation_id, event["conversation"]["url"])
    elif event["event"] == "handoff.assigned":
        # 指派給 MaiAgent 後台的客服；轉接給另一位客服時會再收到一筆，assignee 會變
        assign_ticket(conversation_id, event["assignee"]["id"])
    elif event["event"] == "handoff.returned_to_ai":
        close_ticket(conversation_id)
    elif event["event"] == "handoff.queue_timeout":
        # MaiAgent 已自動恢復 AI 回覆；若你的客服仍在處理，這是需要告警的異常
        close_ticket(conversation_id, reason="queue_timeout")
    # 未知事件：回 2xx 忽略，不要當錯誤

    return "", 204  # 10 秒內回 2xx；耗時工作丟到背景


def already_processed(event_id):
    ...


def open_ticket(conversation_id, url):
    ...


def assign_ticket(conversation_id, assignee_id):
    ...


def close_ticket(conversation_id, reason=None):
    ...
```

{% endcode %}

```bash
HANDOFF_WEBHOOK_SECRET=你的密鑰 flask --app receiver run --port 8080
```

本機測試可用下列指令模擬一筆推送（簽章用同一把密鑰算）：

```bash
BODY='{"assignee":{"id":"3e8f5a90-0000-0000-0000-000000000004"},"contact":{"id":"a4c1f6b3-0000-0000-0000-000000000005"},"conversation":{"id":"6c2b7c1e-0000-0000-0000-000000000001","url":"https://admin.maiagent.ai/conversations/index?conversationId=6c2b7c1e-0000-0000-0000-000000000001"},"event":"handoff.assigned","id":"9f0e1d2c-0000-0000-0000-000000000006","inbox":{"id":"0f9a3d42-0000-0000-0000-000000000002"},"occurred_at":"2026-09-09T02:30:00.123456+00:00","organization":{"id":"b1d20c77-0000-0000-0000-000000000003"}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "你的密鑰" | awk '{print $NF}')
curl -X POST http://localhost:8080/webhooks/handoff \
  -H "Content-Type: application/json" \
  -H "X-MaiAgent-Signature-256: sha256=$SIG" \
  -d "$BODY"
```

## 回應與重試

* 接收端應在 10 秒內以 2xx 狀態碼回應，回應內容不拘。
* 逾時、連線失敗或非 2xx 回應時，系統會自動重試，最多 3 次、間隔 60 秒；重試送出的內容與原始推送完全相同（同一個 `id`），接收端請以事件 `id` 去重。事件各自以背景任務送出，`handoff.requested` 與緊接著的 `handoff.assigned` 可能不依序到達，請以 `occurred_at` 排序。
* Webhook 推送失敗不影響轉真人主流程，也不影響通知中心與 Email 通知。

## 轉真人後由外部系統接手對話 <a href="#external-takeover" id="external-takeover"></a>

若你的真人客服不在 MaiAgent 後台，而是在自己的客服系統回覆，可以把本頁的事件、對話平台的「訊息 Webhook」與訊息 API 組合起來，讓對話在轉真人期間雙向同步：收到 `handoff.requested` 後在你的系統開單，以訊息 Webhook 接收訪客訊息，以 `POST /api/v1/messages/outgoing/` 寫回客服回覆，處理完畢呼叫 `PATCH /api/v1/conversations/{id}/return-to-ai/` 交回 AI。完整流程、呼叫範例與注意事項見技術手冊[第三方客服系統串接（含轉真人）](https://docs.maiagent.ai/tech/serve/customer-service-system-integration#scenarios)：訪客的通道掛在你的系統時看情境 A，訪客在 MaiAgent 的對話平台、只有真人客服在你的系統時看情境 B。

### 串接流程 <a href="#takeover-flow" id="takeover-flow"></a>

見技術手冊[情境 B › 串接流程](https://docs.maiagent.ai/tech/serve/customer-service-system-integration#scenario-b-flow)。

### 呼叫範例 <a href="#takeover-examples" id="takeover-examples"></a>

見技術手冊[情境 B › 呼叫範例](https://docs.maiagent.ai/tech/serve/customer-service-system-integration#scenario-b-examples)。

### 注意事項 <a href="#takeover-notes" id="takeover-notes"></a>

見技術手冊[情境 B › 注意事項](https://docs.maiagent.ai/tech/serve/customer-service-system-integration#scenario-b-notes)。


---

# 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/preparation/handoff-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.
