# Webhooks

来源：https://docs.nestjs.com/http/webhooks

`@nestjs/webhooks` 在事务提交之后向你的合作方发送带签名、可重试的 webhook，并在原始请求体上校验你收到的 webhook。

> info **提示** 想了解完整商店中支付服务商的 webhook，请参阅[用 webhook 接收支付](/tutorials/payments-webhooks)。

一个卖猫粮与用品的网店，通过 API 向批量采购的猫舍与经销商供货。经销商 Northside Pet Supplies 下单后想知道何时发货、何时取消，而不想轮询：给它的仓储系统发一个 webhook。这家店也接收 webhook：支付服务商报告付款，承运商报告运输。两个方向看起来都简单，出错的方式却一样：

- **发送。** 订单提交后调用 `fetch()`，如果进程在这中间死掉，这条消息就丢了；而如果那个事务随后回滚，它又已经被发出去了。重试会在不告知合作方的情况下把同一事件发两次。每个合作方都要为自制签名写自己的校验器。宕机一小时的合作方会被反复轰炸，死掉的端点永远不会被关掉，也没人能回答"你到底发了没有？"。而合作方填的那个 URL 是一个随时会爆的服务端请求伪造：`https://169.254.169.254/` 会带着云凭据应答。
- **接收。** 签名校验的是框架解析后又重新序列化的请求体（多一个空格就校验失败，而被篡改的请求体反而可能通过），用 `===` 而不是常量时间比较，没有时间戳窗口，重投的事件会让处理器跑两次：订单被标记为已付两次，或发货两次。

