NestJS中文文档
教程 / 用 Node.js 通过 webhooks 接收支付
已译 191/191

用 Node.js 通过 webhooks 接收支付

在 Node.js 中用 NestJS 接收支付:支付服务商的 webhook(如 Stripe 的)、签名校验、幂等键,以及恰好生效一次的事件。

本教程为电商后端加上支付:API 为每个订单在支付服务商处创建一笔支付,而订单变为已支付,只因为服务商签名过的 webhook 这么说了,绝不会因为浏览器从支付页面跳了回来。本教程承接 构建电商后端。收钱是服务商的事。API 的事是:只请求一次钱、只相信服务商签名过的内容,并且把服务商的每个事件都恰好应用一次——无论它们以什么顺序到达、到达多少次。

完成本教程后,这个 API 将能够:

  • 通过 @nestjs/http-client 上一个带类型的客户端,为每个订单在服务商处创建一笔支付,并把订单的 id 作为服务商的幂等键,因此重试或第二次点击都不会创建出第二笔支付。
  • 用 @nestjs/webhooks 接收服务商的 webhook:在原始请求体上校验,按事件 id 去重,并与它所引起的那处改动记录在同一个事务里。
  • 用一次条件更新把订单从 placed 推进到 paid,因此重放、迟到或乱序的事件都不会改变任何东西,支付也永远不会把已取消的订单救回来。
  • 支付失败时取消订单并归还其库存,复用电商教程里的取消逻辑。
  • 只有在支付的事务提交之后,才通过 事务性 outbox 宣告 order.paid。
  • 在测试中证明这一切:测试按服务商的方式为 webhook 签名,并针对 PostgreSQL 运行。

此处模拟了什么。 这里没有真正的支付服务商,本页的任何内容都不会向银行卡扣款。服务商是虚构的:它的 API 形状仿照 Stripe(一个带 bearer 密钥和 Idempotency-Key 请求头的 POST),它的 webhook 遵循 Standard Webhooks,即许多服务商采用的那套方案。你试用这个 API 时,由一个小脚本代替服务商;测试则自己为服务商的请求签名。切换到真实服务商 列出了改用真实服务商时需要改动的地方。

以下是各个端点,以及添加它们的小节:

端点 小节
电商教程已有的:/auth/*、/me、/health/*、/products、/cart 和 /orders 从电商后端开始
POST /orders/:id/payment 创建支付
POST /webhooks/payments 接收服务商的 webhook
提示

完成后的应用位于 GitHub:nestjs/example-payments-webhooks,其中包含测试和一份 CI 工作流。

从电商后端开始

从 构建电商后端 的成品应用开始,全部都要:src/、test/、带迁移的 drizzle/ 目录,以及它的数据库。本教程会改动其中几个文件,并新增第二个迁移。先安装它新增的三个包:

$ npm i --save @nestjs/webhooks @nestjs/outbox @nestjs/http-client
  • @nestjs/webhooks 校验服务商的 webhook,并跳过已经处理过的那些。
  • @nestjs/outbox 把已处理 webhook 的清单(它的 收件箱)保存在你的数据库里,并在提交之后发送 order.paid。即使应用不发送任何 webhook,@nestjs/webhooks 也需要它来提供收件箱。
  • @nestjs/http-client 负责调用服务商的 API。

服务商给你三样东西:它 API 的 URL、一个 API 密钥,以及一个 webhook 签名密钥。Standard Webhooks 把这个签名密钥写成 whsec_ 后接 base64。试一试 里的假服务商接受任意密钥,以及你自己生成的签名密钥。把它们加进 .env:

PAYMENTS_API_URL=http://localhost:4000
PAYMENTS_API_KEY=sk_test_anything
# 来自服务商的控制台。对假服务商:echo "whsec_$(openssl rand -base64 32)"
PAYMENTS_WEBHOOK_SECRET=

配置 schema 会在启动时校验它们,因此缺少密钥会让应用直接启动失败,而不是让每一个 webhook 都失败:

src/config.ts
import { z } from 'zod';

export const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  DATABASE_URL: z.url(),
  // 为访问令牌签名:至少 32 字节。
  JWT_SECRET: z.string().min(32),
  // 允许调用该 API 的浏览器来源,以逗号分隔。默认为无。
  CORS_ORIGINS: z
    .string()
    .default('')
    .transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
    .pipe(z.array(z.url())),
  // 支付服务商的 API,以及它给你的密钥。
  PAYMENTS_API_URL: z.url(),
  PAYMENTS_API_KEY: z.string().min(1),
  // 校验服务商的 webhook:whsec_ 加 base64,来自服务商的控制台。
  PAYMENTS_WEBHOOK_SECRET: z.string().startsWith('whsec_'),
  // 测试中为 "off",因为测试自己运行 outbox 的中继。
  OUTBOX_RELAY: z.enum(['on', 'off']).default('on'),
});

export type Env = z.infer<typeof envSchema>;

OUTBOX_RELAY 让测试自己运行 outbox 的中继,测试它 一节就是这么做的。

在订单上记录支付

订单在 placed 与 shipped 之间多出一个状态 paid,以及为它付了款的那笔支付在服务商处的 id。在 src/database/schema.ts 中,orders 表变成:

src/database/schema.ts
// ...
export const orders = pgTable(
  'orders',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id),
    // placed,然后 paid 和 shipped,或者 cancelled。
    status: text('status', { enum: ['placed', 'paid', 'shipped', 'cancelled'] }).notNull(),
    total: integer('total').notNull(),
    // 服务商为该笔支付提供的 id,在支付成功时写入。
    paymentId: text('payment_id'),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [index('orders_user_id_created_at_idx').on(table.userId, table.createdAt)],
);
// ...

状态是一个 text 列,其取值由 Drizzle 提供类型,因此新增状态不需要改动数据库。生成迁移(它会加上 payment_id 列)并应用:

$ npx drizzle-kit generate --name=payments
$ npx drizzle-kit migrate

下面这些服务会互相传递 Drizzle 的事务,所以先给它的类型起个名字:

src/database/drizzle.ts
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';

/** `db.transaction()` 传给其回调的东西。 */
export type Transaction = Parameters<Parameters<NodePgDatabase['transaction']>[0]>[0];

创建支付

服务商的 API 只有一次调用是这家商店需要的:为某个金额创建一笔支付,它返回这笔支付的 id 以及服务商的支付页面,顾客在那个页面输入银行卡信息。商店永远看不到卡号。服务商在 API 响应和 webhook 中发送的数据的类型:

src/payments/payment.ts
/** 一笔支付,即服务商 API 返回的样子。 */
export interface Payment {
  id: string;
  /** 以分为单位。 */
  amount: number;
  currency: string;
  /** 这笔支付是为什么付的:订单的 id。 */
  reference: string;
  status: 'requires_payment' | 'succeeded' | 'failed';
  /** 服务商的支付页面,顾客在那里付款。 */
  checkoutUrl: string;
}

/** 服务商的 webhook 请求体:Standard Webhooks 的 `type`、`timestamp` 和 `data`。 */
export interface PaymentEvent {
  type: 'payment.succeeded' | 'payment.failed';
  timestamp: string;
  data: Payment;
}

