# Webhook

> 从任何能发送 HTTP POST 的系统启动工作流。在 Webhook 触发器中创建端点，选择 test 或 prod 模式，发送 JSON，同步等待结果或异步运行，并通过 Server-Sent Events 跟踪进度。

Source: https://docs.sommatic.ai/zh/workflows/webhooks/ (updated 2026-11-26)

Webhook 是把工作流接到其他系统之后最简单的方式：外部系统发送 `POST`，Sommatic AI 以该请求为输入运行工作流，
并返回结果，或返回一个可供跟踪的运行 id。

## 创建端点

1. 把 [`webhook.trigger`](https://docs.sommatic.ai/zh/nodes/webhook.trigger.md)（**Webhook Receiver**）添加为工作流的第一个节点。
2. 打开该节点，在 **Webhook URL** 区域点击 **Create webhook endpoint**。
3. Sommatic AI 为工作流创建两个 **ingress binding**，分别标记为 **TEST** 和 **PROD**，并显示它们的 URL 以及可直接复制的 `curl` 命令。

URL 的最后一段用于标识 binding。它最初是为工作流生成的标识符，你可以在同一区域把它改成易读的 slug。

## URL

```text
POST https://api.sommatic.ai/workflow-orchestration/trigger/webhooks/:mode/:bindingIdentifier
```

| 路径段                 | 取值                                                   |
| ------------------- | ---------------------------------------------------- |
| `mode`              | `test` 运行**草稿**；`prod` 运行**默认的已发布版本**。               |
| `bindingIdentifier` | binding 的 id 或 slug。Sommatic AI 先按 id 查找，再按 slug 查找。 |

> **注意: 测试模式运行的是草稿**
>
> `test` 调用运行的是调用时已保存的草稿。请把 `prod` URL 提供给外部系统，改动就绪后再发布。对从未发布的工作流发起
> `prod` 调用会返回 `No published version found for this workflow`。

## 请求

可发送任意 JSON 请求体（最大 5 MB）。工作流会把完整请求作为输入：

| 字段        | 内容          |
| --------- | ----------- |
| `body`    | 你发送的 JSON。  |
| `headers` | 请求头，名称均为小写。 |
| `query`   | 查询字符串参数。    |
| `method`  | `POST`。     |

后续节点用表达式读取：

```javascript
{{ $json.body.data.order_id }}                               // 紧接触发器的节点
{{ $('Webhook Receiver').item.json.body.data.order_id }}     // 之后的任意节点
{{ $('Webhook Receiver').item.json.headers['x-request-id'] }}
```

## 调用示例

**curl**

```bash
curl -X POST "https://api.sommatic.ai/workflow-orchestration/trigger/webhooks/prod/order-intake" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "order.received",
    "data": { "order_id": "ord_abc123", "total": 129.99, "currency": "USD" }
  }'
```

**JavaScript**

```javascript
const response = await fetch(
  'https://api.sommatic.ai/workflow-orchestration/trigger/webhooks/prod/order-intake',
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      event: 'order.received',
      data: { order_id: 'ord_abc123', total: 129.99, currency: 'USD' },
    }),
  },
);
const { success, result } = await response.json();
```

## 同步与异步

默认情况下调用是**同步**的：等待运行结束，返回实例、步骤和结果。

```json
{
  "status": 200,
  "success": true,
  "message": "Operation completed successfully",
  "result": {
    "instance": { "id": "wf-flow-instance-…", "status": "completed" },
    "steps": [
      { "nodeId": "…", "operatorSlug": "webhook.trigger", "status": "success", "port": "out", "durationMs": 2 }
    ],
    "result": {
      "outcome_category": "success",
      "duration_ms": 1840,
      "final_output_envelope": { "node_id": "…", "port": "out", "payload": {} }
    }
  }
}
```

对于耗时较长的工作流，可在查询字符串或请求体中使用 `execution_mode=async` 请求**异步**执行。调用会立即返回运行 id：

```bash
curl -X POST "https://api.sommatic.ai/workflow-orchestration/trigger/webhooks/prod/order-intake?execution_mode=async" \
  -H "Content-Type: application/json" \
  -d '{ "event": "report.generate", "data": { "period": "2026-04" } }'
```

```json
{
  "status": 200,
  "success": true,
  "message": "Operation completed successfully",
  "result": {
    "instance": { "id": "wf-flow-instance-…", "status": "running" },
    "execution_mode": "async"
  }
}
```

之后可通过 SSE 跟踪运行，或稍后通过[执行 API](https://docs.sommatic.ai/zh/api/reference/execution.md)（`flow-instance` 和 `flow-instance-result`）读取。

## 通过 SSE 跟踪进度

为工作流打开一个 Server-Sent Events 流：

```bash
curl -N "https://api.sommatic.ai/workflow-orchestration/execution/stream?flow_definition_id=<flow-definition-id>&user_identity=<your-identity>"
```

两个参数都是必填项。由 Webhook 启动的运行会广播给该工作流上所有已打开的流。事件如下：

| 事件                    | 触发时机                                                  |
| --------------------- | ----------------------------------------------------- |
| `connected`           | 流已打开。                                                 |
| `webhook-received`    | 一次 Webhook 调用到达工作流。                                   |
| `node-step-started`   | 某个节点开始运行。                                             |
| `node-step-progress`  | 耗时较长的节点报告了进度。                                         |
| `node-step-completed` | 某个节点结束，附带端口、耗时和输出（从 `error` 离开时 `status` 为 `failed`）。 |
| `execution-completed` | 运行结束，`status` 为 `completed` 或 `failed`。               |
| `execution-failed`    | 运行在引擎完成之前中断（例如无法连接编排器）。                               |

## 已暂停的工作流

你可以按模式暂停工作流（见[发布](https://docs.sommatic.ai/zh/workflows/publishing.md)）。对已暂停工作流的 `test` 调用会以状态 `423` 被拒绝，
且不会创建运行。`prod` 调用会被接受，并创建状态为 `paused` 的运行，确保调用有据可查。

## 错误

| 消息                                             | 原因                            |
| ---------------------------------------------- | ----------------------------- |
| `Invalid webhook mode. Use "test" or "prod"`   | `mode` 路径段不是 `test` 或 `prod`。 |
| `Webhook binding not found`                    | 没有 binding 使用该 id 或 slug。     |
| `No flow definition bound to this webhook`     | binding 没有指向任何工作流。            |
| `No published version found for this workflow` | 对从未发布的工作流发起了 `prod` 调用。       |

> **说明: 谁可以调用你的 Webhook**
>
> Webhook 路由不接收 Veripass 令牌。如果只应允许某个系统调用，请在触发器之后紧接一个 [`flow.if`](https://docs.sommatic.ai/zh/nodes/flow.if.md)，
> 校验该系统发送的内容，例如某个请求头。

## 下一步

- [触发器 API](https://docs.sommatic.ai/zh/api/reference/triggers.md): Webhook、串联调用与 ingress binding 端点。
- [测试](https://docs.sommatic.ai/zh/workflows/testing.md): 在 Studio 中等待测试调用，观察节点运行。
- [表达式](https://docs.sommatic.ai/zh/expressions.md): 在任意节点中读取请求。