`@nestjs/webhooks` 把两个方向变成一处配置。出站 webhook 走 [outbox](/reliability/outbox)：`webhooks.dispatch()` 在与订单同一个事务中加入消息，提交之后由 worker 把它扇出到合作方的各个端点，按 [Standard Webhooks](https://www.standardwebhooks.com) 规范为每个请求签名，以退避方式重试约两天，记录每次尝试的日志，并可按请求重放。入站 webhook 只需一个装饰器 `@VerifyWebhook()`，它在原始请求体上校验签名并跳过重投。

在本教程中，你将为这家店的订单 API 添加 webhook，数据库使用 PostgreSQL + Drizzle：

- 合作方通过 API 订阅 `order.shipped` 和 `order.cancelled`，并且只看到一次自己的密钥。
- API 在提交之后发送 webhook，带签名，并在合作方宕机期间重试。
- 合作方可以读取自己的投递日志，并申请重放。
- API 接收支付服务商的付款 webhook（Standard Webhooks）和承运商的运输 webhook（Stripe 方案），在原始请求体上校验并恰好处理一次。
- 密钥可以无缝轮换，而指向店内网的 URL 会被拒绝。

#### 安装

开始之前，先安装所需的依赖：

```bash
$ npm i --save @nestjs/webhooks
```

本教程运行在 PostgreSQL 上，通过 [Drizzle ORM](https://orm.drizzle.team) 和 [`@nestjs/drizzle`](/data/drizzle) 使用 `pg` 驱动：端点与投递日志和订单存在同一个数据库里，该数据库服务器的寿命长于应用的任何实例。用 TypeORM 或 MySQL？照本教程做，然后看[把 webhook 存进你的数据库](/http/webhooks#keep-webhooks-in-your-database)中「使用 TypeORM」和「使用 MySQL」两节了解差异。

出站 webhook 是 outbox 消息，入站 webhook 用 outbox 的 inbox 去重，因此应用也要运行 outbox（`@nestjs/outbox`，在 [outbox 教程](/reliability/outbox)中安装并配置）。

示例应用（这家网店的订单 API）把自己的商品目录、调用它的合作方以及它们的订单放在自己的三张表里，后面的小节会读写这些表。它们是示例的数据，不是 webhook 必需的：webhook 与 outbox 的表属于它们各自的存储，由存储创建，见[把 webhook 存进你的数据库](/http/webhooks#keep-webhooks-in-your-database)。

`products` 是商品目录：

| 列 | 类型 | 说明 |
| --- | --- | --- |
| `id` | `text` | 主键，例如 `salmon-kibble-2kg` |
| `name` | `text` | 显示名称，例如 `Salmon kibble, 2 kg` |
| `price` | `integer` | 以分为单位 |

`partners` 保存通过 API 批量采购并接收其 webhook 的猫舍与经销商：

| 列 | 类型 | 说明 |
| --- | --- | --- |
| `id` | `text` | 主键，例如 `northside` |
| `name` | `text` | 显示名称，例如 `Northside Pet Supplies` |
| `api_key_hash` | `text` | 合作方 API key 的 SHA-256 十六进制值。唯一 |

`orders` 保存合作方的订单，其 `status` 从 `placed` 变为 `paid` 和 `shipped`，或变为 `cancelled`：

| 列 | 类型 | 说明 |
| --- | --- | --- |
| `id` | `text` | 主键 |
| `partner_id` | `text` | 引用 `partners.id` |
| `items` | `jsonb` | 订单行，JSON 数组：每行的 `productId`、`quantity` 与单价 `price`（分） |
| `total` | `integer` | 以分为单位 |
| `status` | `text` | `placed`、`paid`、`shipped` 或 `cancelled` |
| `payment_id` | `text` | 可空：订单支付时设置 |
| `tracking_number` | `text` | 可空：订单发货时设置 |

其他列不可为空。

目录里有两个商品，`salmon-kibble-2kg` 售价 2499 分，`clumping-litter-10l` 售价 1599 分；两个合作方有示例 API key（正式的要通过你的合作方入驻流程签发）：

| 合作方 | `id` | API key |
| --- | --- | --- |
| Northside Pet Supplies（经销商） | `northside` | `partner_northside_7c1d2e` |
| Riverside Cat Shelter | `riverside` | `partner_riverside_91ab44` |

#### 把 webhook 存进你的数据库

webhook 本身、以及它们经过的 outbox，都不需要你创建任何东西：没有表、实体或 Prisma 模型。注册它们的两个存储，每个都会创建自己的 schema（`nest_webhooks` 和 `nest_outbox`）并迁移它：开发与测试中在启动时迁移，生产中用 `npx @nestjs/webhooks migrate` 和 `npx @nestjs/outbox migrate`，或在你的迁移里调用它们的 `migrationSql()`。

该包把端点及其密钥、已派发的消息、它们的投递以及每次尝试的日志保存在一个**存储**（store）中，并通过两个契约读取它：`WebhookEndpointStore` 与 `WebhookDeliveryStore`。在你注册存储之前，模块把它们放在内存里：首次运行没问题，但重启会丢掉所有待投递的记录，两个实例之间也不共享。

> warning **警告** 若 `NODE_ENV=production` 且未注册存储，启动会失败，除非设置 `allowInMemoryStorage: true`。

在 PostgreSQL 上，注册该包提供的存储：来自 `@nestjs/webhooks/postgres` 的 `PostgresWebhookStore`。outbox 也需要一个存储，用于把已派发的 webhook 带出你的事务，以及用于给入站消息去重的 inbox：来自 `@nestjs/outbox/postgres` 的 `PostgresOutboxStore`，如 [outbox 教程](/reliability/outbox#keep-messages-in-your-database)所述。两者都通过你应用已有的数据库客户端执行 SQL，并把表放在各自的 schema 中。它们是普通提供者，在根模块中注册一次，与 `WebhooksModule` 和 `OutboxModule` 并列：四者都是应用级的。`AppModule` 用工厂创建每个存储，注入 Drizzle 数据库和该包的存储注册表（存储会把自己注册进去）：

```typescript
@@filename(app.module)
{
  // Outbox messages and the inbox, in your database, in a schema of their own (nest_outbox)
  provide: PostgresOutboxStore,
  inject: [getDrizzleToken(), OutboxStorage],
  useFactory: (db: Database, outboxStorage: OutboxStorage) =>
    new PostgresOutboxStore({ executor: fromDrizzle(db) }, outboxStorage),
},
{
  // Endpoints, deliveries and their log, in your database, in a schema of their own (nest_webhooks)
  provide: PostgresWebhookStore,
  inject: [getDrizzleToken(), WebhooksStorage],
  useFactory: (db: Database, webhooksStorage: WebhooksStorage) =>
    new PostgresWebhookStore({ executor: fromDrizzle(db) }, webhooksStorage),
},
```

`fromDrizzle(db)` 是这些存储的**执行器**（executor）：它通过你的 Drizzle 数据库执行语句，无论其驱动是 `pg` 还是 PGlite。`fromPg(pool)`、`fromTypeOrm(dataSource)`、`fromPrisma(prisma)` 和 `fromKysely(db)` 分别为 node-postgres 连接池、TypeORM、Prisma 和 Kysely 做同样的事。`@nestjs/webhooks/postgres` 与 `@nestjs/outbox/postgres` 都导出它们，因此 `AppModule` 只需导入一次 `fromDrizzle`，供两个存储共用。启动时，每个模块都会记录它使用的存储。

**schema。** webhook 存储把自己的表放在独立的 schema `nest_webhooks` 中（`schema` 选项可指定别的名字）。在 MySQL 上（它没有 schema），它们是连接所在数据库中的表，并以 schema 名作前缀：`nest_webhooks_endpoints` 等。

| 表 | 内容 |
| --- | --- |
| `nest_webhooks.endpoints` | 合作方的端点：URL、事件类型、租户与密钥 |
| `nest_webhooks.messages` | 已派发的内容，逐字节保存 |
| `nest_webhooks.deliveries` | 每条消息对每个端点一条，含状态、尝试次数与租约 |
| `nest_webhooks.delivery_attempts` | 日志：每次尝试，含状态码、响应与耗时 |
| `nest_webhooks.migrations` | 已应用的存储 schema 版本 |

outbox 的存储把消息、死信和 inbox 放在 `nest_outbox` 中（MySQL 上为 `nest_outbox_messages` 等），如 [outbox 教程](/reliability/outbox#keep-messages-in-your-database)所述。它们属于存储：你的迁移不会创建它们，你自己的表也不会与它们冲突。其中有几个设计选择对该包很重要：

- 端点的密钥是一个 JSON 数组，最新的在前：轮换期间，旧密钥会带过期时间保留一段时间。配置了 `encryption`（见[注册模块](/http/webhooks#register-the-modules)）时，保存的是密封后的内容。
- 消息的 `body` 是 `text` 而不是 `jsonb`。它就是被签名并发送的那份精确 JSON，而 `jsonb` 会重新格式化它：合作方若保存了请求及其签名，重放时就再也验证不过。
- 一条投递在消息与端点的组合上唯一。创建投递的扇出在提交之后、outbox 内部运行，因此可能跑两次；唯一键让第二次插入不生效。
- 投递到端点之间没有外键：端点删除后其日志仍保留。尝试记录随投递一起删除。
- 时间是以毫秒为单位的纪元值（`bigint`），来自该包的时钟，绝不用数据库的。

**迁移。** 这些包把 schema 以带版本的迁移形式发布，存储自行应用。启用 `migrate` 选项时，每个存储在启动时（relay 与 worker 运行之前）应用其 schema 尚未拥有的版本，整个过程在一个持有 advisory lock 的事务中完成：多个实例同时启动时只有一个执行迁移，其余发现无事可做。`migrate` 默认为 `true`，但 `NODE_ENV=production` 时例外。因此在开发与测试中，存储在首次启动时创建自己的 schema，你的迁移只创建自己的表。

在生产环境，请在新版本应用启动之前应用这些迁移（就像应用你自己的迁移一样），以免任何实例在启动过程中改动 schema：滚动发布期间那会锁住繁忙的表，而且最小权限的数据库用户本来也做不了。这些包的命令行可在部署步骤中执行，与 `npx drizzle-kit migrate` 并列。它们从 `DATABASE_URL` 或 `--url` 读取数据库，并需要安装 `pg`：

```bash
$ npx @nestjs/webhooks status
Schema "nest_webhooks" is at version 0; this version of @nestjs/webhooks needs version 1.
$ npx @nestjs/webhooks migrate
Migrated schema "nest_webhooks" to version 1 (applied 1).
$ npx @nestjs/outbox migrate
Migrated schema "nest_outbox" to version 1 (applied 1).
```

schema 落后时 `status` 以 1 退出，因此可作为 CI 检查。若想改用你自己的迁移工具应用这些迁移，请从 `npx @nestjs/webhooks sql` 和 `npx @nestjs/outbox sql` 获取其 SQL，或在代码中调用 `PostgresWebhookStore.migrationSql()` 与 `PostgresOutboxStore.migrationSql()`：其中包含每个迁移的语句，以及记录版本的簿记语句。请像 TypeORM 和 Drizzle 的迁移器那样，在单个事务中运行它们。使用 TypeORM 时，这就是你自己的一个迁移，与它为你实体生成的迁移并列：

```typescript
@@filename(typeorm/migrations/1790801311590-WebhookStores)
import { PostgresOutboxStore } from '@nestjs/outbox/postgres';
import { PostgresWebhookStore } from '@nestjs/webhooks/postgres';
import type { MigrationInterface, QueryRunner } from 'typeorm';

export class WebhookStores1790801311590 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(PostgresOutboxStore.migrationSql());
    await queryRunner.query(PostgresWebhookStore.migrationSql());
  }

  async down(): Promise<void> {
    throw new Error('The webhook and outbox stores have no down migrations.');
  }
}
```

使用 drizzle-kit 时，为每个存储创建一个自定义迁移，并把生成的空文件填上其 SQL，语句之间用 `--> statement-breakpoint` 分隔：Drizzle 的迁移器随后会逐条执行，这是 PGlite 要求的。在代码中，带 `statementBreakpoints: true` 的 `migrationSql()` 返回相同内容。

```bash
$ npx drizzle-kit generate --custom --name=outbox
$ npx @nestjs/outbox sql --statement-breakpoints > drizzle/20261103120000_outbox/migration.sql
$ npx drizzle-kit generate --custom --name=webhooks
$ npx @nestjs/webhooks sql --statement-breakpoints > drizzle/20261103120100_webhooks/migration.sql
```

在 MySQL 上，存储的 `migrationStatements()` 把语句逐条返回，TypeORM 迁移每次调用执行一条：

```typescript
@@filename(typeorm/mysql-migrations/1790801311590-WebhookStores)
for (const statement of [...MySqlOutboxStore.migrationStatements(), ...MySqlWebhookStore.migrationStatements()]) {
  await queryRunner.query(statement);
}
```

关闭 `migrate` 时，schema 落后的存储会让启动失败，抛出 `WebhookSchemaError`（outbox 的存储是 `OutboxSchemaError`），错误中列出上述三种做法；并且每次调用都以同样方式失败，直到 schema 追上——它会自动发现，无需重启。滚动发布期间，应用的前一版本会继续运行在新版本已迁移的 schema 上。没有向下迁移。

**事务。** webhook 存储的任何方法都不接受你的事务。`webhooks.dispatch(tx, ...)` 在你的事务中通过 outbox 的存储把消息加入 outbox，`webhook.processInTransaction(tx, ...)` 以同样方式把入站 webhook 记录到 outbox 的 inbox；提交之后的扇出、worker 以及其他一切都在存储自己的连接上运行。使用 Drizzle 时，`tx` 就是 `db.transaction()` 传给回调的对象，后面的小节会展示。outbox 的存储会拒绝数据库对象本身（它的语句会自行提交），并抛出 `OutboxTransactionRequiredError` 说明该传什么。使用其他执行器时，请传 `BEGIN` 之后的 node-postgres 客户端（不是连接池）、来自 `dataSource.transaction()` 的 TypeORM `EntityManager`、Prisma 的交互式事务客户端，或 Kysely 事务。

**隔离级别。** 这些存储依赖 READ COMMITTED（PostgreSQL 的默认隔离级别）：它们的语句彼此竞争，在更严格的级别下会以序列化错误失败。启动时每个存储都会检查数据库的 `default_transaction_isolation`，若更严格则失败。你自己的事务可以在任意级别运行。不过在 REPEATABLE READ 或 SERIALIZABLE 下，`processInTransaction()` 在你事务中处理的入站 webhook 副本若与第一次的提交竞争，会以 PostgreSQL 的序列化错误失败，而不是被当作重复跳过：发送方收到错误，其重试会发现该 webhook 已被记录。

**使用 TypeORM。** `TypeOrmModule` 取代 `AppModule` 中的 `DrizzleModule`，两个存储都通过 `fromTypeOrm()` 运行在它提供的 `DataSource` 上：

```typescript
@@filename(typeorm/app.module)
{
  // Outbox messages and the inbox, in your database, in a schema of their own (nest_outbox)
  provide: PostgresOutboxStore,
  inject: [DataSource, OutboxStorage],
  useFactory: (dataSource: DataSource, outboxStorage: OutboxStorage) =>
    new PostgresOutboxStore({ executor: fromTypeOrm(dataSource) }, outboxStorage),
},
{
  // Endpoints, deliveries and their log, in your database, in a schema of their own (nest_webhooks)
  provide: PostgresWebhookStore,
  inject: [DataSource, WebhooksStorage],
  useFactory: (dataSource: DataSource, webhooksStorage: WebhooksStorage) =>
    new PostgresWebhookStore({ executor: fromTypeOrm(dataSource) }, webhooksStorage),
},
```

教程中把 Drizzle 的 `tx` 传给 `dispatch()` 和 `processInTransaction()` 的地方，改为传 `dataSource.transaction()` 交给回调的 `EntityManager`，并注入 `Webhooks<EntityManager>`。outbox 的存储会拒绝 `dataSource.manager`（它的写入会自行提交）。下面是订单服务的 `cancelOrder()`（出自[在提交后发送 order.shipped 与 order.cancelled](/http/webhooks#send-ordershipped-and-ordercancelled-after-the-commit)）在 TypeORM 下的写法：

```typescript
@@filename(typeorm/orders.service)
const order = await this.dataSource.transaction(async (manager) => {
  const row = await manager.findOne(OrderEntity, { where: { id, partnerId: partner.id }, lock: { mode: 'pessimistic_write' } });
  if (!row) {
    throw new NotFoundException(`Order ${id} not found`);
  }
  if (row.status === 'shipped' || row.status === 'cancelled') {
    throw new ConflictException(`Order ${id} is ${row.status}`);
  }
  await manager.update(OrderEntity, id, { status: 'cancelled' });

  // The transaction's EntityManager: the webhook is sent only if the cancellation commits.
  const data: OrderCancelled = { orderId: id, reason };
  await this.webhooks.dispatch(manager, { type: 'order.cancelled', tenant: row.partnerId, data });
  return { ...row, status: 'cancelled' as const };
});
```

你的实体及其迁移保持不变：`migration:generate` 只把你的实体与数据库比较，不会动存储的 schema。

**使用 MySQL。** 在 MySQL 8.4 或 9.x 上，改为从 `@nestjs/outbox/mysql` 和 `@nestjs/webhooks/mysql` 导入存储与执行器。提供者相同，只是换成 `MySqlOutboxStore` 和 `MySqlWebhookStore`，运行在 `drizzle-orm/mysql2` 的 Drizzle 数据库上：

```typescript
@@filename(mysql/app.module)
import { MySqlOutboxStore } from '@nestjs/outbox/mysql';
import { fromDrizzle, MySqlWebhookStore } from '@nestjs/webhooks/mysql';
import { drizzle } from 'drizzle-orm/mysql2';
// ...
DrizzleModule.forRootAsync({
  // Drizzle on MySQL: a mysql2 pool on DATABASE_URL (mysql://), whose database holds the stores' tables too
  useFactory: () => ({ drizzle, connection: process.env.DATABASE_URL! }),
}),
// ...
{
  // Outbox messages and the inbox, in your database, in tables of their own (nest_outbox_*)
  provide: MySqlOutboxStore,
  inject: [getDrizzleToken(), OutboxStorage],
  useFactory: (db: Database, outboxStorage: OutboxStorage) =>
    new MySqlOutboxStore({ executor: fromDrizzle(db) }, outboxStorage),
},
{
  // Endpoints, deliveries and their log, in your database, in tables of their own (nest_webhooks_*)
  provide: MySqlWebhookStore,
  inject: [getDrizzleToken(), WebhooksStorage],
  useFactory: (db: Database, webhooksStorage: WebhooksStorage) =>
    new MySqlWebhookStore({ executor: fromDrizzle(db) }, webhooksStorage),
},
```

使用其他客户端时，执行器分别是：`mysql2/promise` 连接池用 `fromMysql2(pool)`，类型为 `mysql` 的 `DataSource` 用 `fromTypeOrm(dataSource)`，经 `@prisma/adapter-mariadb` 的 Prisma 用 `fromPrisma(prisma)`，Kysely 的 `MysqlDialect` 用 `fromKysely(db)`。与 PostgreSQL 不同之处：

- **是表，不是 schema。** MySQL 的数据库内没有 schema，因此存储把表放在连接所在的数据库（URL 路径中的那个）里，与你的表并列，而 `schema` 变成它们的前缀：`nest_webhooks_endpoints`、`nest_webhooks_deliveries` 等，outbox 则是 `nest_outbox_messages`。前缀只接受小写字母、数字和下划线，最多 40 个字符。
- **你的事务。** `dispatch()` 和 `processInTransaction()` 在 REPEATABLE READ（MySQL 的默认）下与在 READ COMMITTED 下一样工作：无需配置，存储也不检查数据库的默认级别。当 MySQL 在你的事务中打破死锁（错误 1213）时，会回滚整个事务，客户端的错误会传到你的代码：重新执行该事务。存储自己的事务会自行重试。使用 `processInTransaction()` 时，同一 webhook 的多份副本同时到达且第一份的事务回滚就可能触发：发送方收到错误，其重试会通过。
- **键有长度上限。** id 和租户是带索引的列：最多 255 个字符，租户 256 个，该包自有的 id 及其对 `tenant` 的限制都在范围内。入站 webhook 的 id 会进入 inbox 的键（同样最多 255 个字符），且校验器在所有数据库上都会以 401 拒绝更长的 id，这发生在处理器运行之前。
- **迁移不是单个事务。** MySQL 让每条 DDL 语句自行提交，因此 `migrate` 在锁（`GET_LOCK()`）下逐条应用语句，失败的运行会从停下的语句继续。你自己的工具也必须每次调用只发一条语句，如上面**迁移**中的 TypeORM 迁移那样。命令行接受 `mysql://` URL，`sql --dialect mysql` 打印 MySQL 的 SQL：给 drizzle-kit 自定义迁移加上 `--statement-breakpoints`，因为其 MySQL 迁移器按断点逐条发送。
- **服务器。** 存储在启动时检查它，并拒绝 MariaDB、未选择数据库的连接，以及非严格（MySQL 默认是严格）的 `sql_mode`。也不要让 `NO_BACKSLASH_ESCAPES` 出现在其中。

要用其他数据库，请自己写一个存储：[存储契约](/http/webhooks#the-store-contract)说明了它必须做什么。

#### 注册模块

在根模块中注册 `OutboxModule` 和 `WebhooksModule`，与注册 Drizzle 数据库的 `DrizzleModule` 并列，并把两个存储放进它的 `providers`。特性模块在后续小节中构建：

```typescript
@@filename(app.module)
import { Module } from '@nestjs/common';
import { DrizzleModule, getDrizzleToken } from '@nestjs/drizzle';
import { OutboxModule, OutboxStorage } from '@nestjs/outbox';
import { PostgresOutboxStore } from '@nestjs/outbox/postgres';
import { WebhooksModule, WebhooksStorage } from '@nestjs/webhooks';
import { fromDrizzle, PostgresWebhookStore } from '@nestjs/webhooks/postgres';
import { drizzle } from 'drizzle-orm/node-postgres';
import type { Database } from './database/drizzle.js';
import * as schema from './database/schema.js';
import { OrdersModule } from './orders/orders.module.js';
import { PartnerWebhooksModule } from './partner-webhooks/partner-webhooks.module.js';

@Module({
  imports: [
    // A pg pool on DATABASE_URL, closed in onApplicationShutdown(), after the relay and the
    // worker drained. The services inject it with @InjectDrizzle(), the stores' factories too.
    DrizzleModule.forRootAsync({
      useFactory: () => ({ drizzle, connection: process.env.DATABASE_URL!, schema }),
    }),
    // Outgoing webhooks travel through the outbox: dispatched in the order's transaction,
    // handed to the webhooks worker after the commit.
    OutboxModule.forRootAsync({
      useFactory: () => ({
        relay: { enabled: process.env.OUTBOX_RELAY !== 'off', pollInterval: '1s' },
      }),
    }),
    WebhooksModule.forRootAsync({
      useFactory: () => ({
        // The types partners may subscribe to; dispatch() refuses any other.
        eventTypes: ['order.shipped', 'order.cancelled'],
        // Ten attempts: 5s, 20s, 80s, ... capped at a day, about two days in all.
        retry: { attempts: 10, backoff: { delay: '5s', factor: 4, maxDelay: '1d' } },
        // An endpoint that fails every attempt for five days is switched off.
        disableEndpointAfter: '5d',
        delivery: {
          timeout: '15s',
          // Development only: deliver over http:// and to this machine. Without it, only
          // public https:// endpoints are accepted.
          allowHttp: process.env.WEBHOOKS_ALLOW_LOCAL === '1',
          allowPrivateNetworks: process.env.WEBHOOKS_ALLOW_LOCAL === '1',
        },
        worker: { enabled: process.env.WEBHOOKS_WORKER !== 'off', pollInterval: '1s' },
        // Endpoint secrets at rest: the first key encrypts, every key decrypts.
        encryption: process.env.WEBHOOKS_ENCRYPTION_KEYS
          ? { keys: process.env.WEBHOOKS_ENCRYPTION_KEYS.split(',').map((key) => key.trim()) }
          : undefined,
      }),
    }),
    OrdersModule,
    PartnerWebhooksModule,
  ],
  providers: [
    {
      // Outbox messages and the inbox, in your database, in a schema of their own (nest_outbox)
      provide: PostgresOutboxStore,
      inject: [getDrizzleToken(), OutboxStorage],
      useFactory: (db: Database, outboxStorage: OutboxStorage) =>
        new PostgresOutboxStore({ executor: fromDrizzle(db) }, outboxStorage),
    },
    {
      // Endpoints, deliveries and their log, in your database, in a schema of their own (nest_webhooks)
      provide: PostgresWebhookStore,
      inject: [getDrizzleToken(), WebhooksStorage],
      useFactory: (db: Database, webhooksStorage: WebhooksStorage) =>
        new PostgresWebhookStore({ executor: fromDrizzle(db) }, webhooksStorage),
    },
  ],
})
export class AppModule {}
```

`WebhooksModule` 需要 outbox：`dispatch()` 就是一次 `Outbox.add()`，而把已提交消息变成投递的扇出是一个 outbox 处理器。没有 `OutboxModule`，启动会失败并说明原因。outbox 的 `relay` 把已提交消息交给扇出，每秒轮询一次，`OUTBOX_RELAY=off` 可关闭它。其余选项在应用启动时解析：

- `eventTypes`：本应用发送的消息类型。`dispatch()` 拒绝其他任何类型，端点尝试订阅其他类型时也会被拒绝，并在消息中给出已知类型。
- `retry`：与 outbox、HTTP 客户端和弹性机制共享的词汇。十次尝试，退避从 5 秒开始，每次增长四倍，上限一天，并带抖动：正是 Standard Webhooks 规范推荐的"跨越数天的重试计划"。
- `disableEndpointAfter`：连续五天每次尝试都失败且无一成功的端点会被关闭，并通知其所有者（见[重试、投递日志与重放](/http/webhooks#retries-the-delivery-log-and-replay)）。
- `delivery`：一次尝试有 15 秒，用于 DNS、连接、TLS、请求与响应。`allowHttp` 和 `allowPrivateNetworks` 默认关闭：只接受公开的 `https://` 端点。`WEBHOOKS_ALLOW_LOCAL=1` 在开发环境中打开它们，此时合作方的接收端运行在本机。云元数据地址即使在那时也仍然被屏蔽。
- `worker`：后台投递器，每个进程一个。`WEBHOOKS_WORKER=off` 可在只提供 API 的实例上关闭它。
- `encryption`：端点密钥静态加密，采用该系列的统一形状：第一个密钥加密，所有密钥都能解密。可选，来自 `WEBHOOKS_ENCRYPTION_KEYS`。

> info **提示** 为简明起见，教程直接读取 `process.env`。在真实应用中，请通过 [`@nestjs/config`](/application/configuration) 加校验 schema 加载环境变量，使缺失的变量在启动时而非首个请求时中止应用，并从 `ConfigService` 读取值（工厂里 `inject: [ConfigService]`）。

时长可以是毫秒数，或 `'15s'`、`'5d'` 这样的字符串。两个模块都是全局的：`Webhooks`、`WebhookEndpoints`、`WebhookDeliveries`、`WebhooksEvents` 和 `WebhooksStorage` 可在任何地方注入。`main.ts` 为合作方 API 的 DTO 绑定校验管道（见下一节），并启用关闭钩子，使部署时 relay 与 worker 能完成手上的工作：

```typescript
@@filename(main)
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // The partner API's DTOs; whitelist: properties without a decorator are dropped.
  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
  // On SIGTERM the outbox relay and the webhook worker finish what they started.
  app.enableShutdownHooks();
  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();
```

启动时两个模块都会记录所使用的存储，首次启动时存储还会记录它们创建的 schema：

```bash
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [OutboxModule] OutboxStorage: PostgresOutboxStore
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [WebhooksModule] WebhooksStorage: PostgresWebhookStore
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [OutboxModule] PostgresOutboxStore: migrated schema "nest_outbox" to version 1.
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [WebhooksModule] PostgresWebhookStore: migrated schema "nest_webhooks" to version 1.
```

#### 让合作方订阅

猫舍和经销商用 API key 调用合作方 API：示例中的两个合作方 Northside Pet Supplies（经销商）和 Riverside Cat Shelter 的示例密钥见[安装](/http/webhooks#installation)。`PartnerGuard` 查出密钥的哈希并把合作方设置到请求上，`@CurrentPartner()` 读取它：

```typescript
@@filename(partners/partner.guard)
import {
  createParamDecorator,
  Injectable,
  UnauthorizedException,
  type CanActivate,
  type ExecutionContext,
} from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { eq } from 'drizzle-orm';
import { createHash } from 'node:crypto';
import type { Database } from '../database/drizzle.js';
import { partners } from '../database/schema.js';

export interface Partner {
  id: string;
  name: string;
}

/** Authenticates a partner by its API key: `Authorization: Bearer <key>`. */
@Injectable()
export class PartnerGuard implements CanActivate {
  constructor(@InjectDrizzle() private readonly db: Database) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<{ headers: Record<string, string>; partner?: Partner }>();
    const key = /^Bearer (\S+)$/.exec(request.headers.authorization ?? '')?.[1];
    if (!key) {
      throw new UnauthorizedException();
    }
    const hash = createHash('sha256').update(key).digest('hex');
    const [partner] = await this.db
      .select({ id: partners.id, name: partners.name })
      .from(partners)
      .where(eq(partners.apiKeyHash, hash));
    if (!partner) {
      throw new UnauthorizedException();
    }
    request.partner = partner;
    return true;
  }
}

/** The partner `PartnerGuard` authenticated. */
export const CurrentPartner = createParamDecorator(
  (_data: unknown, context: ExecutionContext) => context.switchToHttp().getRequest<{ partner: Partner }>().partner,
);
```

一个订阅由 URL、要接收的事件类型和一段描述组成；更新时只发送发生变化的部分。DTO 只检查形状，URL 与事件类型留给该包检查，因为它知道哪些是可接受的。请求体按应用已有的方式校验：本页每个 DTO 都出现两次，一次是带 `class-validator` 装饰器的类，一次是 Zod schema，选你已在用的那种，跳过另一种写法：

```typescript
@@filename(partner-webhooks/webhook-endpoints.dto)
import { IsArray, IsBoolean, IsOptional, IsString } from 'class-validator';

/** Body of `POST /partner/webhook-endpoints`. The package checks the URL and the types themselves. */
export class CreateEndpointDto {
  @IsString()
  url: string;

  /** `order.shipped`, `order.cancelled`, or `*` for both. */
  @IsArray()
  @IsString({ each: true })
  eventTypes: string[];

  @IsOptional()
  @IsString()
  description?: string;
}

/** Body of `PATCH /partner/webhook-endpoints/:id`: only what is sent changes. */
export class UpdateEndpointDto {
  @IsOptional()
  @IsString()
  url?: string;

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  eventTypes?: string[];

  @IsOptional()
  @IsString()
  description?: string | null;

  @IsOptional()
  @IsBoolean()
  enabled?: boolean;
}
```

同样的规则写成 Zod schema，其推导类型取代类。Nest 12.1 通过 `StandardSchemaValidationPipe` 校验任何 [Standard Schema](https://standardschema.dev/) 对象，无论是来自 Zod、Valibot 还是 ArkType：

```typescript
@@filename(partner-webhooks/webhook-endpoints.schemas)
import { z } from 'zod';

/** Body of `POST /partner/webhook-endpoints`. The package checks the URL and the types themselves. */
export const createEndpointSchema = z.object({
  url: z.string(),
  /** `order.shipped`, `order.cancelled`, or `*` for both. */
  eventTypes: z.array(z.string()),
  description: z.string().optional(),
});
export type CreateEndpointDto = z.infer<typeof createEndpointSchema>;

/** Body of `PATCH /partner/webhook-endpoints/:id`: only what is sent changes. */
export const updateEndpointSchema = z.object({
  url: z.string().optional(),
  eventTypes: z.array(z.string()).optional(),
  description: z.string().nullable().optional(),
  enabled: z.boolean().optional(),
});
export type UpdateEndpointDto = z.infer<typeof updateEndpointSchema>;
```

订阅 API 是一个包裹 `WebhookEndpoints` 的控制器。每次调用都把合作方的 id 作为**租户**传入：端点按该租户创建、按该租户列出，别的合作方的端点 id 表现得像不存在一样：

```typescript
@@filename(partner-webhooks/webhook-endpoints.controller)
import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  NotFoundException,
  Param,
  Patch,
  Post,
  UseGuards,
} from '@nestjs/common';
import { WebhookEndpoints } from '@nestjs/webhooks';
import { CurrentPartner, PartnerGuard, type Partner } from '../partners/partner.guard.js';
import { CreateEndpointDto, UpdateEndpointDto } from './webhook-endpoints.dto.js';

/** A partner's subscriptions. Every call is scoped to the partner: another partner's endpoint is a 404. */
@Controller('partner/webhook-endpoints')
@UseGuards(PartnerGuard)
export class WebhookEndpointsController {
  constructor(private readonly webhookEndpoints: WebhookEndpoints) {}

  /** Returns the endpoint and its secret. The secret is shown this once. */
  @Post()
  create(@CurrentPartner() partner: Partner, @Body() dto: CreateEndpointDto) {
    return this.webhookEndpoints.create({
      url: dto.url,
      eventTypes: dto.eventTypes,
      description: dto.description ?? null,
      tenant: partner.id,
    });
  }

  @Get()
  list(@CurrentPartner() partner: Partner) {
    return this.webhookEndpoints.list({ tenant: partner.id });
  }

  @Get(':id')
  async get(@CurrentPartner() partner: Partner, @Param('id') id: string) {
    const endpoint = await this.webhookEndpoints.get(id, { tenant: partner.id });
    if (!endpoint) {
      throw new NotFoundException(`Webhook endpoint ${id} not found`);
    }
    return endpoint;
  }

  @Patch(':id')
  update(@CurrentPartner() partner: Partner, @Param('id') id: string, @Body() dto: UpdateEndpointDto) {
    return this.webhookEndpoints.update(id, dto, { tenant: partner.id });
  }

  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  async delete(@CurrentPartner() partner: Partner, @Param('id') id: string) {
    await this.webhookEndpoints.delete(id, { tenant: partner.id });
  }

  /** A new secret. The old one keeps signing for 24 hours, so the partner can switch without a gap. */
  @Post(':id/rotate-secret')
  @HttpCode(HttpStatus.OK)
  async rotateSecret(@CurrentPartner() partner: Partner, @Param('id') id: string) {
    return { secret: await this.webhookEndpoints.rotateSecret(id, { tenant: partner.id }) };
  }
}
```

使用 Zod schema 时，请求体参数声明其 schema 而不是类：

```typescript
@@filename(partner-webhooks/webhook-endpoints.controller)
import { createEndpointSchema, updateEndpointSchema, type CreateEndpointDto, type UpdateEndpointDto } from './webhook-endpoints.schemas.js';
// ...
@Post()
create(@CurrentPartner() partner: Partner, @Body({ schema: createEndpointSchema }) dto: CreateEndpointDto) {
  // ...
}

@Patch(':id')
update(@CurrentPartner() partner: Partner, @Param('id') id: string, @Body({ schema: updateEndpointSchema }) dto: UpdateEndpointDto) {
  // ...
}
```

> info **提示** DTO 只有靠校验管道才生效：在 `main.ts` 中用 `useGlobalPipes()` 全局绑定 `ValidationPipe`（如[注册模块](/http/webhooks#register-the-modules)所做，`whitelist` 会丢弃没有装饰器的属性），或作为 `APP_PIPE` 提供者绑定。使用 Zod schema 时，改为以同样方式绑定 `StandardSchemaValidationPipe`：一个应用只用其中一种。[校验](/application/validation)页给出了各自的选项。

`create()` 返回端点及其 `secret`——一个由 32 个随机字节生成的 Standard Webhooks `whsec_…`，就在这里生成。本 API 只展示这一次：`list()` 和 `get()` 从不包含它，丢失的合作方去轮换。该包保存密钥（设置 `encryption` 时是密封的），因为它要用它签名；`getSecret()` 可读回当前密钥，供你在 API 提供"重新显示"按钮时使用（按钮前应要求重新登录）。从 Svix 或其他 Standard Webhooks 发送方迁移过来的端点保留其密钥：迁移脚本把合作方现有的 `whsec_…` 作为 `create()` 的 `secret` 传入，合作方的校验器便继续工作，`rotateSecret()` 也以同样方式接受给定的 `secret`。该包会检查合作方提交的内容，并以 400 状态抛出 `InvalidWebhookEndpointError`：不是 `https://` 的 URL（或未开启 `allowHttp` 时的 `http://`）、携带凭据的 URL、主机为被屏蔽地址的 URL（如 `https://169.254.169.254/latest/meta-data/` 或 `https://localhost/`），以及不在 `eventTypes` 中的事件类型。合作方的失误以 400 返回，别的合作方的 id 以 404 返回，通过一个过滤器：

```typescript
@@filename(partner-webhooks/webhooks-error.filter)
import { Catch, HttpException, type ArgumentsHost } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { WebhooksError } from '@nestjs/webhooks';

/**
 * The package's errors carry an HTTP status (400 for an endpoint it refuses, 404 for another
 * partner's endpoint or delivery); this answers with it and the error's message.
 */
@Catch(WebhooksError)
export class WebhooksErrorFilter extends BaseExceptionFilter {
  override catch(error: WebhooksError, host: ArgumentsHost) {
    const status = (error as { status?: number }).status;
    super.catch(status ? new HttpException(error.message, status, { cause: error }) : error, host);
  }
}
```

```typescript
@@filename(partner-webhooks/partner-webhooks.module)
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { WebhookDeliveriesController } from './webhook-deliveries.controller.js';
import { WebhookEndpointsController } from './webhook-endpoints.controller.js';
import { WebhooksErrorFilter } from './webhooks-error.filter.js';

@Module({
  controllers: [WebhookEndpointsController, WebhookDeliveriesController],
  // Turns the package's errors (a refused URL, another partner's endpoint) into 4xx responses.
  providers: [{ provide: APP_FILTER, useClass: WebhooksErrorFilter }],
})
export class PartnerWebhooksModule {}
```

投递日志的控制器会在[后面](/http/webhooks#retries-the-delivery-log-and-replay)加入这个模块，为合作方提供另一半：发往其端点的内容。

#### 在提交后发送 order.shipped 与 order.cancelled

`Webhooks.dispatch()` 像 `Outbox.add()` 一样先接收你的事务句柄：使用 Drizzle 时，就是 `db.transaction()` 传给回调的 `tx`，服务把它的类型声明为 `Webhooks<Transaction>`。取消订单会在同一个 `tx` 上更新订单并派发 `order.cancelled`；发货（由承运商触发，见[接收承运商类 Stripe 的 webhook](/http/webhooks#receive-the-carriers-stripe-like-webhooks)）则更新订单并派发 `order.shipped`。`tenant` 是下单的合作方，因此只有该合作方的端点会收到：

```typescript
@@filename(orders/orders.service)
@Injectable()
export class OrdersService {
  constructor(
    @InjectDrizzle() private readonly db: Database,
    private readonly webhooks: Webhooks<Transaction>,
  ) {}

  // ...

  /** Cancels an order that hasn't shipped, and tells the partner in the same transaction. */
  async cancelOrder(partner: Partner, id: string, reason: string): Promise<Order> {
    const order = await this.db.transaction(async (tx) => {
      const [row] = await tx
        .select()
        .from(orders)
        .where(and(eq(orders.id, id), eq(orders.partnerId, partner.id)))
        .for('update');
      if (!row) {
        throw new NotFoundException(`Order ${id} not found`);
      }
      if (row.status === 'shipped' || row.status === 'cancelled') {
        throw new ConflictException(`Order ${id} is ${row.status}`);
      }
      await tx.update(orders).set({ status: 'cancelled' }).where(eq(orders.id, id));

      // Drizzle's tx: the webhook is sent only if the cancellation commits, and only to the
      // partner's own endpoints (the tenant).
      const data: OrderCancelled = { orderId: id, reason };
      await this.webhooks.dispatch(tx, { type: 'order.cancelled', tenant: row.partnerId, data });
      return { ...row, status: 'cancelled' as const };
    });

    this.webhooks.notify(); // deliver now instead of at the next poll
    return order;
  }

  // ...

  /** The carrier picked the order up: marks it shipped and tells the partner, in one transaction (the carrier's webhook). */
  async markShipped(tx: Transaction, orderId: string, trackingNumber: string): Promise<Order> {
    const [row] = await tx.select().from(orders).where(eq(orders.id, orderId)).for('update');
    if (!row) {
      throw new NotFoundException(`Order ${orderId} not found`);
    }
    if (row.status !== 'paid') {
      throw new ConflictException(`Order ${orderId} is ${row.status}, not paid`);
    }
    await tx.update(orders).set({ status: 'shipped', trackingNumber }).where(eq(orders.id, orderId));

    const data: OrderShipped = { orderId, trackingNumber };
    await this.webhooks.dispatch(tx, { type: 'order.shipped', tenant: row.partnerId, data });
    return { ...row, status: 'shipped', trackingNumber };
  }
}
```

事务之内没有任何东西离开进程。若它回滚，消息从未存在过。若它提交，outbox 的 relay 会取走该消息（`notify()` 让它立刻处理而不是等下一次轮询）并交给该包的扇出，扇出为订阅了该类型的租户下每个已启用端点创建一条投递。随后 worker 逐条签名并发送。下面是 Northside 的服务器在每次投递尝试中收到的内容，`webhook-id` 相同，请求体与 `dispatch()` 时序列化的完全一致：

```http
POST /store/webhooks HTTP/1.1
content-type: application/json
user-agent: NestJS-Webhooks/1.0
webhook-id: msg_01a0f33b898e7341950339801ec3319a
webhook-timestamp: 1790787160
webhook-signature: v1,<base64 HMAC-SHA256 of "msg_01a0f33b898e7341950339801ec3319a.1790787160.{the body}">

{"type":"order.shipped","timestamp":"2026-09-30T16:52:40.462Z","data":{"orderId":"1067d04c-0617-44ac-9a29-67297867329e","trackingNumber":"TRK-4471-0001"}}
```

签名以端点的密钥为密钥，因此合作方可以用任何 Standard Webhooks 库校验它。或者用这个包：Northside 的接收端是一个独立的 Nest 应用，有自己的根模块，只接收，设置 `outgoing: false`，并在路由上加 `@VerifyWebhook('store')`。`STORE_WEBHOOK_SECRET` 接受逗号分隔的列表，因为店铺的[轮换](/http/webhooks#rotate-secrets)会在一天内用两个密钥签名：

```typescript
@@filename(partner-service/app.module)
import { Module } from '@nestjs/common';
import { OutboxModule } from '@nestjs/outbox';
import { WebhooksModule } from '@nestjs/webhooks';
import { StoreWebhooksController } from './store-webhooks.controller.js';

/**
 * Northside's side: a service that only receives. `outgoing: false` leaves out the
 * endpoints, deliveries and worker. The outbox's inbox deduplicates redeliveries by
 * webhook-id; in memory here, on the partner's own database in production (the outbox's
 * store, as in the outbox tutorial's analytics service).
 */
@Module({
  imports: [
    OutboxModule.forRoot({ relay: { enabled: false } }),
    WebhooksModule.forRootAsync({
      outgoing: false,
      useFactory: () => {
        const secrets = process.env.STORE_WEBHOOK_SECRET;
        if (!secrets) {
          throw new Error('Set STORE_WEBHOOK_SECRET to the secret the store gave this endpoint');
        }
        return {
          receivers: {
            // Every listed secret is tried: keep the old one next to the new one while the store rotates.
            store: { scheme: 'standard', secret: secrets.split(',') },
          },
        };
      },
    }),
  ],
  controllers: [StoreWebhooksController],
})
export class AppModule {}
```

```typescript
@@filename(partner-service/store-webhooks.controller)
import { Controller, HttpCode, HttpStatus, Logger, Post } from '@nestjs/common';
import { IncomingWebhook, VerifyWebhook } from '@nestjs/webhooks';

/** What the store sends: the Standard Webhooks payload, `type`, `timestamp` and `data`. */
export type StoreEvent =
  | { type: 'order.shipped'; timestamp: string; data: { orderId: string; trackingNumber: string } }
  | { type: 'order.cancelled'; timestamp: string; data: { orderId: string; reason: string } };

@Controller('store')
export class StoreWebhooksController {
  private readonly logger = new Logger(StoreWebhooksController.name);

  @Post('webhooks')
  @HttpCode(HttpStatus.NO_CONTENT)
  @VerifyWebhook('store')
  receive(@IncomingWebhook() webhook: IncomingWebhook<StoreEvent>) {
    const event = webhook.payload;
    if (event.type === 'order.shipped') {
      this.logger.log(`Order ${event.data.orderId} shipped, tracking ${event.data.trackingNumber} (${webhook.id})`);
    } else {
      this.logger.log(`Order ${event.data.orderId} cancelled: ${event.data.reason} (${webhook.id})`);
    }
  }
}
```

```typescript
@@filename(partner-service/main)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';

async function bootstrap() {
  // rawBody: the signature is checked on the bytes the store signed, not on a re-serialized body.
  const app = await NestFactory.create(AppModule, { rawBody: true });
  app.enableShutdownHooks();
  await app.listen(process.env.PORT ?? 4100);
}
await bootstrap();
```

合作方的 `OutboxModule` 提供 `@VerifyWebhook()` 用来去重的 inbox。这里它运行在内存中；真实合作方会在自己的数据库上注册 outbox 的存储，在 PostgreSQL 上即 `PostgresOutboxStore`，如 [outbox 教程](/reliability/outbox#publish-to-the-analytics-microservice)中的分析服务所做。

#### 重试、投递日志与重放

合作方返回 2xx 即为成功。其他都算失败的尝试：5xx、4xx、3xx（从不跟随重定向）、超时、连接被拒。worker 在退避之后重试，并尊重以秒或 HTTP 日期形式给出的 `Retry-After` 头（最多到退避上限，即一天；其他值被忽略）；遇到 429、502、503 或 504 时，会把该端点暂停到那时，没有头则暂停五秒：该端点的其他投递会等待而不尝试，因此请求喘息的合作方只会收到一次探测而不是每批一次，同时其他合作方的投递照常进行。三种应答会提前结束一条投递：410 Gone（同时禁用该端点，原因 `gone`）、传输层拒绝的目的地（订阅时的检查在每次发送时都会重跑，因为 DNS 会变），以及 `retry.retryIf` 说不。最后一次尝试之后，投递状态为 `failed`，原因 `exhausted`。

若端点连续失败达 `disableEndpointAfter`，会被禁用，原因 `failing`，`WebhooksEvents` 会发出 `endpoint-disabled`：去通知合作方。任何时刻的一次成功都会重置计时。被禁用的端点（无论由 worker 还是由合作方通过订阅 `update()` 的 `enabled: false` 禁用），在禁用期间派发的任何内容都不会得到投递：扇出会跳过它，之后也不会有任何东西创建这些投递。重放也不会，因为重放的是已存在的投递。确实存在的是端点被禁用时仍在等待的那些投递：轮到它们时会以原因 `endpoint-disabled` 失败，重新启用后合作方可以按失败投递再次申请。重新启用会忘记失败记录，此后派发的内容正常接收。

每次尝试都会被记录：状态码、耗时、响应体前 4 KB、错误。合作方读取自己的日志，并可要求重新发送某条投递，或自某次故障以来所有失败的投递。批量重试接受一个端点与故障起始时间，两者都可选：

```typescript
@@filename(partner-webhooks/webhook-deliveries.dto)
import { IsISO8601, IsOptional, IsString } from 'class-validator';

/** Body of `POST /partner/webhook-deliveries/retry`: every failed delivery since an outage began. */
export class RetryDeliveriesDto {
  /** One endpoint's, or every endpoint's. */
  @IsOptional()
  @IsString()
  endpointId?: string;

  /** Deliveries created at or after this time (ISO 8601): the start of the outage. */
  @IsOptional()
  @IsISO8601()
  since?: string;
}
```

```typescript
@@filename(partner-webhooks/webhook-deliveries.schemas)
import { z } from 'zod';

/** Body of `POST /partner/webhook-deliveries/retry`: every failed delivery since an outage began. */
export const retryDeliveriesSchema = z.object({
  /** One endpoint's, or every endpoint's. */
  endpointId: z.string().optional(),
  /** Deliveries created at or after this time (ISO 8601): the start of the outage. */
  since: z.iso.datetime().optional(),
});
export type RetryDeliveriesDto = z.infer<typeof retryDeliveriesSchema>;
```

```typescript
@@filename(partner-webhooks/webhook-deliveries.controller)
import {
  Body,
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  NotFoundException,
  Param,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import { WebhookDeliveries, type WebhookDeliveryStatus } from '@nestjs/webhooks';
import { CurrentPartner, PartnerGuard, type Partner } from '../partners/partner.guard.js';
import { RetryDeliveriesDto } from './webhook-deliveries.dto.js';

/** A partner's delivery log: what was sent, how each attempt went, and a way to ask for it again. */
@Controller('partner/webhook-deliveries')
@UseGuards(PartnerGuard)
export class WebhookDeliveriesController {
  constructor(private readonly webhookDeliveries: WebhookDeliveries) {}

  /** Newest first. */
  @Get()
  list(
    @CurrentPartner() partner: Partner,
    @Query('endpointId') endpointId?: string,
    @Query('status') status?: WebhookDeliveryStatus,
    @Query('type') type?: string,
  ) {
    return this.webhookDeliveries.list({ tenant: partner.id, endpointId, status, type });
  }

  /** The delivery, the message that was sent, and every attempt: status code, duration, the start of the response. */
  @Get(':id')
  async get(@CurrentPartner() partner: Partner, @Param('id') id: string) {
    const delivery = await this.webhookDeliveries.get(id, { tenant: partner.id });
    if (!delivery) {
      throw new NotFoundException(`Webhook delivery ${id} not found`);
    }
    return delivery;
  }

  /** Sends one delivery again, now, with the same webhook-id: a replay of a lost webhook, or a retry of a failed one. */
  @Post(':id/retry')
  @HttpCode(HttpStatus.OK)
  async retry(@CurrentPartner() partner: Partner, @Param('id') id: string) {
    return { retried: await this.webhookDeliveries.retry(id, { tenant: partner.id }) };
  }

  /** Retries every failed delivery, of one endpoint or all, since an outage began. */
  @Post('retry')
  @HttpCode(HttpStatus.OK)
  async retryFailed(@CurrentPartner() partner: Partner, @Body() dto: RetryDeliveriesDto) {
    const since = dto.since === undefined ? undefined : new Date(dto.since);
    const retried = await this.webhookDeliveries.retry(
      { endpointId: dto.endpointId, status: 'failed', since },
      { tenant: partner.id },
    );
    return { retried };
  }
}
```

使用 Zod schema 时：

```typescript
@@filename(partner-webhooks/webhook-deliveries.controller)
import { retryDeliveriesSchema, type RetryDeliveriesDto } from './webhook-deliveries.schemas.js';
// ...
@Post('retry')
@HttpCode(HttpStatus.OK)
async retryFailed(@CurrentPartner() partner: Partner, @Body({ schema: retryDeliveriesSchema }) dto: RetryDeliveriesDto) {
  // ...
}
```

一次重试开启新一轮：`attempts` 归零，立刻发送，`webhook-id` 与请求体都不变。之前几轮的日志保留。由于 id 相同，inbox 保留了该 id 的合作方会直接回 2xx 而不运行处理器，因此重放对已投递的 webhook 也是安全的：Northside 在丢掉自己的数据库后可以要求重发最近一小时的内容，只会拿到它尚未处理的部分。

运维人员可以通过 `WebhookDeliveries` 在不带租户的情况下做同样的事：`stats()`（pending、due、leased、failed 计数，以及 `lagMs`——最超期的那条投递已经等了多久，这是你该设告警的数字）、跨租户的 `retry()`，以及 `prune('30d')`（没有人会替你调用它）。`WebhooksEvents.events$` 发出 `delivered`、`retry-scheduled`、`delivery-failed`、`endpoint-disabled` 和 `destination-blocked`，每个事件同时发到名为 `nestjs:webhooks:<event>` 的 `node:diagnostics_channel` 通道上。

#### 接收支付服务商的 webhook

支付服务商用 Standard Webhooks 请求告知店铺某笔支付已成功。校验它需要与提供方签名时完全一致的请求体，因此应用以 `rawBody: true` 创建。这在 Express 和 Fastify 上都有效：

```typescript
@@filename(main)
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';

async function bootstrap() {
  // rawBody: incoming webhooks are verified on the bytes that were signed, not on a re-serialized body.
  const app = await NestFactory.create(AppModule, { rawBody: true });
  // The partner API's DTOs; whitelist: properties without a decorator are dropped.
  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
  // On SIGTERM the outbox relay and the webhook worker finish what they started.
  app.enableShutdownHooks();
  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();
```

发送方按路由将使用的名称放进模块的 `receivers`。支付服务商的密钥就是它在自己面板中显示的那个：

```typescript
@@filename(app.module)
// The senders whose webhooks this API accepts, by the name @VerifyWebhook() uses.
receivers: {
  // The payment provider follows Standard Webhooks: webhook-id, webhook-timestamp, webhook-signature.
  payments: { scheme: 'standard', secret: process.env.PAYMENTS_WEBHOOK_SECRET! },
  // The carrier copied Stripe's scheme under its own header: Carrier-Signature: t=...,v1=...
  carrier: { scheme: 'stripe', header: 'Carrier-Signature', secret: process.env.CARRIER_WEBHOOK_SECRET! },
},
```

路由上的 `@VerifyWebhook('payments')` 会在处理器运行之前校验请求，`@IncomingWebhook()` 提供校验结果：该 webhook 的发送方 `id`、被签名的 `timestamp`、从被签名字节解析出的 `payload`，以及 `processInTransaction()`：

```typescript
@@filename(provider-webhooks/payment-provider-webhooks.controller)
import { Controller, HttpCode, HttpStatus, Logger, Post } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { IncomingWebhook, VerifyWebhook } from '@nestjs/webhooks';
import type { Database } from '../database/drizzle.js';
import { OrdersService } from '../orders/orders.service.js';

/** The payment provider's payload: the Standard Webhooks shape, `type`, `timestamp` and `data`. */
export interface PaymentProviderEvent {
  type: 'payment.succeeded' | 'payment.failed';
  timestamp: string;
  data: { paymentId: string; orderId: string; amount: number };
}

@Controller('webhooks/payments')
export class PaymentProviderWebhooksController {
  private readonly logger = new Logger(PaymentProviderWebhooksController.name);

  constructor(
    @InjectDrizzle() private readonly db: Database,
    private readonly ordersService: OrdersService,
  ) {}

  @Post()
  @HttpCode(HttpStatus.OK)
  @VerifyWebhook('payments')
  async receive(@IncomingWebhook() webhook: IncomingWebhook<PaymentProviderEvent>) {
    const { type, data } = webhook.payload;
    if (type !== 'payment.succeeded') {
      this.logger.log(`Ignoring ${type} for order ${data.orderId}`);
      return;
    }
    // Exactly once: the webhook's id is recorded in the same transaction as the order's new
    // status, so a redelivery, even one racing this request on another instance, changes nothing.
    const result = await this.db.transaction(async (tx) =>
      webhook.processInTransaction(tx, () => this.ordersService.markPaid(tx, data.orderId, data.paymentId, data.amount)),
    );
    if (!result.duplicate) {
      this.logger.log(`Order ${data.orderId} paid: ${data.paymentId}, ${data.amount} cents`);
    }
  }
}
```

```typescript
@@filename(orders/orders.service)
/** The payment provider confirmed the payment. Runs inside the receiver's transaction. */
async markPaid(tx: Transaction, orderId: string, paymentId: string, amount: number): Promise<Order> {
  const [row] = await tx.select().from(orders).where(eq(orders.id, orderId)).for('update');
  if (!row) {
    throw new NotFoundException(`Order ${orderId} not found`);
  }
  if (row.status !== 'placed') {
    throw new ConflictException(`Order ${orderId} is ${row.status}`);
  }
  if (amount !== row.total) {
    throw new ConflictException(`Payment ${paymentId} is for ${amount}, and order ${orderId} totals ${row.total}`);
  }
  await tx.update(orders).set({ status: 'paid', paymentId }).where(eq(orders.id, orderId));
  return { ...row, status: 'paid', paymentId };
}
```

```typescript
@@filename(provider-webhooks/provider-webhooks.module)
import { Module } from '@nestjs/common';
import { OrdersModule } from '../orders/orders.module.js';
import { CarrierWebhooksController } from './carrier-webhooks.controller.js';
import { PaymentProviderWebhooksController } from './payment-provider-webhooks.controller.js';

/** The webhooks the store receives: the payment provider's payments and the carrier's shipments. */
@Module({
  imports: [OrdersModule],
  controllers: [PaymentProviderWebhooksController, CarrierWebhooksController],
})
export class ProviderWebhooksModule {}
```

该装饰器按顺序检查：三个 `webhook-` 头存在且格式正确，`webhook-id` 不超过 255 个字符（按码点计）；`webhook-signature` 中有一个 `v1,` 签名与 `id.timestamp.body` 用某个已配置密钥计算的 HMAC 匹配（常量时间比较；支付服务商轮换期间可以列出多个密钥）；被签名的 timestamp 与当前时间相差不超过 5 分钟（前后皆可）；请求体是 JSON。失败时返回 401 和一条通用消息。原因从不发给发送方，而是进入 `verification-failed` 事件，附带接收方名称。被签名但不是 JSON 的请求体会在装饰器看到它之前被框架的请求体解析器以 400 拒绝，因此不会发出事件。超过请求体解析器大小限制的请求体同样如此（Express 默认 100 kB，Fastify 默认 1 MiB）：在装饰器运行之前就得到 413，也不会发出事件。如果支付服务商发送更大的请求体，请用 `useBodyParser()` 提高限制，见[原始请求体](/faq/raw-body#body-parser-size-limit)。

接下来是去重。支付服务商会一直重试直到收到 2xx，因此处理器成功之后的超时会让它再次发送相同的 `webhook-id`。接收方维护一个已处理 id 的 inbox（outbox 的 inbox，消费者名 `webhooks:payments`）：已知 id 会直接得到空 200 而不运行处理器；id 只在处理器成功之后才被记录，因此抛错的处理器会在支付服务商重试时再跑一次。同时到达同一实例的两份副本只会运行一次；两个实例同时收到则可能都运行，这正是下一段要解决的。

`markPaid()` 改动与钱有关的状态，因此控制器用 `processInTransaction()` 更进一步：webhook 的 id *通过订单的事务*记录，`markPaid()` 只在它是新的时候运行。记录与新状态一起提交。处理器与 inbox 写入之间崩溃后的重投，或在另一个实例上与本请求竞争的副本，都会发现该 id 并什么都不改；它以 `duplicate` 为真解析，控制器据此只记录一次日志。而当 `markPaid()` 抛错时（例如金额不对），事务回滚，记录随之回滚，发送方收到 409，其重试在订单修正后再获得一次机会。

开发时，可以用一个小脚本按支付服务商（以及下一节的承运商）的方式签名发请求，使用 `@nestjs/webhooks/testing` 的 `signWebhook()`：

```typescript
@@filename(scripts/send-webhook)
/**
 * Sends the signed request the payment provider or the carrier would send, for trying the API by hand:
 *
 *   npx tsx scripts/send-webhook.ts payments payment.succeeded '{"paymentId":"pay_1","orderId":"...","amount":4998}'
 *   npx tsx scripts/send-webhook.ts carrier shipment.shipped '{"orderId":"...","trackingNumber":"TRK-0001"}'
 *
 * Signs with PAYMENTS_WEBHOOK_SECRET or CARRIER_WEBHOOK_SECRET, the secrets the API was
 * started with, and posts to API_URL (default http://localhost:3000). WEBHOOK_ID sends a
 * redelivery with a given id; TAMPER=1 changes a byte of the body after signing it.
 */
import { signWebhook } from '@nestjs/webhooks/testing';
import { randomUUID } from 'node:crypto';

const [sender, type, json = '{}'] = process.argv.slice(2);
if (sender !== 'payments' && sender !== 'carrier') {
  console.error('usage: send-webhook.ts <payments|carrier> <type> <data as JSON>');
  process.exit(2);
}
const data: unknown = JSON.parse(json);
const id = process.env.WEBHOOK_ID;

function secret(name: string): string {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Set ${name}`);
  }
  return value;
}

const signed =
  sender === 'payments'
    ? signWebhook({
        scheme: 'standard',
        secret: secret('PAYMENTS_WEBHOOK_SECRET'),
        id,
        payload: { type, timestamp: new Date().toISOString(), data },
      })
    : signWebhook({
        scheme: 'stripe',
        header: 'Carrier-Signature',
        secret: secret('CARRIER_WEBHOOK_SECRET'),
        payload: { id: id ?? `evt_${randomUUID().replaceAll('-', '')}`, type, data },
      });

const body = process.env.TAMPER ? `${signed.body.slice(0, -1)} }` : signed.body;
const response = await fetch(`${process.env.API_URL ?? 'http://localhost:3000'}/webhooks/${sender}`, {
  method: 'POST',
  headers: signed.headers,
  body,
});
console.log(`${response.status} ${await response.text()}`);
```

#### 接收承运商类 Stripe 的 webhook

承运商照搬了 Stripe 的方案：`Carrier-Signature: t=…,v1=…` 头，以密钥文本为密钥、对 `t.body` 计算的十六进制 HMAC-SHA256，事件 id 在负载里。[`receivers` 选项](/http/webhooks#receive-the-payment-providers-webhooks)中的接收方据此声明：`scheme: 'stripe'` 并指定 `header` 名。Stripe 自己的 webhook 就是同一个接收方，只是不带 `header`。GitHub 的、以及有自己方案的发送方，见[其他发送方](/http/webhooks#other-senders)。

处理器才是有意思的部分。标记订单已发货与通知合作方在同一个事务中完成：订单的新状态、合作方的 `order.shipped` 消息（经 outbox）以及该 webhook 的 inbox 记录一起提交，或者都不提交：

```typescript
@@filename(provider-webhooks/carrier-webhooks.controller)
import { Controller, HttpCode, HttpStatus, Logger, Post } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { IncomingWebhook, VerifyWebhook, Webhooks } from '@nestjs/webhooks';
import type { Database } from '../database/drizzle.js';
import { OrdersService } from '../orders/orders.service.js';

/** The carrier's payload, Stripe-like: the event's `id` is in the body, which is what the signature covers. */
export interface CarrierEvent {
  id: string;
  type: 'shipment.shipped' | 'shipment.delivered';
  data: { orderId: string; trackingNumber: string };
}

@Controller('webhooks/carrier')
export class CarrierWebhooksController {
  private readonly logger = new Logger(CarrierWebhooksController.name);

  constructor(
    @InjectDrizzle() private readonly db: Database,
    private readonly ordersService: OrdersService,
    private readonly webhooks: Webhooks,
  ) {}

  @Post()
  @HttpCode(HttpStatus.OK)
  @VerifyWebhook('carrier')
  async receive(@IncomingWebhook() webhook: IncomingWebhook<CarrierEvent>) {
    const { type, data } = webhook.payload;
    if (type !== 'shipment.shipped') {
      this.logger.log(`Ignoring ${type} for order ${data.orderId}`);
      return;
    }
    // One transaction: the order's status, the partner's order.shipped webhook (through the
    // outbox) and this webhook's inbox record commit together, or not at all.
    const result = await this.db.transaction(async (tx) =>
      webhook.processInTransaction(tx, () => this.ordersService.markShipped(tx, data.orderId, data.trackingNumber)),
    );
    if (result.duplicate) {
      return;
    }
    this.webhooks.notify(); // deliver order.shipped now instead of at the next poll
    this.logger.log(`Order ${data.orderId} shipped, tracking ${data.trackingNumber}`);
  }
}
```

`markShipped()` 就是[在提交后发送 order.shipped 与 order.cancelled](/http/webhooks#send-ordershipped-and-ordercancelled-after-the-commit)中的那个方法。去重 id 来自被签名负载中的事件 `id`，而不是某个头，因为那才是 Stripe 方案签名的内容。订单尚未支付时的 `shipment.shipped` 事件会以 409 被拒绝，且不记录任何东西：承运商在支付到达后重试时，同一个事件 id 会被处理。

#### 其他发送方

GitHub 的 webhook 使用 `scheme: 'github'`：`X-Hub-Signature-256`，以密钥文本为密钥、对请求体计算的十六进制 HMAC-SHA256。请把钩子的 **Content type** 在 GitHub 中设为 `application/json`：它的默认值 `application/x-www-form-urlencoded` 会把负载作为表单字段发送，接收方会以 400 回应每一次投递，因为请求体不是 JSON。

> warning **警告** GitHub 既不签时间戳也不签 id。被截获的请求可以永久通过校验，而去重默认以 `X-GitHub-Delivery` 头为键，该头并未被签名：同一个请求换一个该头的值重放，处理器会再跑一次。

改为用接收方的 `id` 选项以被签名的请求体为键去重。负载从被签名的字节解析，因此重放与原请求 id 相同，inbox 会跳过它：

```typescript
receivers: {
  github: {
    scheme: 'github',
    secret: process.env.GITHUB_WEBHOOK_SECRET!,
    // The signed body, not the unsigned X-GitHub-Delivery header: a replayed request has a known id.
    id: (payload) => createHash('sha256').update(JSON.stringify(payload)).digest('hex'),
  },
},
```

inbox 会一直记住 id 直到 `OutboxInbox.prune()` 删除它，因此对 GitHub 而言，这个窗口也就是重放能被抓住的时间：请设得长一些。超过之后重放的请求会通过校验并运行；只接受 GitHub 公布地址（`https://api.github.com/meta` 中的 `hooks`）的 webhook 可以缩小谁有权发送的范围。

有自己方案的发送方，就是继承 `WebhookSignatureScheme` 的类。假设这家店还通过一个市场销售，该市场对它 POST 到的 URL 加上请求体签名，并把事件 id 放在请求体里：

```typescript
@@filename(provider-webhooks/marketplace.scheme)
import { WebhookSignatureScheme, type WebhookSignatureCheck, type WebhookSignedRequest } from '@nestjs/webhooks';
import { createHmac } from 'node:crypto';

/**
 * The marketplace's scheme: `X-Marketplace-Signature` is the base64 HMAC-SHA256 of the URL it
 * posts to followed by the body, keyed with the secret's text, and the event's id is in the body.
 * A scheme sees the request's headers and raw body, so the URL comes in through the constructor:
 * the one registered in the marketplace's dashboard.
 */
export class MarketplaceScheme extends WebhookSignatureScheme {
  constructor(private readonly url: string) {
    super();
  }

  verify({ headers, rawBody }: WebhookSignedRequest, keys: readonly Buffer[]): WebhookSignatureCheck {
    const signature = headers['x-marketplace-signature'];
    if (signature === undefined) {
      return { valid: false, reason: 'missing-header', detail: 'no x-marketplace-signature header' };
    }
    if (typeof signature !== 'string') {
      return { valid: false, reason: 'malformed-header', detail: 'x-marketplace-signature is repeated' };
    }

    const candidates = [Buffer.from(signature, 'base64')];
    for (const key of keys) {
      const expected = createHmac('sha256', key).update(this.url).update(rawBody).digest();
      // In constant time, never with ===.
      if (WebhookSignatureScheme.matches(expected, candidates)) {
        return { valid: true };
      }
    }
    return { valid: false, reason: 'invalid-signature', detail: 'no signature matches a configured secret' };
  }

  /** The deduplication id: the event's, from the signed body. */
  override idFromPayload(payload: unknown): string | undefined {
    const id = (payload as { eventId?: unknown } | null)?.eventId;
    return typeof id === 'string' ? id : undefined;
  }
}
```

- `verify(request, keys)` 拿到请求的 `headers`（小写名称）与其 `rawBody`（按收到的原样），以及每个已配置密钥对应的一把密钥。匹配时返回 `valid: true`，若某个头携带了发送方的 `id` 则一并给出；若方案签了时间戳，则给出以纪元秒计的被签名 `timestamp`（此时接收方的 `tolerance` 生效）。失败时返回 `valid: false`，并给出用于 `verification-failed` 事件的 `reason` 与一段 `detail`。它同步运行，早于请求体被解析为 JSON。
- `WebhookSignatureScheme.matches(expected, candidates)` 以常量时间比较。绝不要用 `===` 比较签名。
- `idFromPayload(payload, headers)` 在没有头携带 id 时，从解析后的请求体给出用于去重的 id，正如内置的 Stripe 方案对事件 `id` 所做。来自任一途径的 id 若超过 255 个字符，会以 `malformed-header` 被拒绝。
- `key(secret)` 在启动时把每个已配置密钥一次性转换为 `verify()` 收到的密钥，格式错误的密钥会在那里中止应用。默认实现取密钥文本，并拒绝空值或首尾带空白的值。对编码过的密钥请重写它，正如 `standard` 方案对 `whsec_…` 所做。

接收方接受一个实例：

```typescript
receivers: {
  marketplace: {
    scheme: new MarketplaceScheme('https://api.store.example.com/webhooks/marketplace'),
    secret: process.env.MARKETPLACE_WEBHOOK_SECRET!,
  },
},
```

#### 轮换密钥

密钥泄露了，或者合作方的政策规定一年一换。`POST /partner/webhook-endpoints/:id/rotate-secret`（见[让合作方订阅](/http/webhooks#let-partners-subscribe)）返回新密钥，旧密钥在 `secretRotationOverlap`（24 小时）内继续并行签名：每条投递携带两个 `v1,` 签名，Standard Webhooks 校验器接受其中任一匹配的。合作方把新密钥加入自己的列表、部署、按自己的节奏移除旧密钥。重叠期之后只有新密钥签名。`rotateSecret()` 传 `overlap: 0` 会立即废弃旧密钥，适用于密钥已泄露的情况。

设置 `WEBHOOKS_ENCRYPTION_KEYS` 可将密钥静态加密，每个密钥用 `openssl rand -base64 32` 生成，最新的在前。此前创建的端点仍可读取（其密钥是明文），并会在下次轮换时加密。

#### 动手试试

创建数据库，并对它应用你的迁移，这会创建[安装](/http/webhooks#installation)中订单 API 的表与数据：

```bash
$ psql postgres://localhost:5432/postgres -c 'CREATE DATABASE store'
```

导出支付服务商与承运商同店铺共享的密钥（此处为虚构），允许向本机投递，并在 3000 端口启动 API：

```bash
$ export PAYMENTS_WEBHOOK_SECRET=whsec_$(openssl rand -base64 32)
$ export CARRIER_WEBHOOK_SECRET=carrier_test_$(openssl rand -hex 6)
$ export WEBHOOKS_ALLOW_LOCAL=1
```

```bash
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [OutboxModule] OutboxStorage: PostgresOutboxStore
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [WebhooksModule] WebhooksStorage: PostgresWebhookStore
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [OutboxModule] PostgresOutboxStore: migrated schema "nest_outbox" to version 1.
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [WebhooksModule] PostgresWebhookStore: migrated schema "nest_webhooks" to version 1.
[Nest] 55905  - 09/30/2026, 6:52:36 PM     LOG [NestApplication] Nest application successfully started +2ms
```

你的迁移创建了订单 API 的表，存储在其旁创建了自己的 schema。Northside 用它的 API key 订阅两个事件，接收端将运行在 4100 端口。响应中携带密钥，仅此一次：

```bash
$ curl -s -X POST localhost:3000/partner/webhook-endpoints \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"url":"http://127.0.0.1:4100/store/webhooks","eventTypes":["order.shipped","order.cancelled"],"description":"Warehouse system"}'
{"id":"ep_01a0f33b79e27154b8fd089a10f3e48e","tenant":"northside","url":"http://127.0.0.1:4100/store/webhooks","eventTypes":["order.shipped","order.cancelled"],"description":"Warehouse system","enabled":true,"disabledReason":null,"failingSince":null,"createdAt":1790787156450,"updatedAt":1790787156450,"secret":"whsec_yKaIEKkc0ZpOWofM8Fx1Wc5yxdffKSsP1jolLCynqug="}
$ curl -s localhost:3000/partner/webhook-endpoints -H 'Authorization: Bearer partner_northside_7c1d2e'
[{"id":"ep_01a0f33b79e27154b8fd089a10f3e48e","tenant":"northside","url":"http://127.0.0.1:4100/store/webhooks","eventTypes":["order.shipped","order.cancelled"],"description":"Warehouse system","enabled":true,"disabledReason":null,"failingSince":null,"createdAt":1790787156450,"updatedAt":1790787156450}]
```

> info **提示** `--json` 需要 curl 7.82 或更高版本。

云元数据服务的 URL 会在任何内容被保存之前被拒绝，API 不发送的事件类型同样如此。另一个合作方 Riverside Cat Shelter 访问 Northside 的端点会得到 404：

```bash
$ curl -s -X POST localhost:3000/partner/webhook-endpoints \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"url":"https://169.254.169.254/latest/meta-data/","eventTypes":["*"]}'
{"statusCode":400,"message":"Invalid webhook URL: 169.254.169.254 is link-local (cloud metadata)"}
$ curl -s -X POST localhost:3000/partner/webhook-endpoints \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"url":"https://hooks.northside.example.com/store","eventTypes":["order.paid"]}'
{"statusCode":400,"message":"Unknown message type \"order.paid\". Known: order.shipped, order.cancelled"}
$ curl -s -o /dev/null -w '%{http_code}' localhost:3000/partner/webhook-endpoints/ep_01a0f33b79e27154b8fd089a10f3e48e \
    -H 'Authorization: Bearer partner_riverside_91ab44'
404
```

在 4100 端口启动 Northside 的接收端 `partner-service/main.ts`，并在其环境中放入它拿到的密钥：

```bash
STORE_WEBHOOK_SECRET=whsec_yKaIEKkc0ZpOWofM8Fx1Wc5yxdffKSsP1jolLCynqug=
```

现在下单，让支付服务商付款、承运商发货。脚本用上面导出的密钥为它们将要发送的请求签名：

```bash
$ curl -s -X POST localhost:3000/orders \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"items":[{"productId":"salmon-kibble-2kg","quantity":2}]}'
{"id":"1067d04c-0617-44ac-9a29-67297867329e","partnerId":"northside","items":[{"productId":"salmon-kibble-2kg","quantity":2,"price":2499}],"total":4998,"status":"placed","paymentId":null,"trackingNumber":null}
$ npx tsx scripts/send-webhook.ts payments payment.succeeded \
    '{"paymentId":"pay_8f21c","orderId":"1067d04c-0617-44ac-9a29-67297867329e","amount":4998}'
200
$ npx tsx scripts/send-webhook.ts carrier shipment.shipped \
    '{"orderId":"1067d04c-0617-44ac-9a29-67297867329e","trackingNumber":"TRK-4471-0001"}'
200
$ curl -s localhost:3000/orders/1067d04c-0617-44ac-9a29-67297867329e -H 'Authorization: Bearer partner_northside_7c1d2e'
{"id":"1067d04c-0617-44ac-9a29-67297867329e","partnerId":"northside","items":[{"price":2499,"quantity":2,"productId":"salmon-kibble-2kg"}],"total":4998,"status":"shipped","paymentId":"pay_8f21c","trackingNumber":"TRK-4471-0001"}
```

API 的日志显示两个 webhook 都被处理，Northside 的日志显示 `order.shipped` 紧接在承运商的之后到达，并带上其 `webhook-id`：

```bash
[Nest] 55905  - 09/30/2026, 6:52:39 PM     LOG [PaymentProviderWebhooksController] Order 1067d04c-0617-44ac-9a29-67297867329e paid: pay_8f21c, 4998 cents
[Nest] 55905  - 09/30/2026, 6:52:40 PM     LOG [CarrierWebhooksController] Order 1067d04c-0617-44ac-9a29-67297867329e shipped, tracking TRK-4471-0001
```

```bash
[Nest] 56040  - 09/30/2026, 6:52:40 PM     LOG [StoreWebhooksController] Order 1067d04c-0617-44ac-9a29-67297867329e shipped, tracking TRK-4471-0001 (msg_01a0f33b898e7341950339801ec3319a)
```

Northside 的投递日志里有这条投递，其详情包含消息与那一次尝试，以及合作方返回的状态码和耗时：

```bash
$ curl -s localhost:3000/partner/webhook-deliveries -H 'Authorization: Bearer partner_northside_7c1d2e'
[{"id":"dlv_01a0f33b89ac720aa76e2c3da97f3c14","messageId":"msg_01a0f33b898e7341950339801ec3319a","endpointId":"ep_01a0f33b79e27154b8fd089a10f3e48e","tenant":"northside","type":"order.shipped","status":"succeeded","attempts":1,"nextAttemptAt":null,"lastAttemptAt":1790787160533,"lastStatusCode":204,"lastError":null,"failureReason":null,"createdAt":1790787160462,"completedAt":1790787160544}]
$ curl -s localhost:3000/partner/webhook-deliveries/dlv_01a0f33b89ac720aa76e2c3da97f3c14 -H 'Authorization: Bearer partner_northside_7c1d2e'
```

```json
{
  "id": "dlv_01a0f33b89ac720aa76e2c3da97f3c14",
  "messageId": "msg_01a0f33b898e7341950339801ec3319a",
  "endpointId": "ep_01a0f33b79e27154b8fd089a10f3e48e",
  "tenant": "northside",
  "type": "order.shipped",
  "status": "succeeded",
  "attempts": 1,
  "nextAttemptAt": null,
  "lastAttemptAt": 1790787160533,
  "lastStatusCode": 204,
  "lastError": null,
  "failureReason": null,
  "createdAt": 1790787160462,
  "completedAt": 1790787160544,
  "message": {
    "id": "msg_01a0f33b898e7341950339801ec3319a",
    "type": "order.shipped",
    "tenant": "northside",
    "body": "{\"type\":\"order.shipped\",\"timestamp\":\"2026-09-30T16:52:40.462Z\",\"data\":{\"orderId\":\"1067d04c-0617-44ac-9a29-67297867329e\",\"trackingNumber\":\"TRK-4471-0001\"}}",
    "createdAt": 1790787160462
  },
  "history": [
    { "deliveryId": "dlv_01a0f33b89ac720aa76e2c3da97f3c14", "attempt": 1, "at": 1790787160533, "durationMs": 11, "statusCode": 204, "response": "", "error": null }
  ]
}
```

用 `Ctrl+C` 停掉 Northside 的接收端，然后下单并取消。投递会连接失败，API 记录下次尝试前的等待时间，合作方的日志显示该投递处于 pending 及其错误：

```bash
$ curl -s -X POST localhost:3000/orders \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"items":[{"productId":"clumping-litter-10l","quantity":1}]}'
{"id":"d6a36832-6b83-40f6-960b-0c6aa905ae18","partnerId":"northside","items":[{"productId":"clumping-litter-10l","quantity":1,"price":1599}],"total":1599,"status":"placed","paymentId":null,"trackingNumber":null}
$ curl -s -X POST localhost:3000/orders/d6a36832-6b83-40f6-960b-0c6aa905ae18/cancel \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"reason":"out of stock"}'
{"id":"d6a36832-6b83-40f6-960b-0c6aa905ae18","partnerId":"northside","items":[{"price":1599,"quantity":1,"productId":"clumping-litter-10l"}],"total":1599,"status":"cancelled","paymentId":null,"trackingNumber":null}
$ curl -s 'localhost:3000/partner/webhook-deliveries?status=pending' -H 'Authorization: Bearer partner_northside_7c1d2e'
[{"id":"dlv_01a0f33b8f51724da606406a85418fab","messageId":"msg_01a0f33b8f367090b44d3de36eed8f13","endpointId":"ep_01a0f33b79e27154b8fd089a10f3e48e","tenant":"northside","type":"order.cancelled","status":"pending","attempts":1,"nextAttemptAt":1790787164580,"lastAttemptAt":1790787161969,"lastStatusCode":null,"lastError":"Error: connect ECONNREFUSED 127.0.0.1:4100","failureReason":null,"createdAt":1790787161910,"completedAt":null}]
```

```bash
[Nest] 55905  - 09/30/2026, 6:52:42 PM    WARN [WebhookWorker] Retrying webhook delivery dlv_01a0f33b8f51724da606406a85418fab (order.cancelled) in 2609ms (attempt 1 of 10 failed): Error: connect ECONNREFUSED 127.0.0.1:4100
```

再次启动接收端。重试通过，日志保留两次尝试：

```bash
[Nest] 56304  - 09/30/2026, 6:52:45 PM     LOG [StoreWebhooksController] Order d6a36832-6b83-40f6-960b-0c6aa905ae18 cancelled: out of stock (msg_01a0f33b8f367090b44d3de36eed8f13)
```

```bash
$ curl -s localhost:3000/partner/webhook-deliveries/dlv_01a0f33b8f51724da606406a85418fab -H 'Authorization: Bearer partner_northside_7c1d2e'
```

```json
{
  "id": "dlv_01a0f33b8f51724da606406a85418fab",
  "type": "order.cancelled",
  "status": "succeeded",
  "attempts": 2,
  "lastStatusCode": 204,
  "history": [
    { "attempt": 1, "at": 1790787161969, "durationMs": 2, "statusCode": null, "response": null, "error": "Error: connect ECONNREFUSED 127.0.0.1:4100" },
    { "attempt": 2, "at": 1790787165060, "durationMs": 11, "statusCode": 204, "response": "", "error": null }
  ]
}
```

Northside 再次申请这条投递。它以相同的 `webhook-id` 发送，接收方的 inbox 认出它并直接回 204 而不运行处理器（其日志中没有新增），投递日志显示新的一轮：

```bash
$ curl -s -X POST localhost:3000/partner/webhook-deliveries/dlv_01a0f33b8f51724da606406a85418fab/retry \
    -H 'Authorization: Bearer partner_northside_7c1d2e'
{"retried":1}
$ curl -s localhost:3000/partner/webhook-deliveries/dlv_01a0f33b8f51724da606406a85418fab -H 'Authorization: Bearer partner_northside_7c1d2e'
```

```json
{
  "status": "succeeded",
  "attempts": 1,
  "history": [
    { "attempt": 1, "at": 1790787161969, "statusCode": null, "error": "Error: connect ECONNREFUSED 127.0.0.1:4100" },
    { "attempt": 2, "at": 1790787165060, "statusCode": 204, "error": null },
    { "attempt": 1, "at": 1790787166185, "statusCode": 204, "error": null }
  ]
}
```

再看支付服务商这一侧。带有相同 `webhook-id` 的重投（200 丢了，于是服务商重试）会被应答但不会再次处理：API 只记录一次付款。被篡改的请求体和错误的密钥会被拒绝，且不给出原因：

```bash
$ curl -s -X POST localhost:3000/orders \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"items":[{"productId":"salmon-kibble-2kg","quantity":1}]}'
{"id":"d7dbe1ab-c408-4688-9e9e-2925ed2025a3","partnerId":"northside","items":[{"productId":"salmon-kibble-2kg","quantity":1,"price":2499}],"total":2499,"status":"placed","paymentId":null,"trackingNumber":null}
$ WEBHOOK_ID=msg_2c9e4f1a npx tsx scripts/send-webhook.ts payments payment.succeeded \
    '{"paymentId":"pay_9d0a2","orderId":"d7dbe1ab-c408-4688-9e9e-2925ed2025a3","amount":2499}'
200
$ WEBHOOK_ID=msg_2c9e4f1a npx tsx scripts/send-webhook.ts payments payment.succeeded \
    '{"paymentId":"pay_9d0a2","orderId":"d7dbe1ab-c408-4688-9e9e-2925ed2025a3","amount":2499}'
200
$ TAMPER=1 npx tsx scripts/send-webhook.ts payments payment.succeeded \
    '{"paymentId":"pay_9d0a2","orderId":"d7dbe1ab-c408-4688-9e9e-2925ed2025a3","amount":2499}'
401 {"message":"Webhook signature verification failed","error":"Unauthorized","statusCode":401}
$ PAYMENTS_WEBHOOK_SECRET=whsec_$(openssl rand -base64 32) npx tsx scripts/send-webhook.ts payments payment.succeeded \
    '{"paymentId":"pay_9d0a2","orderId":"d7dbe1ab-c408-4688-9e9e-2925ed2025a3","amount":2499}'
401 {"message":"Webhook signature verification failed","error":"Unauthorized","statusCode":401}
```

```bash
[Nest] 55905  - 09/30/2026, 6:52:48 PM     LOG [PaymentProviderWebhooksController] Order d7dbe1ab-c408-4688-9e9e-2925ed2025a3 paid: pay_9d0a2, 2499 cents
```

最后，轮换端点的密钥。接收端仍用旧密钥运行，下一次投递依然通过校验：它携带两个签名。然后用新密钥（排在前面）和旧密钥重启接收端，正如合作方会部署的那样，再下单并取消：那条投递同样通过校验：

```bash
$ curl -s -X POST localhost:3000/partner/webhook-endpoints/ep_01a0f33b79e27154b8fd089a10f3e48e/rotate-secret \
    -H 'Authorization: Bearer partner_northside_7c1d2e'
{"secret":"whsec_BUPv/LlKhv9qDH7udP3gsGPquuj4WaopeP8fxyouWOk="}
$ curl -s -X POST localhost:3000/orders/d7dbe1ab-c408-4688-9e9e-2925ed2025a3/cancel \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"reason":"customer changed their mind"}'
{"id":"d7dbe1ab-c408-4688-9e9e-2925ed2025a3","partnerId":"northside","items":[{"price":2499,"quantity":1,"productId":"salmon-kibble-2kg"}],"total":2499,"status":"cancelled","paymentId":"pay_9d0a2","trackingNumber":null}
```

```bash
[Nest] 56304  - 09/30/2026, 6:52:50 PM     LOG [StoreWebhooksController] Order d7dbe1ab-c408-4688-9e9e-2925ed2025a3 cancelled: customer changed their mind (msg_01a0f33bb022712e8e440b7adef8208f)
```

```bash
STORE_WEBHOOK_SECRET=whsec_BUPv/LlKhv9qDH7udP3gsGPquuj4WaopeP8fxyouWOk=,whsec_yKaIEKkc0ZpOWofM8Fx1Wc5yxdffKSsP1jolLCynqug=
```

```bash
$ curl -s -X POST localhost:3000/orders \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"items":[{"productId":"clumping-litter-10l","quantity":2}]}'
{"id":"d203fd6f-7396-489b-9d20-775cd8a6ca4e","partnerId":"northside","items":[{"productId":"clumping-litter-10l","quantity":2,"price":1599}],"total":3198,"status":"placed","paymentId":null,"trackingNumber":null}
$ curl -s -X POST localhost:3000/orders/d203fd6f-7396-489b-9d20-775cd8a6ca4e/cancel \
    -H 'Authorization: Bearer partner_northside_7c1d2e' \
    --json '{"reason":"ordered twice"}'
{"id":"d203fd6f-7396-489b-9d20-775cd8a6ca4e","partnerId":"northside","items":[{"price":1599,"quantity":2,"productId":"clumping-litter-10l"}],"total":3198,"status":"cancelled","paymentId":null,"trackingNumber":null}
```

```bash
[Nest] 56624  - 09/30/2026, 6:52:52 PM     LOG [StoreWebhooksController] Order d203fd6f-7396-489b-9d20-775cd8a6ca4e cancelled: ordered twice (msg_01a0f33bb8ad7249a0fa069361100c49)
```

这些投递就是你数据库中店铺 schema 里的行：

```bash
$ psql "$DATABASE_URL" -c "SELECT type, status, attempts, last_status_code FROM nest_webhooks.deliveries ORDER BY created_at"
      type       |  status   | attempts | last_status_code
-----------------+-----------+----------+------------------
 order.shipped   | succeeded |        1 |              204
 order.cancelled | succeeded |        1 |              204
 order.cancelled | succeeded |        1 |              204
 order.cancelled | succeeded |        1 |              204
(4 rows)
```

#### 测试

在 e2e 测试中，用 [PGlite](https://pglite.dev) 在进程内跑 PostgreSQL 并应用真实迁移，关闭 relay 与 worker，把传输层替换为记录请求的实现，并用 `signWebhook()` 为各服务商的请求签名。用 PGlite 上的数据库覆盖 `DrizzleModule` 注册的那个（`getDrizzleToken()` 返回其令牌）：存储会跟着走，因为它们的工厂注入它，并在应用启动时在那里创建 schema：

```typescript
@@filename(test/webhooks.e2e-spec)
import { PGlite } from '@electric-sql/pglite';
import type { INestApplication } from '@nestjs/common';
import { getDrizzleToken } from '@nestjs/drizzle';
import { OutboxRelay } from '@nestjs/outbox';
import { Test } from '@nestjs/testing';
import { InMemoryWebhookTransport, WebhookEndpoints, WebhookTransport, WebhookWorker } from '@nestjs/webhooks';
import { signWebhook } from '@nestjs/webhooks/testing';
import { drizzle } from 'drizzle-orm/pglite';
import { migrate } from 'drizzle-orm/pglite/migrator';
import { fileURLToPath } from 'node:url';
import request from 'supertest';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { AppModule } from '../src/app.module.js';
import * as schema from '../src/database/schema.js';
import { OrdersService } from '../src/orders/orders.service.js';

const PAYMENTS_SECRET = `whsec_${Buffer.alloc(32, 1).toString('base64')}`;
const CARRIER_SECRET = 'carrier_test_secret';

describe('Order webhooks', () => {
  const client = new PGlite(); // PostgreSQL, in-process
  const db = drizzle({ client });
  const transport = new InMemoryWebhookTransport(); // records requests instead of sending them
  const partner = { id: 'northside', name: 'Northside Pet Supplies' };
  let app: INestApplication;
  let relay: OutboxRelay;
  let worker: WebhookWorker;
  let endpoint: { id: string; secret: string };

  beforeAll(async () => {
    // The real migrations: the order tables. The stores create their schemas when the app starts.
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    process.env.PAYMENTS_WEBHOOK_SECRET = PAYMENTS_SECRET;
    process.env.CARRIER_WEBHOOK_SECRET = CARRIER_SECRET;
    process.env.OUTBOX_RELAY = 'off'; // no poll loops: the test drives the relay and the worker
    process.env.WEBHOOKS_WORKER = 'off';
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(db) // the stores' factories inject it too
      .overrideProvider(WebhookTransport)
      .useValue(transport)
      .compile();
    app = moduleRef.createNestApplication({ rawBody: true });
    await app.init();
    relay = app.get(OutboxRelay);
    worker = app.get(WebhookWorker);
    endpoint = await app.get(WebhookEndpoints).create({ url: 'https://hooks.northside.example.com/store', eventTypes: ['*'], tenant: partner.id });
  });

  afterAll(async () => {
    await app.close();
    await client.close();
  });

  /** Publishes committed messages (the fan-out), then runs one worker batch. */
  const deliver = async () => {
    await relay.runOnce();
    return worker.runOnce();
  };
  const shipment = (orderId: string, id = 'evt_1') =>
    signWebhook({
      scheme: 'stripe',
      header: 'Carrier-Signature',
      secret: CARRIER_SECRET,
      payload: { id, type: 'shipment.shipped', data: { orderId, trackingNumber: 'TRK-1' } },
    });

  it("sends order.shipped to the partner once the carrier's webhook commits", async () => {
    const order = await app.get(OrdersService).placeOrder(partner, { items: [{ productId: 'salmon-kibble-2kg', quantity: 1 }] });
    const paid = signWebhook({
      scheme: 'standard',
      secret: PAYMENTS_SECRET,
      payload: { type: 'payment.succeeded', data: { paymentId: 'pay_1', orderId: order.id, amount: order.total } },
    });
    await request(app.getHttpServer()).post('/webhooks/payments').set(paid.headers).send(paid.body).expect(200);
    const shipped = shipment(order.id);
    await request(app.getHttpServer()).post('/webhooks/carrier').set(shipped.headers).send(shipped.body).expect(200);
    expect(transport.sent).toEqual([]); // nothing until the outbox relays the commit

    expect(await deliver()).toMatchObject({ delivered: 1 });

    const sent = transport.single({ type: 'order.shipped', endpointId: endpoint.id });
    expect(sent.data).toEqual({ orderId: order.id, trackingNumber: 'TRK-1' });
    expect(sent.isSignedWith(endpoint.secret)).toBe(true);
  });

  it('processes a redelivered shipment webhook once', async () => {
    const [order] = await db.select().from(schema.orders);
    const shipped = shipment(order!.id);
    await request(app.getHttpServer()).post('/webhooks/carrier').set(shipped.headers).send(shipped.body).expect(200, '');
    expect(await deliver()).toMatchObject({ claimed: 0 });
    expect(transport.sent).toHaveLength(1);
  });

  it('refuses a webhook whose body was altered', async () => {
    const shipped = shipment('order-x', 'evt_2');
    await request(app.getHttpServer())
      .post('/webhooks/carrier')
      .set(shipped.headers)
      .send(shipped.body.replace('TRK-1', 'TRK-2'))
      .expect(401);
    expect(await deliver()).toMatchObject({ claimed: 0 });
  });
});
```

- outbox、两个存储、迁移、扇出、签名与校验都是真的。只有网络被替换：`InMemoryWebhookTransport` 回 200 并保留每个请求，`respondWith(503)` 或一个函数可以模拟宕机、缓慢或挑剔的合作方。
- `deliver()` 是提交之后的整条流水线：`relay.runOnce()` 发布已提交消息（扇出创建投递），`worker.runOnce()` 领取一批并发送。
- `SentWebhook.isSignedWith(secret)` 用某个端点的密钥校验 `v1` 签名，`data` 是请求体的 `data`，因此测试断言的是合作方本会校验并读取的内容。
- `signWebhook()` 生成支付服务商、Stripe 或 GitHub 会发送的请求体与请求头。重投时复用它的 `id`，移动 `timestamp` 测试容差，改动请求体的一个字节测试篡改。
- 对依赖时间的行为（如退避、租约、轮换重叠），用 `vi.spyOn(Date, 'now')` 把 `Date.now()` 前移。worker 与存储都从它取时间，而真实定时器仍为套接字运行。
- 示例的 `tutorial.e2e-spec.ts` 在真实 HTTP 上跑遍本页每一节，覆盖 PGlite 与 PostgreSQL 服务器：API 通过默认传输层向合作方接收端投递，包含宕机、重放、重投与轮换。其 `zod.e2e-spec.ts` 用 DTO 的 Zod 变体与 `StandardSchemaValidationPipe` 启动同一个应用。其存储测试通过 Drizzle 在 PGlite、PostgreSQL 和 MySQL 上运行存储，并通过 TypeORM 在 PostgreSQL 上运行：契约套件、随订单提交与回滚的派发，以及生产中的 schema。

关于测试环境的更多内容见[端到端测试](/fundamentals/testing#end-to-end-testing)。

#### 投递保证

出站 webhook 以**至少一次**投递；接收方按 `webhook-id` 去重。

| 情况 | 结果 |
| --- | --- |
| 订单的事务回滚 | 消息从未存在，什么都不发送 |
| 订单的事务提交 | 该租户每个已订阅端点各一条投递，最终投递成功或失败并留有尝试日志 |
| outbox 重投该消息（relay 在扇出后崩溃） | 扇出是幂等的：每条消息对每个端点只有一条投递 |
| 端点在消息之后才创建，或已被禁用 | 它不会收到，重放也不会补上 |
| worker 在领取后死亡 | 租约过期后由另一个 worker 发送（`worker.lease`，1 分钟） |
| worker 在发送后、记录前死亡 | 租约过期后**发送两次**，`webhook-id` 相同 |
| 两个 worker 处理同一条投递 | 领取在租约期内是排他的，之后每次写入都受其栅栏保护 |
| 合作方回 2xx | 已投递 |
| 回其他任何内容，或没有响应 | 带退避重试，尊重 `Retry-After`；429、502、503、504 会给端点定节奏 |
| 回 410 Gone | 失败（`rejected`），并禁用该端点（`gone`） |
| 连续失败达 `disableEndpointAfter` | 端点被禁用（`failing`），仅一次 |
| 合作方申请重放 | 以相同 `webhook-id` 开新一轮，其 inbox 会跳过 |

投递**没有顺序**。worker 对一个端点的投递逐条发送，最超期的优先，但失败的尝试会等完其退避，期间后面的消息照常发出；多个 worker 会同时向同一端点发送；重放会立刻发送一条旧消息。同一订单的两次更新可能以任意顺序到达合作方。接收方的应对方式与处理重复相同：请求体的 `timestamp` 是消息被派发的时间（`webhook-timestamp` 是本次尝试签名的时间），因此处理器可以忽略比已持有状态更旧的事件，或把 webhook 当作信号并回 API 读取当前状态。

入站 webhook 在默认 inbox 下**在常见情况下每个 webhook id 与接收方只运行一次处理器**（处理器与 inbox 写入之间崩溃后、或两份副本在两个实例上竞争时会再跑一次），而其 `processInTransaction()` 中的工作**恰好一次**。

#### 生产检查清单

- 把端点与投递放在应用的数据库中，且位于数据库服务器上：注册 `PostgresWebhookStore` 或 `MySqlWebhookStore`，以及紧随其旁的 outbox 存储（见[把 webhook 存进你的数据库](/http/webhooks#keep-webhooks-in-your-database)）。生产守卫拒绝以内存模式启动；`allowInMemoryStorage` 适用于那些待投递丢失也无所谓损失的进程。
- 在新版本启动之前应用两个存储的迁移，用 `npx @nestjs/webhooks migrate` 和 `npx @nestjs/outbox migrate` 或你的迁移工具，并在 CI 中用 `status` 检查。`NODE_ENV=production` 时存储不在启动时迁移：schema 落后会让启动失败。
- 在 PostgreSQL 上，保持数据库默认隔离级别为 READ COMMITTED：存储拒绝更严格的级别。在 MySQL 上，当 MySQL 打破事务中的死锁（错误 1213）时重新执行该事务：它已回滚，连同它派发的消息与记录的 webhook。
- 保持 `delivery.allowHttp` 与 `delivery.allowPrivateNetworks` 关闭。合作方的 URL 是不可信输入，传输层自行解析它并锁定已检查的地址。对你确实要投递的那一个私有网段使用 `allowedAddresses`，并对 `destination-blocked` 事件设告警：有客户把 webhook 指向你的元数据服务，值得看一眼。
- 在少数几个实例中运行 worker（`WEBHOOKS_WORKER`），不要在每个 API pod 里都跑：每次领取是一个短事务，租约可防止重复发送同一条投递。
- 对 `deliveries.stats()` 的 `lagMs` 与 `failed` 设告警，也对 `endpoint-disabled` 设告警：用邮件告知合作方其端点被关闭及原因。
- 给负载做版本。合作方会把处理器留用好几年，而 `retry()` 会按派发时的原样重发请求体。只往某个类型的 `data` 里加字段，绝不重命名或删除字段。做破坏性变更时，新增一个类型（如 `eventTypes` 中的 `order.shipped.v2`），并在同一事务中同时派发两者（`dispatch()` 接受数组），让合作方逐步迁移订阅；订阅了 `*` 的端点两个都会收到。之后再停止派发旧类型。旧消息的重放仍携带旧形状，直到日志被清理。
- 把投递日志与重放给到合作方。它能在对方开工单之前回答"你到底发了没有？"。
- 用重叠期轮换密钥，除非密钥已泄露，否则不要用 `overlap: 0`，并用 `WEBHOOKS_ENCRYPTION_KEYS` 静态加密它们。把密钥放在密钥管理服务中。
- 清理日志。从一个[定时任务](/application/task-scheduling#declarative-cron-jobs)里调用 `deliveries.prune('30d')`；没有东西会替你调度它。
- 对入站 webhook，保持 `rawBody: true`，并把接收方密钥放在环境变量中。服务商轮换期间同时列出旧密钥和新密钥。
- 让服务商处理器保持简短，并且自身幂等（在事务内做状态检查），即使有 `processInTransaction()` 也一样：inbox 防重投，状态检查防某个服务商为同一事实发来两个不同事件。
- 用 `OutboxInbox.prune()` 清理 inbox，窗口要长于任何服务商的重试计划（Stripe 重试三天，GitHub 完全不重试）。对 GitHub 而言，这个窗口也是重放请求能被抓住的时长（去重以请求体为键，见[其他发送方](/http/webhooks#other-senders)）。
- 调用 `app.enableShutdownHooks()`，让部署时正在进行的尝试得以完成，其余的被释放。
- 自己写存储时，在 CI 中用 `concurrent: true` 对生产所用的数据库版本运行契约套件。

#### 存储契约

`PostgresWebhookStore` 与 `MySqlWebhookStore` 实现了该包的两个契约：`WebhookEndpointStore` 与 `WebhookDeliveryStore`。要支持其他数据库，请在自己的提供者中实现它们。两个接口中每个方法的 JSDoc 都写明了它的规则，以及它防的是哪种竞争。

**注册。** 存储是普通的单例提供者，在其构造函数中对可注入的 `WebhooksStorage` 调用 `registerSource()`，声明它实现哪些契约：`endpoints`、`deliveries`，或由一个类同时提供两者。注册表会立刻检查形状，拒绝第二次注册（除非传 `replace: true`），并在 `WebhooksModule` 初始化时锁定并记录所使用的存储。什么都没注册时，模块使用 `InMemoryWebhookStore`，它重启即丢端点和待投递，也无法在实例间共享。`NODE_ENV=production` 时改为启动失败，除非 `allowInMemoryStorage: true` 接受这一点。

**没有事务句柄。** 与 outbox 的 `add()` 不同，这里没有方法接受你的事务：outbox 负责把消息带出你的事务，而 webhook 存储运行在自己的连接上。

**方法。** 标记为原子的方法是一条条件语句或一个带行锁的事务，绝不是先读后写；契约套件竞争的就是这些方法。

| 方法 | 作用 | 原子 |
| --- | --- | --- |
| `createEndpoint`、`getEndpoint`、`listEndpoints`、`updateEndpoint`、`deleteEndpoint` | 端点的生命周期；`list` 按租户、最新的在前 | 否 |
| `findSubscribedEndpoints(tenant, type)` | 恰好属于该租户、订阅了该类型（或 `*`）的已启用端点：扇出的查询 | 否，但套件检查它绝不返回其他租户的 |
| `addEndpointSecret(id, secret, expireOthersAt, now)` | 轮换：新密钥放最前，其余设置过期 | 是：行被锁定，因此两次轮换都会落地 |
| `recordEndpointFailure(id, failure)` | 首次失败时设置 `failingSince`；失败足够久后禁用端点，并只告知一次 | 是：行被锁定 |
| `recordEndpointSuccess(id)` | 清除 `failingSince` | 否 |
| `createDeliveries(message, deliveries)` | 扇出：消息不存在才插入，每条投递在其 `(messageId, endpointId)` 不存在时才插入 | 是：该组合上的唯一键，例如 PostgreSQL 的 `ON CONFLICT DO NOTHING` |
| `claimDeliveries(request)` | 租借到期的投递（最超期的优先）及其消息 | 是：`FOR UPDATE SKIP LOCKED`，再写租约 |
| `recordDeliveryAttempt(id, owner, update)` | 尝试的结果与日志行，前提是 `owner` 仍持有租约 | 是：受租约所有者栅栏保护 |
| `releaseDeliveries(ids, owner, nextAttemptAt)` | 归还租约，需要时推迟下次时间 | 是：栅栏保护 |
| `getDelivery`、`getMessage`、`listDeliveries`、`listDeliveryAttempts`、`deliveryStats` | 读取；`list` 按租户、端点、消息、状态与类型，最新的在前 | 否 |
| `retryDeliveries(filter, now)` | 为未被租借的匹配项开新一轮 | 是：一条 `UPDATE`，租约条件写在 `WHERE` 中 |
| `pruneDeliveries(before)` | 早于 `before` 的已完成投递、其日志，以及不再有投递的消息 | 否，但绝不删除待投递 |

**测试它**：用 `@nestjs/webhooks/testing` 的 `webhookEndpointStoreContract()` 与 `webhookDeliveryStoreContract()`。每个用例都会用你传入的函数在空表上取得一个存储。教程的测试通过 Drizzle 对 `PostgresWebhookStore` 跑两套契约，正如你会对自己的存储所做：

```typescript
@@filename(test/drizzle-webhook.store.e2e-spec)
/** A store on emptied tables, built the way Nest builds it: with the database and a registry. */
async function freshStore(db: Database) {
  await db.execute(sql.raw(`TRUNCATE ${STORE_TABLES.join(', ')} RESTART IDENTITY`));
  return { store: new PostgresWebhookStore({ executor: fromDrizzle(db) }, new WebhooksStorage()) };
}

// ...

// The concurrency cases run too; with one connection, PGlite runs them one statement at a time.
describe('the endpoint contract', () => {
  for (const c of webhookEndpointStoreContract(() => freshStore(db), { concurrent: true })) {
    it(c.name, c.run);
  }
});
describe('the delivery contract', () => {
  for (const c of webhookDeliveryStoreContract(() => freshStore(db), { concurrent: true })) {
    it(c.name, c.run);
  }
});
```

使用 `concurrent: true` 时，套件会竞争同一端点上的轮换与失败、并行的 worker 领取、同一条消息的扇出、过期 worker 与接管、以及重试与领取。在 PGlite 上（单连接）它们串行通过：也请在服务器上通过多连接池运行，缺少正确锁的存储会在那里失败。该包自身的测试对手写的 Drizzle 存储运行这些套件，作为"按接口实现的存储能通过"的证明。

#### 参考

##### 模块选项

`WebhooksModule.forRoot()` 接受这些选项。`forRootAsync()` 在顶层接受 `outgoing`、`transport`（作为类）、`imports` 和 `isGlobal`，与 `useFactory`、`useClass` 或 `useExisting` 并列，工厂返回其余部分。见[注册模块](/http/webhooks#register-the-modules)。

| 选项 | 默认值 | 说明 |
| --- | --- | --- |
| `eventTypes` | 任意类型 | 本应用发送的消息类型。`dispatch()` 与新建端点只接受这些（端点还接受 `*`）。 |
| `retry` | 10 次尝试 | `attempts`（含首次）、`backoff` 与 `retryIf(error, attempt, delivery)`。传数字即设置 `attempts`，`false` 表示只尝试一次。 |
| `retry.backoff` | 见说明 | `delay`（`'5s'`）、`factor`（4）、`maxDelay`（`'1d'`，也是 `Retry-After` 的上限）、`jitter`：`'equal'`、`'full'` 或 `'none'`（`'equal'`）。也可以是一个接收尝试次数、错误与投递并返回时长的函数。 |
| `disableEndpointAfter` | `'5d'` | 连续这么久每次尝试都失败且无成功的端点将被禁用。`false` 表示永不因失败禁用。 |
| `secretRotationOverlap` | `'24h'` | 被轮换掉的密钥在新密钥旁继续签名多久。 |
| `delivery.timeout` | `'15s'` | 一次尝试：DNS、连接、TLS、请求与响应。应短于 `worker.lease`。 |
| `delivery.allowHttp` | `false` | 接受 `http://` 端点 URL。用于开发。 |
| `delivery.allowPrivateNetworks` | `false` | 向回环、私有、共享地址与唯一本地网段投递。用于开发。链路本地与云元数据地址始终被屏蔽。 |
| `delivery.allowedAddresses` | 无 | CIDR 网段，如 `10.20.0.0/16`，即使本会被屏蔽也向其投递。 |
| `delivery.maxResponseSize` | 4096 | 读取并保留在日志中的响应体字节数。 |
| `delivery.userAgent` | `NestJS-Webhooks/1.0` | `User-Agent` 头。 |
| `worker.enabled` | `true` | 是否在本进程投递。只派发的实例设为 `false`。 |
| `worker.pollInterval` | `'1s'` | 空闲时两次轮询之间的等待。`notify()` 会立即轮询。 |
| `worker.batchSize` | 50 | 每次轮询领取的投递数。 |
| `worker.concurrency` | 10 | 并行投递的端点数。同一端点的投递逐条发送。 |
| `worker.lease` | `'1m'` | 领取的排他时长。应长于 `delivery.timeout`。 |
| `encryption` | 关闭 | 静态加密端点密钥。`keys` 列出 32 字节的 `Buffer` 或至少 32 字符的字符串，最新的在前：第一个密钥加密，所有密钥都能解密。 |
| `receivers` | 无 | 本应用接受的 webhook 发送方，键为 `@VerifyWebhook()` 使用的名称（见下表）。 |
| `transport` | `HttpWebhookTransport` | 顶层传 `WebhookTransport` 类，或从异步工厂传实例。 |
| `allowInMemoryStorage` | `false` | 允许生产应用在未注册存储的情况下启动。 |
| `outgoing` | `true` | 仅顶层。只接收 webhook 的服务设为 `false`：没有端点、投递、worker 或存储。 |
| `imports` | 无 | 仅顶层。传输类要注入其导出的那些模块。 |
| `isGlobal` | `true` | 仅顶层。把模块注册为全局。 |

时长可以是毫秒数或 `'15s'`、`'24h'`、`'5d'` 这样的字符串。选项的注入令牌是 `WEBHOOKS_MODULE_OPTIONS`。

`receivers` 的每个条目接受这些选项（见[接收支付服务商的 webhook](/http/webhooks#receive-the-payment-providers-webhooks)与[接收承运商类 Stripe 的 webhook](/http/webhooks#receive-the-carriers-stripe-like-webhooks)）：

| 选项 | 适用 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `scheme` | 全部 | 必需 | `'standard'`、`'stripe'`、`'github'`，或继承 `WebhookSignatureScheme` 的类的实例 |
| `secret` | 全部 | 必需 | 一个密钥，或发送方轮换期间的数组。每个都会尝试。 |
| `tolerance` | `standard`、`stripe`、自定义 | `'5m'` | 被签名时间戳与当前时间之间允许的最大差距（前后皆可） |
| `header` | `stripe` | `'stripe-signature'` | 签名头，用于照搬 Stripe 方案的发送方 |
| `id` | `stripe`、`github` | 负载的 `id`；`X-GitHub-Delivery` 头（未被签名，见[其他发送方](/http/webhooks#other-senders)） | 接收负载与请求头并返回去重 id 的函数，最长 255 个字符 |
| `dedupe` | 全部 | `true` | 跳过该接收方已处理过的 webhook id |
| `consumer` | 全部 | `webhooks:<name>` | inbox 消费者名。保持稳定。最长 255 个字符（含默认值）：更长会在启动时以 `TypeError` 失败 |

##### PostgreSQL 与 MySQL 存储

`new PostgresWebhookStore(options, webhooksStorage)`（来自 `@nestjs/webhooks/postgres`）与 `new MySqlWebhookStore(options, webhooksStorage)`（来自 `@nestjs/webhooks/mysql`）接受这些选项。outbox 的 `PostgresOutboxStore` 与 `MySqlOutboxStore` 接受同样的选项，默认 `schema` 为 `'nest_outbox'`：

| 选项 | 默认值 | 含义 |
| --- | --- | --- |
| `executor` | 必填 | 存储如何访问数据库：`fromDrizzle(db)`、`fromTypeOrm(dataSource)`、`fromPrisma(prisma, options)`、`fromKysely(db)`，以及 PostgreSQL 上的 `fromPg(pool)` 或 MySQL 上的 `fromMysql2(pool)`，从存储自己的子路径导入：另一方言的执行器无法通过编译 |
| `schema` | `'nest_webhooks'` | 在 PostgreSQL 上，是其表的 schema，由首个迁移创建：字母、数字与下划线，不以数字开头，最多 63 个字符。在 MySQL 上，是其在连接数据库中的表前缀（`nest_webhooks_endpoints`…）：小写字母、数字与下划线，不以数字开头，最多 40 个字符 |
| `migrate` | `true`，`NODE_ENV=production` 时例外 | 应用启动时应用待执行的迁移。为 `false` 时，schema 落后会让启动以 `WebhookSchemaError` 失败 |

每个执行器接受你的数据库客户端，以及它自己那种事务对象，随后由 `dispatch()` 与 `processInTransaction()` 接受：

| 执行器 | 接受 | 事务对象 |
| --- | --- | --- |
| `fromDrizzle(db)` | 一个 Drizzle 数据库：PostgreSQL 上任意驱动；MySQL 上为 `drizzle-orm/mysql2` | `db.transaction()` 交给回调的 `tx` |
| `fromTypeOrm(dataSource)` | 类型为 `postgres` 或 `mysql` 的 `DataSource` | `dataSource.transaction()` 交给回调的 `EntityManager`，或 `startTransaction()` 之后的 `QueryRunner` |
| `fromPg(pool)` | PostgreSQL 上的 node-postgres `Pool` | `pool.connect()` 取得的客户端，在 `BEGIN` 之后 |
| `fromMysql2(pool)` | MySQL 上的 `mysql2/promise` 连接池 | `pool.getConnection()` 取得的连接，在 `beginTransaction()` 之后 |
| `fromPrisma(prisma, options)` | Prisma 客户端，经 `@prisma/adapter-pg` 这类驱动适配器，MySQL 上为 `@prisma/adapter-mariadb`。`maxWait`（默认 `'10s'`）与 `timeout`（默认 `'1m'`）限制存储自身的事务 | `prisma.$transaction()` 交给回调的事务客户端 |
| `fromKysely(db)` | 带 PostgreSQL 或 MySQL 方言的 `Kysely` 实例 | `db.transaction().execute()` 交给回调的事务 |

存储的 `migrate()` 方法会立即应用待执行的迁移（无论 `migrate` 选项怎么说），并以已应用的版本解析。`PostgresWebhookStore.migrationSql()` 与 `MySqlWebhookStore.migrationSql()` 返回其 SQL（含簿记）。它们的选项是 `schema`、起始版本 `from`（默认 `0`，即新数据库）与 `to`（默认为该包所需的版本），以及 `statementBreakpoints`——在语句之间插入 drizzle-kit 的 `--> statement-breakpoint`。在 PostgreSQL 上从版本 0 开始时，SQL 以 `CREATE SCHEMA IF NOT EXISTS` 开头，需要对数据库的 CREATE 权限：如果有人已为你创建了 schema，请去掉它。`MySqlWebhookStore.migrationStatements()` 把 MySQL 的语句逐条返回，按顺序各执行一次。`schemaVersion` 是该包所需的版本；某个 schema 自身的版本是它 `migrations` 表中已应用的最高版本。

命令行 `npx @nestjs/webhooks` 接受 `--url`（默认 `DATABASE_URL`），其协议决定存储：`postgres://` 或 `postgresql://` 对应 `PostgresWebhookStore` 的 schema，`mysql://` 对应 `MySqlWebhookStore` 的表。它也接受 `--schema`（默认 `nest_webhooks`）。`npx @nestjs/outbox` 对 outbox 的存储做同样的事：

| 命令 | 作用 |
| --- | --- |
| `migrate` | 应用待执行的迁移，与启动时 `migrate: true` 相同。需要安装 `pg` 或 `mysql2` |
| `status` | 打印 schema 的版本与该包所需的版本，schema 落后时以 1 退出 |
| `sql` | 打印 `migrationSql()` 的 SQL，从 `--from` 到 `--to`，不需要数据库：PostgreSQL 的，或加 `--dialect mysql` 打印 MySQL 的。`--statement-breakpoints` 为 drizzle-kit 分隔语句 |

##### 服务与装饰器

- `Webhooks`：`dispatch(tx, message)` 接受一条消息或数组，含 `type`、`data`、`tenant` 与可选的 `id`，对未知类型、无法 JSON 序列化的数据或非法 id 抛出 `TypeError`。`notify()` 立即运行 relay。
- `WebhookEndpoints`：`create(input)`、`list(query)`、`get(id, scope)`、`update(id, changes, scope)`、`delete(id, scope)`、`getSecret(id, scope)` 与 `rotateSecret(id, options)`，其中 `options` 含 `tenant`、`overlap` 和 `secret`。`create()` 也接受 `secret`，即用一个已有的 `whsec_…` 代替生成的密钥。见[让合作方订阅](/http/webhooks#let-partners-subscribe)。
- `WebhookDeliveries`：`list(query)`、`get(id, scope)`、`retry(idOrFilter, scope)`、`stats()` 与 `prune(olderThan)`。见[重试、投递日志与重放](/http/webhooks#retries-the-delivery-log-and-replay)。
- `WebhookWorker`：投递器，应用启动时启动，除非 `worker.enabled` 为 `false`。`start()`；`stop()` 停止领取、等待进行中的尝试并释放尚未开始的投递；`running`；`notify()` 立即轮询而不是等下一个周期；`runOnce()` 领取一批并投递，解析为 `claimed`、`delivered`、`retried`、`failed`、`released` 的计数，以及失去租约的数量（`leaseLost`），它在 worker 停止时也能工作（测试就是这样驱动的）；`stats()`，与 `WebhookDeliveries.stats()` 相同。
- `WEBHOOKS_OUTBOX_TOPIC`：已派发消息所走的 outbox 主题，`'nestjs.webhooks.message'`，通往该包的扇出处理器 `@OnOutboxMessage()`。若 outbox 的 `route` 在多个传输间选择，该主题走 `local`。
- `WebhookVerifier`：`verify(receiver, request)` 校验未通过 HTTP 路由到达的请求（例如存在队列里的），依据其 `headers` 与 `rawBody`。
- `@VerifyWebhook(receiver)` 在方法或控制器上执行校验与去重。`@IncomingWebhook()` 注入已校验的 webhook：`receiver`、`id`、`timestamp`、`payload`、`rawBody` 与 `processInTransaction()`。`@WebhookPayload()` 只注入负载，并且像 `@Body()` 一样接受管道。

##### 传输层

worker 通过 `WebhookTransport` 提供者发送。默认的 `HttpWebhookTransport` 由 `delivery` 选项构建：每次尝试一个 `POST`，走 `node:http` 与 `node:https`，主机只解析一次并检查它解析出的每个地址，套接字锁定到已检查的地址，从不跟随重定向，不使用环境变量中的代理。其构造函数接受两个 `delivery` 没有的选项：

- `ca`：除 Node 自带之外要信任的证书颁发机构，用于私有 CA 后的端点。它们被加入 Node 的信任库，因此公共端点仍能校验。
- `lookup`：把一个主机名解析为其全部地址（每个含 `address` 与其 `family`，4 或 6），替代系统解析器。它返回的每个地址仍会被检查，连接走第一个。

要使用它们，把实例作为 `transport` 传入，并带上与 `delivery` 相同的 `allowHttp`、`allowPrivateNetworks` 和 `allowedAddresses`：`delivery` 仍决定 `WebhookEndpoints` 接受哪些 URL，传输层决定连接到什么。

```typescript
WebhooksModule.forRoot({
  delivery: { allowedAddresses: ['10.20.0.0/16'] },
  transport: new HttpWebhookTransport({
    allowedAddresses: ['10.20.0.0/16'],
    ca: readFileSync('/etc/ssl/partners-ca.pem'),
  }),
}),
```

自己的传输层继承 `WebhookTransport` 并实现 `send(request, options)`，其中 `options` 含本次尝试的 `signal` 与 `attempt` 序号。请求携带 `url`、已签名的 `headers` 与 `body`，以及其端点、投递和消息的 id。无论状态如何，都以响应的 `statusCode`、`headers` 与其 `body` 开头部分解析；只在没有响应时抛错；在 `delivery.timeout` 之后、`signal` 中止时停止。`NonRetryableWebhookError` 与 `WebhookDestinationBlockedError` 让投递失败且不重试；其他任何错误都会重试。把该类作为 `transport` 传在 `forRoot()` 或 `forRootAsync()` 的顶层（由 Nest 实例化，`imports` 提供它要注入的模块），或传实例。它会用自身行为取代 SSRF 守卫：通过强制出口策略的代理（如 Smokescreen）发送，是写自定义传输层的一个理由；包裹 `HttpWebhookTransport` 则保留该守卫。

测试时，`InMemoryWebhookTransport` 只记录而不发送，也不做网络或地址检查（见[测试](/http/webhooks#testing)）：

- `sent`：所有请求，最早的在前，类型为 `SentWebhook`。`clear()` 清空它。
- `respondWith(answer)`：从此之后端点如何应答，之前是 200。可以是一个状态（`503`）、一个响应（`statusCode`、`headers` 如 `retry-after`、`body`），或一个接收请求与尝试序号并返回其一的函数；抛出则模拟没有响应。
- `filter(query)` 与 `single(query)`：匹配 `type`、`url`（字符串或 `RegExp`）、`endpointId` 与 `messageId` 的请求，或一个接收 `SentWebhook` 的函数。`single()` 在匹配数不为 1 时抛错并列出已发送的内容。

`SentWebhook` 含有 `request`、本轮中的 `attempt` 序号、`sentAt`、请求的 `url`、`type`、`messageId`、`endpointId`、`deliveryId`、`headers` 与 `body`、`data`（请求体的 `data`，已解析），以及 `isSignedWith(secret)`——用某个端点的密钥校验 `v1` 签名。

##### 事件

`WebhooksEvents.events$` 发出每个事件，同时每个事件也发布到诊断通道 `nestjs:webhooks:<type>`。

| 类型 | 负载类型 | 除 `type` 外的字段 |
| --- | --- | --- |
| `delivered` | `WebhooksDeliveredEvent` | `delivery`、`statusCode`、`attempt`、`durationMs` |
| `retry-scheduled` | `WebhooksRetryScheduledEvent` | `delivery`、`error`、`statusCode`（无响应时为 `null`）、`attempt`、`delayMs` |
| `delivery-failed` | `WebhooksDeliveryFailedEvent` | `delivery`、`error`、`statusCode`、`attempt`、`reason` |
| `endpoint-disabled` | `WebhooksEndpointDisabledEvent` | `endpointId`、`tenant`、`reason`（`'failing'` 或 `'gone'`） |
| `destination-blocked` | `WebhooksDestinationBlockedEvent` | `endpointId`、`tenant`、`reason`、`address` |
| `verification-failed` | `WebhooksVerificationFailedEvent` | `receiver`、`reason` |

失败投递的 `reason` 为 `exhausted`、`rejected`（410 Gone、被屏蔽的目的地、`NonRetryableWebhookError` 或 `retryIf`）、`endpoint-disabled` 或 `endpoint-deleted`。校验失败的 `reason` 为 `missing-header`、`malformed-header`（webhook id 超过 255 个字符也算）、`invalid-signature`、`timestamp-out-of-tolerance` 或 `invalid-payload`。`WebhooksEvent` 是所有负载类型的联合。

##### 错误

除 `NonRetryableWebhookError` 外，每个错误都继承 `WebhooksError`。带 `status` 的用于合作方 API 的异常过滤器，如[让合作方订阅](/http/webhooks#let-partners-subscribe)所述。

| 错误 | 状态 | 抛出时机 |
| --- | --- | --- |
| `InvalidWebhookEndpointError` | 400 | 端点的 URL、事件类型或密钥被拒绝。`field` 指明是哪一个。 |
| `WebhookEndpointNotFoundError` | 404 | 端点不存在，或属于其他租户 |
| `WebhookDeliveryNotFoundError` | 404 | 投递不存在，或属于其他租户 |
| `WebhookVerificationError` | 401，`invalid-payload` 为 400 | `WebhookVerifier.verify()` 拒绝请求。含 `receiver` 与 `reason`。 |
| `WebhookDestinationBlockedError` | 无 | 端点的 URL 是、或解析到被屏蔽的地址。投递失败且不重试。 |
| `WebhookResponseError` | 无 | 端点在 2xx 之外应答。含 `statusCode`，以及来自 `Retry-After` 头的 `retryAfterMs`。 |
| `WebhookDeliveryTimeoutError` | 无 | 在 `delivery.timeout` 内没有响应 |
| `NonRetryableWebhookError` | 无 | 自定义传输层抛出它以使投递失败且不重试 |
| `WebhookSchemaError` | 无 | `migrate` 关闭时存储的 schema 落后于该包的迁移，或应用迁移失败（`cause`）：启动与每次调用都会失败直到修复。含 `schema`、其 `version` 与 `requiredVersion`。来自 `@nestjs/webhooks/postgres` 与 `@nestjs/webhooks/mysql` |

`@VerifyWebhook()` 对被拒绝的请求回 401（被签名但不是 JSON 的请求体回 400）和一条通用消息，原因则进入 `verification-failed` 事件。请求体未按原始形式保留的请求，如果它不是 JSON 也不是表单会得到 415，否则得到 500 并记录缺失的 `rawBody: true`。