客户端是一个围绕自有的 HttpClient 的小类,名字叫 payments:

src/payments/payments.client.ts
import { Injectable } from '@nestjs/common';
import { HttpClient, InjectHttpClient, toHttpException } from '@nestjs/http-client';
import type { Order } from '../database/schema.js';
import type { Payment } from './payment.js';

/** 支付服务商的 API:这家商店唯一需要的那次调用。 */
@Injectable()
export class PaymentsClient {
  constructor(@InjectHttpClient('payments') private readonly http: HttpClient) {}

  /** 订单的支付。对同一个订单再次调用,返回同一笔支付。 */
  async createPayment(order: Pick<Order, 'id' | 'total'>): Promise<Payment> {
    try {
      const { data } = await this.http.post<Payment>('/v1/payments', {
        json: { amount: order.total, currency: 'usd', reference: order.id },
        // 每个订单一个键:重试或第二次点击都无法创建第二笔支付。
        headers: { 'idempotency-key': order.id },
        // POST 默认不重试;有了这个键,重试是安全的。
        retry: { methods: ['POST'] },
      });
      return data;
    } catch (error) {
      // 服务商失败时为 502,未及时响应时为 504。
      throw toHttpException(error);
    }
  }
}
  • 幂等键就是订单的 id。 服务商已经创建支付之后发生的超时看起来像失败,于是客户端会重试,而顾客也可能点两次「Pay」。用同一个键,服务商返回它已经创建的那笔支付,而不是再创建一笔。一个订单,一笔支付。
  • 这个 POST 会重试。 HTTP 客户端默认不重试 POST,因为重复一次可能会扣两次钱(见 重试)。这个键让重试变得安全,所以本请求选择开启。
  • 错误会变成 502 或 504。 toHttpException() 把服务商出错变成 502 Bad Gateway、把服务商响应慢变成 504 Gateway Timeout,并记录日志,而不是变成 500(见 处理错误)。
  • data 不做校验。 类型参数描述的只是响应;运行时没有任何东西检查它。对于服务商有文档的 API 来说这可以接受,因为你是用自己的密钥调用它的。

服务会检查该订单属于该顾客、且仍是 placed,然后去问服务商:

src/payments/payments.service.ts
import { ConflictException, Injectable } from '@nestjs/common';
import { OrdersService } from '../orders/orders.service.js';
import { PaymentsClient } from './payments.client.js';

@Injectable()
export class PaymentsService {
  constructor(
    private readonly ordersService: OrdersService,
    private readonly paymentsClient: PaymentsClient,
  ) {}

  /** 开始为用户订单付款:把顾客送到哪里去支付。 */
  async start(userId: string, orderId: string) {
    const order = await this.ordersService.findOne(userId, orderId);
    if (order.status !== 'placed') {
      throw new ConflictException(`Order is ${order.status}`);
    }
    // 不在任何事务内:没有数据库连接在等服务商。
    const payment = await this.paymentsClient.createPayment(order);
    return { paymentId: payment.id, checkoutUrl: payment.checkoutUrl };
  }
}

对服务商的调用发生在任何数据库事务之外。一个等待别家公司 API 的事务会一直占着连接池里的一个连接和它的行锁,时长为服务商所需的时间。这次读取和这次调用不是原子的:顾客可能在其间取消订单。在这里这是无害的,因为支付只能通过 webhook 改变订单,而 webhook 会在改变订单的那条语句里再次检查状态。

src/payments/payments.controller.ts
import { Controller, HttpCode, Param, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import { PaymentsService } from './payments.service.js';

const orderId = { schema: z.uuid() };

@Controller('orders')
export class PaymentsController {
  constructor(private readonly paymentsService: PaymentsService) {}

  // 同一个订单总是得到同一笔支付,所以无论新旧都返回 200。
  @Can.Anyone()
  @Post(':id/payment')
  @HttpCode(200)
  start(@CurrentUser('id') userId: string, @Param('id', orderId) id: string) {
    return this.paymentsService.start(userId, id);
  }
}

支付模块注册这个客户端,带上 API 的 URL、作为 bearer 令牌的密钥,以及每次尝试的超时时间。它导入 OrdersModule,所以要在那个模块里加上 exports: [OrdersService](它的最终版本见 在提交之后宣告已支付的订单):

src/payments/payments.module.ts
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { HttpClientModule } from '@nestjs/http-client';
import type { Env } from '../config.js';
import { OrdersModule } from '../orders/orders.module.js';
import { PaymentWebhooksController } from './payment-webhooks.controller.js';
import { PaymentsClient } from './payments.client.js';
import { PaymentsController } from './payments.controller.js';
import { PaymentsService } from './payments.service.js';

@Module({
  imports: [
    OrdersModule,
    HttpClientModule.registerAsync({
      name: 'payments',
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        baseUrl: config.get('PAYMENTS_API_URL', { infer: true }),
        headers: { authorization: `Bearer ${config.get('PAYMENTS_API_KEY', { infer: true })}` },
        timeout: '10s',
      }),
    }),
  ],
  controllers: [PaymentsController, PaymentWebhooksController],
  providers: [PaymentsClient, PaymentsService],
})
export class PaymentsModule {}

服务商的密钥让它的重试变得安全。你自己的 POST /orders/:id/payment 也可以安全重试,因为第二次调用会返回同一笔支付。对于第二次调用会再次做某件事的路由——比如直接给已保存的银行卡扣款——就需要自己的幂等键,由客户端发送:@nestjs/idempotency 会让处理器对每个 Idempotency-Key 只运行一次,并用已存储的响应对答重试。它发布的是其存储的契约,而不是存储本身,所以在生产环境你要在自己的数据库上写一个,如 把键存在 PostgreSQL 中 所示。

接收服务商的 webhook

当顾客完成付款,或者卡被拒付时,服务商会发送一个 webhook:一个签名过的 POST,发到你在它控制台注册的 URL,这里是 https://<your API>/webhooks/payments。签名是事件 id、时间戳和请求体用共享密钥算出的 HMAC。校验它需要签名时那份原样的请求体,而不是请求体解析器由它构造出的对象,所以创建应用时要用 rawBody: true(见 原始请求体):

src/main.ts
// ...
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
  instrument: ObserveInstrument,
  // webhook 在服务商签名的那串字节上校验,而不是在重新序列化后的请求体上。
  rawBody: true,
  logger: new ConsoleLogger({
    // ...
  }),
});
// ...

根模块注册 outbox、它的存储,以及把服务商作为 接收方(receiver)的 webhooks 模块:

