> ## 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

> 통화가 종료될 때 트랜스크립트, 녹음 URL 및 측정항목과 함께 전달되는 논블로킹 웹훅입니다.

모든 통화가 종료된 후 완료 이벤트가 발생합니다. 수신 전화,
발신 전화, 웹 통화 또는 테스트 통화(빌더 마이크 세션)가 해당합니다. 이 이벤트는
**비차단 방식**입니다. 2xx로 응답합니다.

이 이벤트는 두 경로 모두로 전달됩니다.

* \*\*[Webhook 엔드포인트](/ko/webhooks/endpoints)\*\*는 안정적인 페이로드와 함께
  `telephony.complete`(전화 통화) 또는 `web.complete`(웹 통화 및
  빌더 마이크 테스트 통화)를 수신합니다. 페이로드는 아래에 문서화되어 있으며,
  전송별 `event_id`, 30초 제한 시간 및
  [최대 24시간 재시도](/ko/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)로 반올림됩니다. 음성사서함으로 바로 연결된 통화는 대신 1¢의 정액 요금이 청구됩니다. |
| `billing_total_cents`      | integer         | USD 센트                                                                                |
| `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`                    | 문자열       | `user`, `model`, `tool` 또는 `system`                                                                                        |
| `content_type`            | 문자열       | 음성에는 `text/plain`, 도구 호출·도구 결과·시스템 이벤트에는 `application/json`                                                                |
| `content`                 | 문자열 \| 객체 | 음성 텍스트 또는 위에 표시된 구조화된 객체입니다. 도구 호출: `{"tool_call": name, "arguments": {…}}`. 도구 결과: `{"tool_name": name, "response": {…}}` |
| `start_ms`, `end_ms`      | 정수        | 통화 시작 시점부터의 오프셋(ms)입니다. 오디오 타이밍을 알 수 있는 경우 제공됩니다                                                                           |
| `ttfa_ms`                 | 정수        | 측정된 경우 `model` 턴의 첫 오디오까지 걸린 시간입니다                                                                                         |
| `audio_url`, `audio_urls` | 문자열 / 배열  | 턴별로 녹음된 경우 해당 턴 오디오의 만료되는 서명 URL입니다                                                                                        |

중단 마커, 맞장구 프롬프트 및 원시 위치를 포함한 완전히 구조화된 턴 기록은
[`GET /v1/calls/{call_id}/history`](/api-reference/calls#get-history)를 사용하세요.

## 레거시 페이로드 차이점

레거시 단일 URL 웹훅 엔벨로프는
`{"type": "telephony.complete" | "web.complete", "data": {…}}`이며,
**`event_id`가 없고** `data`가 엔드포인트 페이로드와 다릅니다.

* 턴 배열은 `transcripts`가 아니라 **`history`** 아래에 있습니다(위와 동일한 턴 스키마).
* 필드 집합은 통화 종료 시의 원시 보고서이며, 위 표에 없는 추가 내부 필드를 포함할 수 있습니다. 알 수 없는 필드는 정보용으로 처리하세요.
* 웹 통화(`direction: "web"`)는 `from_number` / `to_number`를 **생략**하고 `origin_domain`을 추가합니다.
* Builder 마이크 테스트 통화는 레거시 경로에서 `telephony.complete`로 보고됩니다(엔드포인트 시스템은 이를 `web.complete`로 매핑합니다).
* **전송 조정:** 통화가 전송 중에 종료되면 레거시 웹훅은 동기식으로 호출되며, 인계 대상이 준비되지 않았음을 알리기 위해 `{"transfer_ready": false}`를 응답할 수 있습니다. 그 밖의 모든 응답(또는 레거시 웹훅이 없는 경우)은 전송이 진행되도록 합니다. 이 경우 엔드포인트 전송은 참조되지 않습니다.

***

## 예제 핸들러

<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="/ko/webhooks/call-incoming">
    통화 시작 시 실행되는 차단형 대응 이벤트입니다.
  </Card>

  <Card title="이벤트 카탈로그" icon="list" href="/ko/webhooks/events">
    구독할 수 있는 다른 이벤트 유형입니다.
  </Card>

  <Card title="통화 기록 API" icon="phone" href="/api-reference/calls">
    백필 또는 재생을 위해 REST를 통해 동일한 데이터에 액세스할 수 있습니다.
  </Card>
</CardGroup>
