# Webhook Receiver

> 监听外部 HTTP 请求以触发工作流。

Source: https://docs.sommatic.ai/zh/nodes/webhook.trigger/

- 标识: `webhook.trigger`
- 类别: 触发器
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

监听外部 HTTP 请求以触发工作流。

该算子暴露一个唯一的 URL 端点。当外部服务（例如 Stripe、Typeform、GitHub）向该 URL 发送 POST 请求时，工作流会以请求正文作为载荷进行实例化。

**功能特性：**
- **不限方法：** 可配置为接受 POST、GET、PUT。
- **认证：** 支持校验请求头或签名/密钥。
- **响应：** 可定义返回给调用方的响应（同步或异步）。

**适用场景：**
- 集成表单提交（Typeform）。
- 响应支付事件（Stripe Webhook）。
- 构建自定义 API 端点。

## 配置

- `method` (string, 可选): 默认值: `POST`. 可选值: `POST`, `GET`, `PUT`, `PATCH`, `DELETE`.
- `path` (string, 可选): 自定义路径段（例如 /my-hook）。
- `response_mode` (string, 可选): Immediate：立即返回 200 OK。Workflow End：等待工作流结束后返回结果。 默认值: `immediate`. 可选值: `immediate`, `workflow_end`.

## 输出端口

- `out` (默认): 已收到请求。
- `error`: Error

## 输出契约

- `body` (object, 可选)
- `headers` (object, 可选)
- `query` (object, 可选)

## 在表达式中

后续节点可通过 `$("Webhook Receiver").item.json.<路径>` 读取此节点输出中的内容（请把 `Webhook Receiver` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Webhook Receiver").item.json.body` (object) = `{…}`
- `$("Webhook Receiver").item.json.headers` (object) = `{…}`
- `$("Webhook Receiver").item.json.query` (object) = `{…}`
- `$("Webhook Receiver").item.json.headers.content-type` (string) = `"application/json"` (编辑器不提示)
- `$("Webhook Receiver").item.json.headers.user-agent` (string) = `"curl/8.7.1"` (编辑器不提示)
- `$("Webhook Receiver").item.json.body.event` (string) = `"order.received"` (编辑器不提示)
- `$("Webhook Receiver").item.json.body.data` (object) = `{…}` (编辑器不提示)
- `$("Webhook Receiver").item.json.method` (string) = `"POST"` (编辑器不提示)


## 工作原理

由 HTTP 调用启动的工作流的入口节点。它会校验请求方法和可选的共享密钥，然后输出请求的 `headers`、`body`、`query` 和 `method`。

1. 触发来源：向后端 `/workflow-orchestration/trigger/webhooks/{mode}/{bindingIdentifier}` 发送 `POST`，其中 `bindingIdentifier` 是指向该工作流的入口绑定（ingress binding）ID 或 slug。请求体上限为 5 MB。默认同步执行；在查询串或请求体中设置 `execution_mode=async` 时会立即返回实例 ID。
2. `mode` 为 `test` 时运行工作流草稿；为 `prod` 时运行默认的已发布版本（或最新版本），没有已发布版本时失败。请求会成为运行输入 `{ body, headers, query, method }`。
3. 节点解析配置，并将请求方法（转为大写，默认 `GET`）与 `method`（默认 `POST`）比较，`method` 为 `ANY` 时跳过比较。
4. 校验 `auth_type`：`none`（默认）；`header` 将名为 `auth_config.header_name` 的请求头与 `auth_config.secret` 比较；`basic` 将完整的 `Authorization` 请求头与 `auth_config.secret` 比较；其他值一律拒绝。
5. 经 `out` 输出 `{ headers, body, query, method }`，并附带 `meta.reply_mode`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-webhook",
  "label": "Order webhook",
  "operator_slug": "webhook.trigger",
  "operator_version": "1.0.0",
  "config": {
    "method": "POST",
    "auth_type": "header",
    "auth_config": {
      "header_name": "x-webhook-token",
      "secret": "<shared-secret>"
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "headers": {
      "content-type": "application/json",
      "x-webhook-token": "<shared-secret>"
    },
    "body": {
      "event": "order.received",
      "data": {
        "order_id": "ord_123",
        "total": 129.99
      }
    },
    "query": {},
    "method": "POST"
  },
  "port": "out",
  "meta": {
    "reply_mode": "sync"
  }
}
```

## 输出端口 (代码中的行为)

### `out`

方法和认证校验均通过。请求头名称为小写。

```json
{
  "headers": {
    "content-type": "application/json",
    "user-agent": "curl/8.7.1"
  },
  "body": {
    "event": "order.received",
    "data": {
      "order_id": "ord_123",
      "total": 129.99
    }
  },
  "query": {},
  "method": "POST"
}
```

### `error`

方法或认证校验失败。输出为信封 `{ ok, errors, port, meta: { status_code } }`；`status_code`（405 或 401）仅供参考，不会改变该调用的 HTTP 响应。

```json
{
  "ok": false,
  "errors": [
    "Authentication Failed: Invalid header secret"
  ],
  "port": "error",
  "meta": {
    "status_code": 401
  }
}
```

## 代码中的行为

- `auth_type`: 未声明，`auth_config`（`header_name`、`secret`）和 `reply_mode`（默认 `sync`，仅回显在 `meta` 中）同样未声明。取值按普通字符串比较；`basic` 不会解码请求头。
- `method`: 代码还接受 schema 枚举中没有的 `ANY`。由于后端路由只支持 `POST`，请保持 `POST` 或 `ANY`。
- `path`: 已声明但不会被读取：URL 由入口绑定决定。`response_mode` 同样不会被读取；如需立即响应，请在调用时使用 `execution_mode=async`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Method Not Allowed: Expected <method>, got <incoming>` | `error` | `method` 不是 `POST` 或 `ANY`。入口路由只接受 `POST`，因此其他取值总会失败。 |
| `Authentication Failed: Invalid header secret` | `error` | `auth_type` 为 `header`，但请求头缺失或不一致。`Authentication Failed: Invalid basic auth` 是 `basic` 方式的对应错误。 |
| `Authentication Failed: Auth type <auth_type> not implemented` | `error` | `auth_type` 不是 `none`、`header` 或 `basic`（例如 `jwt` 或 `hmac`）。 |
| `No published version found for this workflow` | `error` | 由后端在节点运行前返回：对从未发布的工作流发起了 `prod` 调用。`Webhook binding not found` 表示绑定 ID 或 slug 错误。 |

