---
title: Webhook 与 SSE
subtitle: 用 OpenAPI 3.1 的 webhooks 描述你发给用户的事件，用 text/event-stream 描述流式响应，ButterIX 会为它们生成专门的页面与示例。
description: 在 ButterIX 中记录 Webhook（OpenAPI 3.1 webhooks、HOOK 页面、WebhookPayloadSnippet、签名验证说明）与服务器发送事件 SSE（text/event-stream、x-fern-streaming、流式示例）。
---

## Webhook

OpenAPI 3.1 在顶层新增了 `webhooks`，用来描述**你的服务主动发给用户**的请求。ButterIX 为每个 webhook 生成一个页面：

- 侧栏和标题使用 `HOOK` 徽章，而不是 HTTP 方法；
- 页面的主体是**负载（Payload）**字段表，而不是请求参数；
- 右侧显示负载示例，没有「试一试」按钮；
- 默认归入「Webhooks」分组（可以用 `tags` 改到其他分组）。

```yaml title="openapi/payments.yml"
openapi: 3.1.0
webhooks:
  payment.succeeded:
    post:
      summary: 付款成功
      x-fern-sdk-method-name: payment-succeeded
      description: 付款状态变为 succeeded 时发送。请用 `Acme-Signature` 头验证来源。
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PaymentEvent"
            example:
              id: evt_1Q2w3E
              type: payment.succeeded
              created: 1763596800
              data:
                id: pay_9xK2
                amount: 1999
                currency: cny
      responses:
        "200":
          description: 返回 2xx 表示已接收；否则按指数退避重试
```

### 在指南中展示负载

```mdx
<WebhookPayloadSnippet webhook="payment.succeeded" />
```

`webhook` 可以是 webhook 名称、`operationId`，或 `WEBHOOK payment.succeeded` 形式的键；`example` 选择具名示例。

### 写好 Webhook 文档的建议

<AccordionGroup>
  <Accordion title="说明签名验证" icon="lucide:shield-check" defaultOpen>
    在 webhook 的 `description` 或单独的指南页里给出签名算法和各语言的验证代码。可以把验证代码放进 `<CodeGroup>`，读者的语言选择会与 API 示例同步。
  </Accordion>
  <Accordion title="说明重试与幂等" icon="lucide:repeat">
    写清楚什么样的响应算成功、重试间隔和次数，以及事件 id 可用于去重。
  </Accordion>
  <Accordion title="给出真实的示例" icon="lucide:file-json">
    `example` 中使用真实形态的数据，读者可以直接复制来测试自己的处理程序。
  </Accordion>
</AccordionGroup>

<Info>
  ButterIX 平台本身**接收**来自 GitHub 的 Webhook（用于自动部署），它在本站 API 参考中是一个普通端点：[接收 GitHub Webhook](/api-reference/git/github-webhook)，因为它是平台对外提供的接口，而不是平台发出的事件。
</Info>

## 服务器发送事件（SSE）

以下任一条件成立时，端点被视为**流式**：

- 响应的 `content` 中有 `text/event-stream`；
- 操作上有 `x-fern-streaming: true`。

流式端点的页面会注明「返回事件流」，响应示例按事件流格式显示。本站的 [Ask AI 对话](/api-reference/runtime/ask-ai)接口就是一个 SSE 端点：

<EndpointResponseSnippet endpoint="POST /_biti/ai/chat" />

对应的规范片段：

```yaml title="openapi/platform.yml"
/_biti/ai/chat:
  post:
    summary: Ask AI 对话（SSE）
    responses:
      "200":
        description: 事件流
        content:
          text/event-stream:
            schema:
              type: string
            example: |
              event: sources
              data: [{"n":1,"title":"多语言","url":"/guides/features/i18n"}]

              event: text
              data: {"t":"在 docs.yml 的 languages 中加入 en [1]，"}

              event: done
              data: {"model":"claude-opus-5-5"}
```

<Tip>
  在 `description` 中用表格列出每种事件的名称与数据结构，读者最需要的就是这张表。参见 [Ask AI 对话](/api-reference/runtime/ask-ai)接口的写法。
</Tip>

### 在浏览器中消费 SSE

`EventSource` 只支持 GET。对于 POST 的 SSE 接口，用 `fetch` 读取流：

```ts title="ask.ts"
const output = document.querySelector("#answer")!;
const res = await fetch("/_biti/ai/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ messages: [{ role: "user", content: "如何添加英文版？" }], locale: "zh" }),
});

const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;
  const events = buffer.split("\n\n");
  buffer = events.pop()!;
  for (const raw of events) {
    const event = /^event: (.+)$/m.exec(raw)?.[1];
    const data = JSON.parse(/^data: (.+)$/m.exec(raw)?.[1] ?? "null");
    if (event === "text") output.textContent += data.t;
  }
}
```