src/app.module.ts
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthorizationModule } from '@nestjs/authorization';
import { DrizzleModule, getDrizzleToken } from '@nestjs/drizzle';
import { createObserveModule } from '@nestjs/observe';
import { OutboxModule, OutboxStorage } from '@nestjs/outbox';
import { fromDrizzle, PostgresOutboxStore } from '@nestjs/outbox/postgres';
import { WebhooksModule } from '@nestjs/webhooks';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { envSchema, type Env } from './config.js';
import { CartModule } from './cart/cart.module.js';
import { HealthModule } from './health/health.module.js';
import { OrdersModule } from './orders/orders.module.js';
import { PaymentsModule } from './payments/payments.module.js';
import { ProductsModule } from './products/products.module.js';
import { UsersModule } from './users/users.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // 放在最前,这样它最后关闭,还能把其他模块做过的事发送出去。
    ObserveModule.forRoot({
      // 在 `npx @nestjs/observe link` 把密钥对写进 .env 之前为空:此时 SDK 什么也不发送。
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'shop-api',
    }),
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    AuthenticationModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        accessToken: {
          key: config.get('JWT_SECRET', { infer: true }),
          issuer: 'shop-api',
          audience: 'shop-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    // 放在 AuthenticationModule 之后:它的守卫要读取认证所设置的用户。
    AuthorizationModule.forRoot(),
    ThrottlerModule.forRoot([
      // 按 IP 地址,作用于每条路由。
      { name: 'default', ttl: minutes(1), limit: 100 },
      // 按邮箱和 IP 地址,作用于请求体指明某个账号的地方。
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
        getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
      },
    ]),
    // 在提交之后运行 order.paid,并保留用于去重 webhook 的收件箱。
    OutboxModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        relay: { enabled: config.get('OUTBOX_RELAY', { infer: true }) === 'on', pollInterval: '1s' },
      }),
    }),
    // 只接收 webhook:这家商店不发送任何 webhook,所以不需要 webhook 存储。
    WebhooksModule.forRootAsync({
      outgoing: false,
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        receivers: {
          // 服务商遵循 Standard Webhooks:webhook-id、webhook-timestamp、webhook-signature。
          payments: { scheme: 'standard', secret: config.get('PAYMENTS_WEBHOOK_SECRET', { infer: true }) },
        },
      }),
    }),
    UsersModule,
    AuthModule,
    ProductsModule,
    CartModule,
    OrdersModule,
    PaymentsModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
    {
      // outbox 消息和收件箱,放在商店自己的数据库里,用它们自己的 schema(nest_outbox)。
      provide: PostgresOutboxStore,
      inject: [getDrizzleToken(), OutboxStorage],
      useFactory: (db: NodePgDatabase, outboxStorage: OutboxStorage) =>
        new PostgresOutboxStore({ executor: fromDrizzle(db) }, outboxStorage),
    },
  ],
})
export class AppModule {}
  • outgoing: false。 @nestjs/webhooks 也能发送 webhook,配有端点、投递和用于它们的存储。这家商店只接收,所以这些一概不需要。
  • 接收方的名字 payments,就是路由装饰器里写的名字。scheme: 'standard' 会校验三个 webhook- 请求头、以常量时间比较签名,并检查签名中的时间戳在当前时间的五分钟之内,从而阻止被捕获的请求在之后被重放。
  • PostgresOutboxStore 把收件箱和 outbox 的消息存在商店自己的数据库里,放在它自己的 schema nest_outbox 中;当应用在开发和测试中启动时,它自己创建并迁移这个 schema。你的迁移不会创建它的表(见 把消息存进你的数据库)。

控制器:

src/payments/payment-webhooks.controller.ts
import { Controller, HttpCode, Logger, Post } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { ApiSecurity } from '@nestjs/swagger';
import { SkipThrottle } from '@nestjs/throttler';
import { IncomingWebhook, VerifyWebhook } from '@nestjs/webhooks';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { z } from 'zod';
import { OrdersService } from '../orders/orders.service.js';
import type { PaymentEvent } from './payment.js';

const orderId = z.uuid();

// 签名认证的是服务商,而不是某个令牌。而且服务商会从少数几个地址
// 成批投递:按 IP 的限制会拒绝它们。
@Public()
@ApiSecurity({})
@SkipThrottle()
@Controller('webhooks/payments')
export class PaymentWebhooksController {
  private readonly logger = new Logger(PaymentWebhooksController.name);

  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly ordersService: OrdersService,
  ) {}

  @Post()
  @HttpCode(200)
  @VerifyWebhook('payments')
  async receive(@IncomingWebhook() webhook: IncomingWebhook<PaymentEvent>) {
    const { type, data: payment } = webhook.payload;
    if (!orderId.safeParse(payment.reference).success) {
      // 不是这家商店创建的支付:返回 200,这样服务商不会重试它。
      this.logger.warn(`Ignoring ${type} for ${payment.id}: its reference isn't an order id`);
      return;
    }
    // 事件 id 与订单的新状态在同一个事务中记入收件箱:
    // 重投递,即便与本请求并发,也不会改变任何东西。
    await this.db.transaction(async (tx) =>
      webhook.processInTransaction(tx, () => {
        switch (type) {
          case 'payment.succeeded':
            return this.ordersService.markPaid(tx, payment);
          case 'payment.failed':
            return this.ordersService.cancelUnpaid(tx, payment.reference);
          default:
            // 其他类型会被记录,但不改变任何东西。
            return undefined;
        }
      }),
    );
  }
}
  • @VerifyWebhook('payments') 在处理器之前运行。签名与用密钥算出的不匹配的请求会拿到 401,处理器根本不会运行。响应不会说明哪里不对:伪造者从中什么也学不到。
  • @Public() 和 @SkipThrottle()。 JWT 教程里的全局守卫会向服务商要令牌,它按 IP 的限制会拒绝成批的投递。签名就是认证。
  • processInTransaction() 就是按事件 id 去重。它通过 tx 把 webhook 的 id 记入收件箱,然后仅当该 id 是新的才运行回调。这条记录与订单的改动一起提交,或者一起回滚。重投递——即便它在第一个实例仍在运行时落到另一个实例上——会发现该 id 已存在,什么也不改;控制器仍然返回 200,于是服务商停止重试。
  • @HttpCode(200)。 服务商会对任何非 2xx 的响应重试,持续数天。抛异常的处理器会回滚事务,连同那条记录一起,于是服务商的重试还能再有机会。
  • 与订单无关的事件同样会被应答。 reference 不是订单 id 的支付(比如同一个服务商账号下的另一个应用)会被记日志并返回 200;若放过去,它会在 uuid 比较处失败并返回 500,然后被重试数天。switch 不认识的事件类型会被记录,但不改变任何东西。

让订单恰好被标记为已支付一次

收件箱能拦住同一个事件的重投递。它拦不住关于同一个订单的两个不同事件:在顾客取消之后到达的 payment.succeeded、在成功之后到达的更早一次尝试的 payment.failed、为同一笔支付发送第二个事件的服务商。所以订单的改动也要是一次条件更新,正如电商教程里每一处状态变更那样。在 OrdersService 中,cancel() 和 ship() 有改动,markPaid()、cancelUnpaid()、cancelPlaced() 和 explainUnpaid() 是新增的,refuse() 的 409 现在会写出任意状态,例如 Order is placed;checkout()、findMine()、findOne() 和 items() 保持原样:

src/orders/orders.service.ts
import { ConflictException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { Outbox } from '@nestjs/outbox';
import { and, asc, desc, eq, gte, sql, type SQL } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import type { Transaction } from '../database/drizzle.js';
import { cartItems, orderItems, orders, products, type Order, type OrderItem } from '../database/schema.js';
import type { Payment } from '../payments/payment.js';

export type OrderWithItems = Order & { items: Omit<OrderItem, 'orderId'>[] };

@Injectable()
export class OrdersService {
  private readonly logger = new Logger(OrdersService.name);

  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly outbox: Outbox<Transaction>,
  ) {}

  // ...

  /** 订单所有者取消尚未支付的订单,其库存被归还。 */
  cancel(userId: string, id: string): Promise<Order> {
    return this.db.transaction(async (tx) => {
      const order = await this.cancelPlaced(tx, and(eq(orders.id, id), eq(orders.userId, userId)));
      return order ?? this.refuse(tx, id, userId);
    });
  }

  /** 服务商确认了这笔支付。在 webhook 的事务中运行。 */
  async markPaid(tx: Transaction, payment: Payment): Promise<Order | undefined> {
    // 有条件:只有 placed 状态、且金额相符的订单才会变成 paid。
    // 被重放的事件,或者针对已取消订单的事件,不会改变任何东西。
    const [order] = await tx
      .update(orders)
      .set({ status: 'paid', paymentId: payment.id })
      .where(and(eq(orders.id, payment.reference), eq(orders.status, 'placed'), eq(orders.total, payment.amount)))
      .returning();
    if (!order) {
      await this.explainUnpaid(tx, payment);
      return undefined;
    }
    // 与新状态一起提交,否则完全不提交:回滚掉的支付不会被任何人听说。
    await this.outbox.add(tx, {
      topic: 'order.paid',
      key: order.id,
      payload: { orderId: order.id, userId: order.userId, total: order.total, paymentId: payment.id },
    });
    return order;
  }

  /** 服务商表示支付失败:订单被取消,其库存被归还。 */
  cancelUnpaid(tx: Transaction, orderId: string): Promise<Order | undefined> {
    return this.cancelPlaced(tx, eq(orders.id, orderId));
  }

  /** 员工为已支付的订单发货。 */
  async ship(id: string): Promise<Order> {
    const [order] = await this.db
      .update(orders)
      .set({ status: 'shipped' })
      .where(and(eq(orders.id, id), eq(orders.status, 'paid')))
      .returning();
    return order ?? this.refuse(this.db, id);
  }

  /** 若订单仍是 placed 则取消它,并归还其库存,在调用方的事务中完成。 */
  private async cancelPlaced(tx: Transaction, where: SQL | undefined): Promise<Order | undefined> {
    // 有条件:当取消与支付为同一个订单竞争时,只有一方获胜。
    const [order] = await tx
      .update(orders)
      .set({ status: 'cancelled' })
      .where(and(where, eq(orders.status, 'placed')))
      .returning();
    if (!order) {
      return undefined;
    }
    for (const { productId, quantity } of await this.items(tx, order.id)) {
      await tx
        .update(products)
        .set({ stock: sql`${products.stock} + ${quantity}` })
        .where(eq(products.id, productId));
    }
    return order;
  }

  /** 记录某笔支付为何没有改变任何东西,除非它是同一笔支付的第二个事件。 */
  private async explainUnpaid(tx: Transaction, payment: Payment): Promise<void> {
    const [order] = await tx
      .select({ status: orders.status, total: orders.total, paymentId: orders.paymentId })
      .from(orders)
      .where(eq(orders.id, payment.reference));
    if (order?.paymentId === payment.id) {
      return;
    }
    // 为已取消订单支付的款项,或者金额不对的款项:这笔钱必须退回去。
    this.logger.warn(
      `Payment ${payment.id} of ${payment.amount} for order ${payment.reference} changed nothing ` +
        `(order ${order ? `${order.status}, total ${order.total}` : 'not found'}): refund it`,
    );
  }

  // ...

  /** 条件更新为何没有改变任何东西:订单不存在(或不属于本人)时 404,否则 409。 */
  private async refuse(db: Pick<NodePgDatabase, 'select'>, id: string, userId?: string): Promise<never> {
    const [order] = await db
      .select({ status: orders.status })
      .from(orders)
      .where(and(eq(orders.id, id), userId ? eq(orders.userId, userId) : undefined));
    if (!order) {
      throw new NotFoundException('Order not found');
    }
    throw new ConflictException(`Order is ${order.status}`);
  }
}
  • markPaid() 是一条 UPDATE,它的 WHERE 子句要求订单处于 placed、且支付的金额与其总额相符。已取消的订单保持已取消,已支付的保持已支付,而金额不对的支付什么也付不了。它之前没有读操作,所以不存在「检查与写入之间插进一次取消」的窗口。
  • 顾客的取消与服务商的支付在同一行上竞争,两者都以 placed 为条件。PostgreSQL 为第一条 UPDATE 锁住该行;第二条会等待,然后发现订单已不是 placed,于是什么也不改。恰好一方获胜,而且只有取消获胜时库存才会归还。
  • 没有改变任何东西的支付不是错误。 处理器正常返回,事件被记录下来,服务商拿到它的 200。如果返回 409,服务商就会为一个永远无法生效的事件重试数天。不过钱确实动了:explainUnpaid() 会记一条警告提示退款,除非该订单已经被这同一笔支付付过了。
  • payment.failed 会取消订单,用的是电商教程的取消逻辑,现在位于 cancelPlaced() 中,顾客的取消与 webhook 都在各自的事务里运行它:只有订单仍为 placed 时才会被取消,其库存在同一事务里归还。顾客的购物车在结账时就没了,所以他们要重新结账才能重试。
  • 顾客只能取消尚未支付的订单。 取消已支付的订单意味着通过服务商退款,本教程不涉及这一点。员工现在也只给 paid 的订单发货:为 placed 的订单发货是 409,Order is placed。

在提交之后宣告已支付的订单

商店的其他部分会对支付作出反应:一封确认邮件、仓库、财务。从 webhook 的处理器里发送这些,会有 outbox 一章 描述的问题:在提交之前发送,它们宣告的支付其事务可能还会回滚;在提交之后发送,如果进程在两者之间死掉,它们就丢了。markPaid() 通过 tx 往 outbox 里添加一条 order.paid 消息,于是这条消息与订单的新状态一起提交,而中继会在提交之后带着重试来投递它。它的处理器,用来代替那封确认邮件:

src/orders/order-paid.handler.ts
import { Injectable, Logger } from '@nestjs/common';
import { OnOutboxMessage } from '@nestjs/outbox';

export interface OrderPaid {
  orderId: string;
  userId: string;
  total: number;
  paymentId: string;
}

/** 在支付的事务提交之后运行:用来代替那封确认邮件。 */
@Injectable()
export class OrderPaidHandler {
  private readonly logger = new Logger(OrderPaidHandler.name);

  // 消费者的收件箱会跳过它已经处理过的消息。
  @OnOutboxMessage('order.paid', { consumer: 'order-paid-confirmation' })
  confirm({ orderId, total }: OrderPaid) {
    this.logger.log(`Order ${orderId} paid (${total} cents): sending the confirmation`);
  }
}

它的 consumer 有自己独立的收件箱,所以中继投递两次的消息只会被处理一次(见 在进程内处理 order.placed)。处理器会在 providers 上被发现,所以 OrdersModule 要注册它,并为支付模块导出 OrdersService:

src/orders/orders.module.ts
import { Module } from '@nestjs/common';
import { OrderPaidHandler } from './order-paid.handler.js';
import { OrderPolicy } from './order.policy.js';
import { OrdersController } from './orders.controller.js';
import { OrdersService } from './orders.service.js';

@Module({
  controllers: [OrdersController],
  providers: [OrdersService, OrderPolicy, OrderPaidHandler],
  exports: [OrdersService],
})
export class OrdersModule {}

试一试

假服务商是一个脚本,scripts/fake-payments-provider.ts。它按幂等键各创建一次支付,把支付保存在内存中,并扮演服务商的支付页面:向某笔支付的 checkoutUrl 发一个 POST 就是顾客在付款,而 ?outcome=failed 表示卡被拒付。然后它按 Standard Webhooks 规定的方式、用同一个密钥为事件签名,并发给商店。它还能用同一个 id 重投递一个事件,就像服务商在未能及时收到 2xx 时做的那样:

scripts/fake-payments-provider.ts
/**
 * 用来代替支付服务商,方便你在自己机器上试用这家商店。它不是服务商:
 * 它不收取任何费用,且把支付保存在内存中。
 *
 *   POST /v1/payments                          创建一笔支付,每个 Idempotency-Key 一次
 *   POST /checkout/:paymentId?outcome=failed   顾客付款(或者卡被拒付)
 *   POST /events/:eventId/resend               用同一个 id 再投递一次事件
 *
 * 它的 webhook 按 Standard Webhooks 规定的方式、用 PAYMENTS_WEBHOOK_SECRET 签名,
 * 并投递到 WEBHOOK_URL(默认 http://localhost:3000/webhooks/payments)。
 */
import { createHmac, randomUUID } from 'node:crypto';
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';

const port = Number(process.env.PROVIDER_PORT ?? 4000);
const webhookUrl = process.env.WEBHOOK_URL ?? 'http://localhost:3000/webhooks/payments';
const secret = process.env.PAYMENTS_WEBHOOK_SECRET ?? '';
if (!secret.startsWith('whsec_')) {
  throw new Error('Set PAYMENTS_WEBHOOK_SECRET to the secret the shop was started with');
}
// 密钥是 whsec_ 前缀之后的 base64 部分。
const key = Buffer.from(secret.slice('whsec_'.length), 'base64');

const payments = new Map<string, Record<string, unknown>>(); // 按幂等键
const events = new Map<string, string>(); // 事件 id 到请求体

/** 像服务商那样为一个事件签名并投递:对 `id.timestamp.body` 做 HMAC-SHA256。 */
async function deliver(id: string, body: string): Promise<number> {
  const timestamp = Math.floor(Date.now() / 1000);
  const signature = createHmac('sha256', key).update(`${id}.${timestamp}.${body}`).digest('base64');
  const response = await fetch(webhookUrl, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'webhook-id': id,
      'webhook-timestamp': String(timestamp),
      'webhook-signature': `v1,${signature}`,
    },
    body,
  });
  return response.status;
}

async function handle(req: IncomingMessage, res: ServerResponse): Promise<[number, unknown]> {
  const url = new URL(req.url ?? '/', `http://localhost:${port}`);
  const [, first, id, action] = url.pathname.split('/');

  if (req.method === 'POST' && url.pathname === '/v1/payments') {
    const idempotencyKey = req.headers['idempotency-key'];
    if (typeof idempotencyKey !== 'string' || !req.headers.authorization?.startsWith('Bearer ')) {
      return [400, { error: 'An API key and an Idempotency-Key are required' }];
    }
    let body = '';
    for await (const chunk of req) body += chunk;
    // 同一个键返回它第一次创建的那笔支付。
    if (!payments.has(idempotencyKey)) {
      const paymentId = `pay_${randomUUID().slice(0, 8)}`;
      const checkoutUrl = `http://localhost:${port}/checkout/${paymentId}`;
      payments.set(idempotencyKey, { id: paymentId, ...JSON.parse(body), status: 'requires_payment', checkoutUrl });
    }
    return [200, payments.get(idempotencyKey)];
  }

  if (req.method === 'POST' && first === 'checkout') {
    const payment = [...payments.values()].find((p) => p.id === id);
    if (!payment) {
      return [404, { error: 'No such payment' }];
    }
    payment.status = url.searchParams.get('outcome') === 'failed' ? 'failed' : 'succeeded';
    const eventId = `evt_${randomUUID().replaceAll('-', '').slice(0, 16)}`;
    const body = JSON.stringify({ type: `payment.${payment.status}`, timestamp: new Date().toISOString(), data: payment });
    events.set(eventId, body);
    return [200, { event: eventId, type: `payment.${payment.status}`, delivered: await deliver(eventId, body) }];
  }

  if (req.method === 'POST' && first === 'events' && action === 'resend') {
    const body = events.get(id);
    return body ? [200, { event: id, delivered: await deliver(id, body) }] : [404, { error: 'No such event' }];
  }
  return [404, { error: 'Not found' }];
}

createServer((req, res) => {
  handle(req, res).then(
    ([status, body]) => res.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body)),
    (error) => res.writeHead(500).end(String(error)),
  );
}).listen(port, () => console.log(`Fake payment provider on http://localhost:${port}`));

Node.js 会直接运行 TypeScript 文件(22.18 或更高版本)。--env-file 把商店的密钥交给它。该脚本位于 src/ 之外,所以 nest build 不会包含它:

$ node --env-file=.env scripts/fake-payments-provider.ts
Fake payment provider on http://localhost:4000

在另一个终端里用 npm run start 启动商店。启动时,outbox 的存储会创建它的 schema:

LOG [OutboxModule] OutboxStorage: PostgresOutboxStore
LOG [OutboxModule] PostgresOutboxStore: migrated schema "nest_outbox" to version 1.

和电商教程一样,以 Ada 和 Sam 的身份登录(Sam 是员工),往目录里加一个键盘,然后结账买两个(此处及下文的令牌和请求体都做了缩写):

$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"...","expiresIn":900}
$ ADA="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ SAM="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ curl localhost:3000/products -H "$SAM" --json '{"name":"Mechanical keyboard","description":"Hot-swappable switches","price":12900,"stock":5}'
{"id":"dd947855-c8cd-4321-bec7-eb66d8f5f9c2","name":"Mechanical keyboard",...,"stock":5,...}
$ curl -X PUT localhost:3000/cart/items/dd947855-c8cd-4321-bec7-eb66d8f5f9c2 -H "$ADA" --json '{"quantity":2}'
$ curl -X POST localhost:3000/orders -H "$ADA"
{"id":"2145ea60-1156-47f1-b304-ffaa33582c34","userId":"884ebd52-aec8-4eec-b7db-6a3bb7623f36","status":"placed","total":25800,"paymentId":null,"createdAt":"2026-11-19T22:38:15.908Z","items":[...]}

请求支付。第二次调用——比如超时后的重试——会得到同一笔支付,因为服务商收到的是同一个幂等键。员工现在还无法给订单发货,因为它尚未支付:

$ curl -X POST localhost:3000/orders/2145ea60-1156-47f1-b304-ffaa33582c34/payment -H "$ADA"
{"paymentId":"pay_27a152e7","checkoutUrl":"http://localhost:4000/checkout/pay_27a152e7"}
$ curl -X POST localhost:3000/orders/2145ea60-1156-47f1-b304-ffaa33582c34/payment -H "$ADA"
{"paymentId":"pay_27a152e7","checkoutUrl":"http://localhost:4000/checkout/pay_27a152e7"}
$ curl -X POST localhost:3000/orders/2145ea60-1156-47f1-b304-ffaa33582c34/ship -H "$SAM"
{"message":"Order is placed","error":"Conflict","statusCode":409}

顾客在服务商的页面上付款。假服务商应答它发出的事件,以及商店对它的应答状态。订单已支付,所以员工可以发货,而确认消息是在提交之后发出的:

$ curl -X POST localhost:4000/checkout/pay_27a152e7
{"event":"evt_a194bac0079a448a","type":"payment.succeeded","delivered":200}
$ curl localhost:3000/orders/2145ea60-1156-47f1-b304-ffaa33582c34 -H "$ADA"
{"id":"2145ea60-1156-47f1-b304-ffaa33582c34",...,"status":"paid","total":25800,"paymentId":"pay_27a152e7",...}
$ curl -X POST localhost:3000/orders/2145ea60-1156-47f1-b304-ffaa33582c34/ship -H "$SAM"
{"id":"2145ea60-1156-47f1-b304-ffaa33582c34",...,"status":"shipped","total":25800,"paymentId":"pay_27a152e7",...}

应用的日志显示确认消息发了出去:

LOG [OrderPaidHandler] Order 2145ea60-1156-47f1-b304-ffaa33582c34 paid (25800 cents): sending the confirmation

服务商再次投递该事件:商店返回 200,什么也没改变。用密钥之外的任何东西签名的请求是 401:

$ curl -X POST localhost:4000/events/evt_a194bac0079a448a/resend
{"event":"evt_a194bac0079a448a","delivered":200}
$ curl localhost:3000/orders/2145ea60-1156-47f1-b304-ffaa33582c34 -H "$ADA"
{"id":"2145ea60-1156-47f1-b304-ffaa33582c34",...,"status":"shipped",...}
$ curl -i localhost:3000/webhooks/payments -H 'webhook-id: evt_forged' -H "webhook-timestamp: $(date +%s)" -H 'webhook-signature: v1,Zm9yZ2Vk' \
    --json '{"type":"payment.succeeded","timestamp":"2026-11-19T22:30:00.000Z","data":{"id":"pay_forged","amount":25800,...}}'
HTTP/1.1 401 Unauthorized
{"message":"Webhook signature verification failed","error":"Unauthorized","statusCode":401}

卡被拒付会取消订单并归还其库存:第一单之后还剩三个键盘,第二单拿走了一个,而拒付把它还了回来。如果顾客随后在服务商的页面上再试一次并且支付成功,那个迟到的 payment.succeeded 不会把订单救回来,而商店会记录它欠下的退款:

$ curl -X PUT localhost:3000/cart/items/dd947855-c8cd-4321-bec7-eb66d8f5f9c2 -H "$ADA" --json '{"quantity":1}'
$ curl -X POST localhost:3000/orders -H "$ADA"
{"id":"20b90e94-af9e-4d41-8bca-e3449dc13deb",...,"status":"placed","total":12900,...}
$ curl -X POST localhost:3000/orders/20b90e94-af9e-4d41-8bca-e3449dc13deb/payment -H "$ADA"
{"paymentId":"pay_07c5a5e9","checkoutUrl":"http://localhost:4000/checkout/pay_07c5a5e9"}
$ curl -X POST "localhost:4000/checkout/pay_07c5a5e9?outcome=failed"
{"event":"evt_464c1af968bd4fc8","type":"payment.failed","delivered":200}
$ curl localhost:3000/orders/20b90e94-af9e-4d41-8bca-e3449dc13deb -H "$ADA"
{"id":"20b90e94-af9e-4d41-8bca-e3449dc13deb",...,"status":"cancelled","total":12900,"paymentId":null,...}
$ curl localhost:3000/products/dd947855-c8cd-4321-bec7-eb66d8f5f9c2
{"id":"dd947855-c8cd-4321-bec7-eb66d8f5f9c2","name":"Mechanical keyboard",...,"stock":3,...}
$ curl -X POST localhost:4000/checkout/pay_07c5a5e9
{"event":"evt_95f96f70f1e1419c","type":"payment.succeeded","delivered":200}
$ curl localhost:3000/orders/20b90e94-af9e-4d41-8bca-e3449dc13deb -H "$ADA"
{"id":"20b90e94-af9e-4d41-8bca-e3449dc13deb",...,"status":"cancelled","total":12900,"paymentId":null,...}

日志把这次迟到的成功标记为需要退款,而订单保持已取消:

WARN [OrdersService] Payment pay_07c5a5e9 of 12900 for order 20b90e94-af9e-4d41-8bca-e3449dc13deb changed nothing (order cancelled, total 12900): refund it

停掉假服务商,再请求支付,就会在客户端三次尝试都失败后得到 502,原因在日志里,而不在响应里:

$ curl -X PUT localhost:3000/cart/items/dd947855-c8cd-4321-bec7-eb66d8f5f9c2 -H "$ADA" --json '{"quantity":1}'
$ curl -X POST localhost:3000/orders -H "$ADA"
{"id":"f43ba16e-fd3e-4f4e-ba12-bcff19c3c3bb",...,"status":"placed","total":12900,...}
$ curl -X POST localhost:3000/orders/f43ba16e-fd3e-4f4e-ba12-bcff19c3c3bb/payment -H "$ADA"
{"message":"Bad Gateway","statusCode":502}

日志里记录了客户端放弃的原因:

ERROR [HttpClient] POST http://localhost:4000/v1/payments failed: ECONNREFUSED; answering 502 Bad Gateway

测试它

测试扮演服务商:它们用 @nestjs/webhooks/testing 的 signWebhook() 为每个 webhook 签名,该函数会产出 Standard Webhooks 发送方会产出的请求体和请求头,用的是应用所持有的密钥。服务商的 API 是一个桩化的 fetch,所以测试能检查商店向它发送了什么,而商店永远不会碰到网络。和电商教程一样,它们通过连接池针对真实的 PostgreSQL 服务器运行,因为事件的两份副本与顾客的取消只有在那里才会真正竞争。把支付相关设置加进测试运行所用的环境:

vitest.config.e2e.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    env: {
      DATABASE_URL: 'postgres://unused-in-tests',
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
      // 永远不会被调用:测试会桩化 fetch。
      PAYMENTS_API_URL: 'https://payments.invalid',
      PAYMENTS_API_KEY: 'test-only-key',
      PAYMENTS_WEBHOOK_SECRET: 'whsec_dGVzdC1vbmx5LXdlYmhvb2stc2VjcmV0LTMyLWJ5dGVz',
      // 测试自己运行 outbox 中继。
      OUTBOX_RELAY: 'off',
    },
  },
});

测试覆盖幂等键、服务商宕机、签名与伪造的 webhook、两个实例上的重复、金额错误,以及支付与取消的竞争:

