> ## 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/webhooks/endpoints)\*\*会接收
  `telephony.complete`（电话通话）或 `web.complete`（网页通话和
  构建器麦克风测试通话），其中包含下文记录的稳定负载、
  每次投递对应的 `event_id`、30 秒超时，以及
  [最长 24 小时的重试](/zh/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          | 计费分钟数，四舍五入至最接近的 0.25 分钟（每 15 秒递增，最低 0.25）。直接转入语音信箱的通话则按固定 1¢ 计费。 |
| `billing_total_cents`      | integer         | 美元美分                                                             |
| `transcripts`              | array           | 每轮转录内容——请参阅下一节                                                   |

### 结束原因

| 值                  | 含义                                    |
| ------------------ | ------------------------------------- |
| `user_hangup`      | 对方先挂断电话                               |
| `ai_hangup`        | AI 主动结束通话                             |
| `ai_transfer`      | AI 转接了通话；已设置 `transfer_number`        |
| `ai_warm_transfer` | AI 完成了暖转接（有人接听的转接）                    |
| `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`（轮次架构与上文相同）。
* 字段集合为原始通话结束报告，可能包含上表之外的其他内部字段——将未知字段视为信息性字段。
* Web 通话（`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/webhooks/call-incoming">
    在通话开始时运行的阻塞式对应事件。
  </Card>

  <Card title="事件目录" icon="list" href="/zh/webhooks/events">
    您可以订阅的其他事件类型。
  </Card>

  <Card title="通话记录 API" icon="phone" href="/api-reference/calls">
    可通过 REST 访问相同数据，用于回填或重放。
  </Card>
</CardGroup>