## 说明与限制

- 入口端点本身不做认证，安全性取决于本节点的 `auth_type` 和绑定配置。校验失败时仍会创建一次运行，并结束于 `error`。
- 已暂停的工作流不会运行：`test` 模式下调用返回 423，`prod` 模式下返回 200 并生成一个暂停状态的实例。在编辑器中使用示例数据时，引擎会跳过本节点并经 `out` 输出示例输入。
- 在下游可通过 `{{ $json.body.<field> }}` 读取请求内容。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "webhook.trigger",
  "name": "Webhook Receiver",
  "category": "triggers",
  "version": "1.0.0",
  "description": "Listens for external HTTP requests to trigger the workflow.\n\n  This operator exposes a unique URL endpoint. When an external service (e.g., Stripe, Typeform, GitHub) sends a POST request to this URL, the workflow is instantiated with the request body as the payload.\n\n  **Features:**\n  - **Method Agnostic:** Can be configured to accept POST, GET, PUT.\n  - **Authentication:** Supports validating headers or signatures/secrets.\n  - **Response:** Can define what response to send back to the caller (Sync vs Async).\n\n  **Use Cases:**\n  - Integrating form submissions (Typeform).\n  - Reacting to payment events (Stripe Webhook).\n  - Building a custom API endpoint.",
  "capabilities": [
    "http",
    "webhook",
    "api",
    "ingress"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "method": {
        "type": "string",
        "enum": [
          "POST",
          "GET",
          "PUT",
          "PATCH",
          "DELETE"
        ],
        "default": "POST",
        "title": "HTTP Method"
      },
      "path": {
        "type": "string",
        "title": "Route Path",
        "description": "Custom path segment (e.g. /my-hook)."
      },
      "response_mode": {
        "type": "string",
        "enum": [
          "immediate",
          "workflow_end"
        ],
        "default": "immediate",
        "description": "Immediate: Returns 200 OK instantly. Workflow End: Waits for workflow to finish and returns result."
      }
    }
  },
  "input_contract_schema": null,
  "output_contract_schema": {
    "type": "object",
    "description": "The incoming HTTP request data.",
    "properties": {
      "body": {
        "type": "object"
      },
      "headers": {
        "type": "object"
      },
      "query": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Received",
      "is_default": true,
      "description": "Request received."
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "http",
    "api",
    "webhook",
    "trigger"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "method": {
      "type": "string",
      "enum": [
        "POST",
        "GET",
        "PUT",
        "PATCH",
        "DELETE"
      ],
      "default": "POST",
      "title": "HTTP Method"
    },
    "path": {
      "type": "string",
      "title": "Route Path",
      "description": "Custom path segment (e.g. /my-hook)."
    },
    "response_mode": {
      "type": "string",
      "enum": [
        "immediate",
        "workflow_end"
      ],
      "default": "immediate",
      "description": "Immediate: Returns 200 OK instantly. Workflow End: Waits for workflow to finish and returns result."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The incoming HTTP request data.",
  "properties": {
    "body": {
      "type": "object"
    },
    "headers": {
      "type": "object"
    },
    "query": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Received",
    "is_default": true,
    "description": "Request received."
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