test/payments.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { OutboxRelay } from '@nestjs/outbox';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { signWebhook } from '@nestjs/webhooks/testing';
import { eq, sql } from 'drizzle-orm';
import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { AppModule } from '../src/app.module.js';
import { orders, products, users } from '../src/database/schema.js';
import { OrderPaidHandler } from '../src/orders/order-paid.handler.js';
import { OrdersService } from '../src/orders/orders.service.js';
import type { PaymentEvent } from '../src/payments/payment.js';

// 真实的 PostgreSQL 加连接池,这样重投递与取消会真正竞争。
const url = process.env.TEST_DATABASE_URL;

describe.skipIf(!url)('Payments (e2e)', () => {
  const db = drizzle({ client: new Pool({ connectionString: url, max: 20 }) });
  // 服务商的 API:商店对它的每次调用都落在这里。
  const fetch = vi.fn<typeof globalThis.fetch>();
  let app: NestNodeApplication;
  let other: NestNodeApplication; // API 的第二个实例,在自己的连接池上
  let relay: OutboxRelay;

  async function createApp(database: NodePgDatabase) {
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(database) // outbox 的存储也跑在它上面
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    return moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter(), { rawBody: true }).init();
  }

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    await db.execute(sql`TRUNCATE users, products, refresh_tokens CASCADE`);
    vi.stubGlobal('fetch', fetch);
    app = await createApp(db);
    other = await createApp(drizzle({ client: new Pool({ connectionString: url, max: 10 }) }));
    relay = app.get(OutboxRelay);
  });

  afterAll(async () => {
    vi.unstubAllGlobals();
    await other.close();
    await app.close(); // 也会关闭连接池
  });

  let clients = 0;

  async function signUp(email: string) {
    const res = await app.inject({
      method: 'POST',
      url: '/auth/sign-up',
      payload: { email, password: 'correct horse battery' },
      remoteAddress: `10.0.1.${++clients}`,
    });
    return { authorization: `Bearer ${res.json<{ accessToken: string }>().accessToken}` };
  }

  /** 一个 placed 状态的订单,包含某个库存为 5 的商品的 2 件。 */
  async function placeOrder() {
    const [product] = await db.insert(products).values({ name: 'Keycaps', description: '', price: 9900, stock: 5 }).returning();
    const headers = await signUp(`buyer-${crypto.randomUUID()}@example.com`);
    await app.inject({ method: 'PUT', url: `/cart/items/${product.id}`, headers, payload: { quantity: 2 } });
    const order = (await app.inject({ method: 'POST', url: '/orders', headers })).json<{ id: string; total: number }>();
    return { ...order, productId: product.id, headers };
  }

  /** 服务商发送的请求:Standard Webhooks,用共享密钥签名。 */
  function event(type: PaymentEvent['type'], order: { id: string; total: number }, secret = process.env.PAYMENTS_WEBHOOK_SECRET!) {
    const data = {
      id: `pay_${order.id.slice(0, 8)}`,
      amount: order.total,
      currency: 'usd',
      reference: order.id,
      status: type === 'payment.succeeded' ? 'succeeded' : 'failed',
      checkoutUrl: 'https://payments.invalid/checkout',
    };
    return signWebhook({ scheme: 'standard', secret, payload: { type, timestamp: new Date().toISOString(), data } });
  }

  const deliver = ({ headers, body }: { headers: Record<string, string>; body: string }, to = app) =>
    to.inject({ method: 'POST', url: '/webhooks/payments', headers, payload: body });

  const statusOf = async (id: string) =>
    (await db.select({ status: orders.status }).from(orders).where(eq(orders.id, id)))[0].status;
  const stockOf = async (id: string) =>
    (await db.select({ stock: products.stock }).from(products).where(eq(products.id, id)))[0].stock;

  it('creates the payment with the order id as the idempotency key, retries included', async () => {
    const order = await placeOrder();
    const payment = { id: 'pay_1', checkoutUrl: 'https://payments.invalid/checkout/pay_1' };
    fetch
      .mockReset()
      .mockResolvedValueOnce(new Response(null, { status: 503 })) // 服务商打了个嗝:会被重试
      .mockResolvedValueOnce(Response.json(payment))
      .mockResolvedValueOnce(Response.json(payment));

    const first = await app.inject({ method: 'POST', url: `/orders/${order.id}/payment`, headers: order.headers });
    const second = await app.inject({ method: 'POST', url: `/orders/${order.id}/payment`, headers: order.headers });

    expect(first.json()).toEqual({ paymentId: 'pay_1', checkoutUrl: payment.checkoutUrl });
    expect(second.json()).toEqual(first.json());
    expect(fetch).toHaveBeenCalledTimes(3);
    for (const [input, init] of fetch.mock.calls) {
      expect(String(input)).toBe('https://payments.invalid/v1/payments');
      expect(new Headers(init?.headers).get('idempotency-key')).toBe(order.id);
      expect(JSON.parse(String(init?.body))).toEqual({ amount: order.total, currency: 'usd', reference: order.id });
    }
  });

  it('answers 502 when the provider is down', async () => {
    const order = await placeOrder();
    fetch.mockReset().mockRejectedValue(new TypeError('fetch failed'));

    const res = await app.inject({ method: 'POST', url: `/orders/${order.id}/payment`, headers: order.headers });

    expect(res.statusCode).toBe(502);
  });

  it('marks the order paid when a signed payment.succeeded arrives', async () => {
    const order = await placeOrder();
    const confirm = vi.spyOn(app.get(OrderPaidHandler), 'confirm');

    const res = await deliver(event('payment.succeeded', order));

    expect(res.statusCode).toBe(200);
    expect(await statusOf(order.id)).toBe('paid');
    await relay.runOnce(); // order.paid 在提交之后发出
    expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ orderId: order.id }), expect.anything());
  });

  it('rejects a webhook that the provider did not sign', async () => {
    const order = await placeOrder();

    const res = await deliver(event('payment.succeeded', order, 'whsec_c29tZW9uZS1lbHNlcy1zZWNyZXQtb2YtMzItYnl0ZXM='));

    expect(res.statusCode).toBe(401);
    expect(await statusOf(order.id)).toBe('placed');
  });

  it('processes an event once, even when two instances receive it at the same time', async () => {
    const order = await placeOrder();
    const confirm = vi.spyOn(app.get(OrderPaidHandler), 'confirm').mockClear();
    const markPaid = [app, other].map((instance) => vi.spyOn(instance.get(OrdersService), 'markPaid'));
    const paid = event('payment.succeeded', order);

    const results = await Promise.all([deliver(paid, app), deliver(paid, other)]);

    expect(results.map((res) => res.statusCode)).toEqual([200, 200]);
    expect(await statusOf(order.id)).toBe('paid');
    // 订单事务里的收件箱记录,拦住了另一份副本。
    expect(markPaid[0].mock.calls.length + markPaid[1].mock.calls.length).toBe(1);
    await relay.runOnce();
    expect(confirm).toHaveBeenCalledTimes(1);
  });

  it('pays nothing for the wrong amount, or for a payment that is not for an order', async () => {
    const order = await placeOrder();

    const wrongAmount = await deliver(event('payment.succeeded', { ...order, total: order.total - 1 }));
    const notAnOrder = await deliver(event('payment.succeeded', { ...order, id: 'invoice-2041' }));

    expect([wrongAmount.statusCode, notAnOrder.statusCode]).toEqual([200, 200]);
    expect(await statusOf(order.id)).toBe('placed');
  });

  it('never brings a cancelled order back', async () => {
    const order = await placeOrder();
    await app.inject({ method: 'POST', url: `/orders/${order.id}/cancel`, headers: order.headers });

    const res = await deliver(event('payment.succeeded', order));

    expect(res.statusCode).toBe(200); // 重试也改变不了什么:没有重试的意义
    expect(await statusOf(order.id)).toBe('cancelled');
    expect(await stockOf(order.productId)).toBe(5);
  });

  it('cancels the order and puts its stock back when the payment fails', async () => {
    const order = await placeOrder();
    expect(await stockOf(order.productId)).toBe(3);

    await deliver(event('payment.failed', order));

    expect(await statusOf(order.id)).toBe('cancelled');
    expect(await stockOf(order.productId)).toBe(5);
  });

  it('lets a payment or a cancel win, never both', async () => {
    const order = await placeOrder();

    await Promise.all([
      deliver(event('payment.succeeded', order)),
      app.inject({ method: 'POST', url: `/orders/${order.id}/cancel`, headers: order.headers }),
    ]);

    const status = await statusOf(order.id);
    expect(['paid', 'cancelled']).toContain(status);
    expect(await stockOf(order.productId)).toBe(status === 'paid' ? 3 : 5);
  });
});
  • 每个事件都会得到一个新的 id。 signWebhook() 每次调用都会生成一个。收件箱位于 nest_outbox,对商店各表做 TRUNCATE 不会清空它,所以固定 id 会在第一次运行时通过,之后每次运行都被当作重复而跳过。
  • 401 来自签名校验。 同一个请求带上正确的密钥,在它前一个测试里会拿到 200,所以这条路由不是因为缺少令牌才拒绝的。
  • 中继在测试要求时才运行。 在 OUTBOX_RELAY=off 时,relay.runOnce() 投递已提交的 order.paid 消息,而 spy 统计处理器的调用次数。
  • API 的两个实例在同一时刻收到同一个签名请求,各自在自己的连接池上,就像负载均衡器后面的两个 pod。其中一个记录 id 并为订单付款;另一个的收件箱插入会等待那个事务,然后发现该 id 已存在,因此 markPaid() 总共只运行一次。
  • 服务商的 API 应答一次 503。 客户端用同一个幂等键重试这个 POST,顾客最终拿到了支付:两个请求一共向服务商发了三次调用,每一次都以订单的 id 作为键。

