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

# telephony.complete / web.complete

> 通話結束時傳送的非阻塞 Webhook，包含逐字稿、錄音 URL 與指標。

每通來電結束後都會觸發完成事件——包含來電電話、撥出電話、網頁通話或測試通話（建構工具麥克風工作階段）。此事件為**非阻塞**：請以任一 2xx 回應。

事件會透過兩種路徑傳送：

* \*\*[Webhook 端點](/zh-Hant/webhooks/endpoints)\*\*會收到
  `telephony.complete`（電話通話）或 `web.complete`（網頁通話和
  建構工具麥克風測試通話），包含下方記載的穩定酬載、
  每次傳送專屬的 `event_id`、30 秒逾時，以及
  [最多重試 24 小時](/zh-Hant/webhooks/overview)。
* **[舊版單一 URL webhook](/api-reference/organizations#legacy-single-url-webhook)**
  會收到一次同步嘗試（10 秒逾時，不會重試），其酬載略有不同——請參閱
  [舊版酬載差異](#legacy-payload-differences)。

## 請求酬載（端點傳送）

```json theme={null}
{
  "data": {
    "billable_minutes": 1.25,
    "billing_total_cents": 8,
    "call_id": 987654321,
    "direction": "inbound",
    "duration_seconds": 54,
    "end_reason": "user_hangup",
    "end_time": "2026-04-20T18:25:04.822Z",
    "from_number": "+14155550199",
    "product": "spark",
    "recording_url": "https://storage.example.com/…",
    "start_time": "2026-04-20T18:24:10.113Z",
    "status": "completed",
    "to_number": "+15551234567",
    "transcripts": [ /* see Transcript format */ ],
    "transfer_number": null,
    "voice": "john"
  },
  "event_id": "6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9d",
  "type": "telephony.complete"
}
```

| 欄位                         | 類型              | 說明                                                                                 |
| -------------------------- | --------------- | ---------------------------------------------------------------------------------- |
| `call_id`                  | integer         | 在此通話的所有事件中保持不變                                                                     |
| `direction`                | string          | `inbound`、`outbound`、`web`、`test`。歷史酬載可能包含舊版的 `mic` 或 `widget` 值                   |
| `from_number`, `to_number` | string          | E.164。網頁通話和測試通話的 `from_number` 固定為 `"web"`                                         |
| `origin_domain`            | string          | **僅限網頁／測試**——託管小工具的頁面來源（麥克風工作階段為空）                                                 |
| `start_time`, `end_time`   | timestamp       | ISO 8601 UTC                                                                       |
| `duration_seconds`         | integer \| null | 根據開始／結束時間計算                                                                        |
| `status`                   | string          | `completed` 或 `failed`                                                             |
| `end_reason`               | string          | 請參閱下表                                                                              |
| `product`, `voice`         | string          | 通話當下生效的智慧體設定                                                                       |
| `transfer_number`          | string \| null  | 通話轉接時設定                                                                            |
| `recording_url`            | string \| null  | 會過期的簽署 URL；請儘速下載。沒有可用錄音檔案時為 `null`                                                 |
| `billable_minutes`         | number          | 計費分鐘數，四捨五入至最接近的四分之一分鐘（每 15 秒遞增，最低 0.25）。直接轉入語音信箱的通話仍會在此回報實際計量分鐘數，但費用會依方案費率上限計為一分鐘。 |
| `billing_total_cents`      | integer         | 美元美分                                                                               |
| `transcripts`              | array           | 每輪逐字稿項目；逐字稿無法使用時可能為空                                                               |

### 結束原因

| 值                  | 意義                                    |
| ------------------ | ------------------------------------- |
| `user_hangup`      | 對方先掛斷                                 |
| `ai_hangup`        | 人工智慧主動結束通話                            |
| `ai_transfer`      | 人工智慧轉接通話；已設定 `transfer_number`        |
| `ai_warm_transfer` | 人工智慧完成暖轉接（有人接聽的轉接）                    |
| `voicemail_hangup` | 偵測到語音信箱，並依據你的 `voicemail_action` 結束通話 |
| `max_duration`     | 通話達到最長時長限制                            |
| `superseded`       | 工作階段已由較新的工作階段取代                       |
| `unknown`          | 無法判定結束原因                              |

## 逐字稿格式

`transcripts` 中的每個項目都是一個對話回合。角色包括
`user`（來電者語音）、`model`（智慧體語音**以及**工具呼叫）、
`tool`（工具結果）和 `system`（通話事件，例如語言切換）。

```json theme={null}
[
  {
    "role": "user",
    "content_type": "text/plain",
    "content": "Hi, I'm calling about my appointment.",
    "start_ms": 1200,
    "end_ms":   4100,
    "audio_url": "https://storage.example.com/…"
  },
  {
    "role": "model",
    "content_type": "text/plain",
    "content": "Sure, what date works best?",
    "start_ms": 4200,
    "end_ms":   6100
  },
  {
    "role": "model",
    "content_type": "application/json",
    "content": {
      "tool_call": "search_appointments",
      "arguments": { "date": "2026-04-21" }
    }
  },
  {
    "role": "tool",
    "content_type": "application/json",
    "content": {
      "tool_name": "search_appointments",
      "response": { "available_slots": ["9:00 AM", "2:00 PM"] }
    }
  }
]
```

| 欄位                       | 類型               | 說明                                                                                                        |
| ------------------------ | ---------------- | --------------------------------------------------------------------------------------------------------- |
| `role`                   | string           | `user`、`model`、`tool` 或 `system`                                                                          |
| `content_type`           | string           | 語音使用 `text/plain`；工具呼叫、工具結果和系統事件使用 `application/json`                                                     |
| `content`                | string \| object | 語音文字，或上述顯示的結構化物件。工具呼叫：`{"tool_call": name, "arguments": {…}}`。工具結果：`{"tool_name": name, "response": {…}}` |
| `start_ms`、`end_ms`      | integer          | 自通話開始起算的位移時間，單位為毫秒。已知音訊時間時會提供                                                                             |
| `ttfa_ms`                | integer          | 已測量時，`model` 回合的首段音訊時間                                                                                    |
| `audio_url`、`audio_urls` | string / array   | 逐回合錄製音訊的限時簽章 URL（如有錄製）                                                                                    |

如需取得完整的結構化回合歷史紀錄（包含中斷標記、
確認提示和原始位置），請使用
[`GET /v1/calls/{call_id}/history`](/api-reference/calls#get-history)。

## 舊版酬載差異

舊版單一 URL webhook 信封為
`{"type": "telephony.complete" | "web.complete", "data": {…}}`，**不含 `event_id`**，
且其 `data` 與端點酬載不同：

* 回合陣列位於 **`history`**，而非 `transcripts`（回合結構與上述相同）。
* 欄位集合為原始通話結束報告，可能包含上表以外的額外內部欄位——請將未知欄位視為參考資訊。
* 網頁通話（`direction: "web"`）**不含** `from_number` / `to_number`，
  並會新增 `origin_domain`。
* Builder 麥克風測試通話會在舊版路徑上以 `telephony.complete` 回報（端點系統會將其對應為 `web.complete`）。
* \*\*轉接協調：\*\*當通話在轉接時結束，舊版 webhook 會同步呼叫，並可能回應
  `{"transfer_ready": false}`，表示交接目標尚未就緒。任何其他回應（或未設定舊版 webhook）都會讓轉接繼續進行。端點傳遞絕不會用於此流程。

***

## 範例處理常式

<CodeGroup>
  ```python Python (FastAPI) theme={null}
  import hashlib
  import hmac
  import json
  import os

  from fastapi import FastAPI, HTTPException, Request

  app = FastAPI()
  SECRET = os.environ["THUNDERPHONE_WEBHOOK_SECRET"]

  def verify(body: bytes, signature: str) -> bool:
      expected = hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()
      return hmac.compare_digest(expected, signature or "")

  @app.post("/thunderphone-webhook")
  async def webhook(request: Request):
      body = await request.body()
      if not verify(body, request.headers.get("X-ThunderPhone-Signature", "")):
          raise HTTPException(status_code=401)

      event = json.loads(body)
      if event["type"] in ("telephony.complete", "web.complete"):
          data = event["data"]
          # Endpoint deliveries use "transcripts"; the legacy webhook uses "history".
          turns = data.get("transcripts") or data.get("history") or []
          await persist_call_record(
              call_id=data["call_id"],
              turns=turns,
              recording_url=data.get("recording_url"),
          )
          if data["end_reason"] in ("ai_transfer", "ai_warm_transfer"):
              await notify_team(data.get("transfer_number"), data["call_id"])
      return {"ok": True}
  ```

  ```javascript Node.js (Express) theme={null}
  import crypto from "node:crypto";
  import express from "express";

  const app = express();
  const SECRET = process.env.THUNDERPHONE_WEBHOOK_SECRET;

  function verify(body, signature) {
    const expected = crypto.createHmac("sha256", SECRET).update(body).digest("hex");
    return signature &&
      crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
  }

  app.post(
    "/thunderphone-webhook",
    express.raw({ type: "application/json" }),
    async (req, res) => {
      if (!verify(req.body, req.header("X-ThunderPhone-Signature"))) {
        return res.sendStatus(401);
      }
      const event = JSON.parse(req.body.toString("utf8"));
      if (["telephony.complete", "web.complete"].includes(event.type)) {
        const data = event.data;
        // Endpoint deliveries use "transcripts"; the legacy webhook uses "history".
        const turns = data.transcripts ?? data.history ?? [];
        await persistCallRecord({ ...data, turns });
        if (["ai_transfer", "ai_warm_transfer"].includes(data.end_reason)) {
          await notifyTeam(data.transfer_number, data.call_id);
        }
      }
      res.json({ ok: true });
    },
  );
  ```
</CodeGroup>

***

## 常見使用案例

<CardGroup cols={2}>
  <Card title="CRM 整合" icon="database">
    將每通電話的逐字稿與錄音 URL，連同你的
    客戶紀錄一併儲存。
  </Card>

  <Card title="分析" icon="chart-line">
    將逐字稿串流至管線，以進行主題建模、擷取 CSAT 訊號，
    或監控轉接率。
  </Card>

  <Card title="品質審查" icon="clipboard-check">
    在 QA 工具中開啟通話供人工審查，或透過你自己的
    評估模型進行分析。
  </Card>

  <Card title="通知" icon="bell">
    發生轉接／失敗時通知真人團隊成員。
  </Card>
</CardGroup>

***

## 相關內容

<CardGroup cols={2}>
  <Card title="telephony.incoming / web.incoming" icon="phone" href="/zh-Hant/webhooks/call-incoming">
    在通話開始時執行的阻塞式對應事件。
  </Card>

  <Card title="事件目錄" icon="list" href="/zh-Hant/webhooks/events">
    你可以訂閱的其他事件類型。
  </Card>

  <Card title="通話紀錄 API" icon="phone" href="/api-reference/calls">
    可透過 REST 存取相同資料，用於回填／重播。
  </Card>
</CardGroup>