用电商教程的那套命令来运行它们,一个文件接一个文件,因为它们会清空同一批表:

$ TEST_DATABASE_URL=postgres://postgres:shop@localhost:5432/shop_test npm run test:e2e -- --no-file-parallelism

 Test Files  3 passed (3)
      Tests  18 passed (18)

从 markPaid() 里删掉 eq(orders.status, 'placed'),「never brings a cancelled order back」和「lets a payment or a cancel win, never both」就会失败:迟到的支付把已取消的订单复活了,而它的库存却已经还了回去。绕过 processInTransaction() 直接调用 markPaid(),双实例测试就会失败:两个实例都会运行它。

切换到真实服务商

本教程模拟了什么,以及换上真实服务商后会有哪些变化:

  • API。 把 PaymentsClient.createPayment() 换成你的服务商的创建支付调用(或它的 SDK),并继续用订单的 id 作为它的幂等键。服务商只在有限时间内保留键,有些还会拒绝用不同参数复用同一个键:先确认你的服务商是怎么做的。先用它的测试密钥在测试模式下跑通,再用正式密钥。
  • webhook。 对于遵循 Standard Webhooks 的服务商,接收方保持原样:只有密钥,以及载荷类型和它的事件名需要改。Stripe 用自己的方案签名,同一个模块可用 scheme: 'stripe' 且不设 header 来校验;此时事件的 id 就是载荷里的 id(见 接收运营商的类 Stripe webhook)。在控制器里把服务商的事件映射到 markPaid() 和 cancelUnpaid()。
  • URL。 在服务商的控制台里注册 https://<your API>/webhooks/payments。在你自己的机器上,用服务商的命令行工具或一条隧道把它的 webhook 转发到 localhost。

生产环境检查清单

电商教程 检查清单 里的每一条都适用。就支付而言,还需要特别注意:

  • 只相信 webhook。 浏览器从服务商的页面返回什么也证明不了:任何人都能打开那个 URL。订单是在签名过的 payment.succeeded 到达时才变为已支付,而成功页面读取的是订单的状态。
  • 保留 rawBody: true,并把密钥放进你平台的密钥存储。 当服务商轮换密钥时,给接收方同时配置两个,在其 secret 选项中用数组:每一个都会被尝试。
  • 退款那些没有改变任何东西的支付。 为已取消订单支付的款项会被记上 refund it。对这个警告设告警,或者在处理器里通过服务商的 API 按支付的 id 发起退款。
  • 让未支付的订单过期。 一个 placed 订单会占着它的库存,直到被支付或被取消。把那些过了一小时(比如)仍未支付的订单取消掉:用一个 cron 任务 对每个订单调用 cancelUnpaid(),并加 锁 以确保只有一个实例在运行它。
  • 在部署之前应用 outbox 的迁移,用 npx @nestjs/outbox migrate,与 npx drizzle-kit migrate 并列执行。当 NODE_ENV=production 时,存储在启动时不会自行迁移。
  • 清理收件箱,用 cron 任务调用 OutboxInbox.prune(),时间窗口要长于服务商的重试计划(Stripe 会重试三天)。如果某个重投递在其 id 被清理之后才到达,处理器会再运行一次,此时只有条件更新能拦住它。
  • 让处理器保持简短。 服务商在等待应答,并且会超时。任何慢操作都属于 outbox 处理器,放在提交之后。
  • 给生产环境单独准备 Observe 密钥对,从项目的 API Keys 页面获取,在平台的环境变量里设为 OBSERVE_APP_KEY 和 OBSERVE_APP_SECRET:start:prod 不会加载 .env。然后就能在链路追踪里看到服务商:NestJS Observe 会为每个请求记录一条由各 span 组成的追踪,对服务商 API 的调用会作为出站请求出现在发起它的方法之下,所以服务商变慢会在 POST /orders/:id/payment 的追踪中显现(见 查询、出站调用与被捕获的请求)。

接下来做什么

  • 为已支付的订单退款,并连同退款一起取消它们:在 PaymentsClient 里再加一次调用,用支付的 id 作为它的幂等键,并在控制器里加一个 payment.refunded 事件。
  • 从 order.paid 处理器真正发出确认邮件:邮件。
  • 订单支付后通知合作伙伴,用你自己的签名 webhook:Webhooks。
  • 用幂等键让其他端点也能安全重试:幂等键。
  • 在生产环境中逐个请求地观察支付流程:可观测性。