Skip to main content
API Gateway Blueprint 会为你的服务处理的每次 API 调用向 Dodo Payments 发送 usage event,而 Count meter 会将这些事件转换为针对每位客户的按调用计费。你可以使用它跟踪 API endpoint 使用情况、为 rate limit 提供依据,并为 API 使用量计费。它包含在 @dodopayments/ingestion-blueprints npm package 中,其中 trackAPICall() 每次调用发送一个事件,createBatch() 则会在请求量较高时将事件加入队列。

使用场景

API Gateway Blueprint 适用于以下场景:

API-as-a-Service

在 API platform 上跟踪每位客户的调用次数,并按调用次数计费。

Rate Limiting

记录每位客户的调用量,为基于使用量的 rate limit 提供依据。该 blueprint 会记录使用量,但不会强制执行限制。

Performance Monitoring

在每个事件中记录响应时间和 status code,使错误率数据与计费数据并列显示。

Multi-Tenant SaaS

根据客户在不同 endpoint 上的 API 使用量向其计费。
每个事件都需要你向其计费的客户对应的 Dodo Payments customer ID,该 ID 以 cus_ 开头。创建客户时,将其与用户记录一同存储,并将其作为 customerId 传入。

快速开始

要跟踪 API 调用,请安装 package、创建 meter,并为每次调用发送一个事件。
1

Install the SDK

安装 Dodo Payments Ingestion Blueprints package:
2

Get Your API Keys

在 Dodo Payments dashboard 中,进入 Developer → API Keys,创建一个 Dodo Payments API key,并将其存储在 DODO_PAYMENTS_API_KEY environment variable 中。开发过程中请使用 test mode key。test mode key 只能与 test_mode 搭配使用。
3

Create a Meter

在 Dodo Payments dashboard 中,进入 Products → Meters,然后点击 Create Meter。设置以下字段:
  • Meter Name:描述性名称,例如 API Calls。
  • Event Name:api_call,或你选择的名称。它必须与代码中的 eventName 完全匹配(区分大小写)。
  • Aggregation Type:选择 Count,按调用次数计费。
  • Measurement Unit:发票上显示的单位,例如 calls。
如果只统计部分调用,请启用 Enable Event Filtering,并针对 endpoint、method 或 status_code 等 metadata key 添加条件。
4

Track API Calls

使用你的 API key 和 event name 创建一个 Ingestion 实例,然后选择一种模式:每次调用发送一个事件、针对高流量进行批处理,或使用 Express.js middleware 跟踪每个 request。在 middleware 中,req.user 来自你的 authentication middleware,其 id 必须是 Dodo Payments customer ID。没有已登录用户的 request 会使用 customer ID anonymous 发送,该 ID 与任何客户都不匹配。

配置

Ingestion 配置

将以下选项传递给 new Ingestion():
string
必填
来自 dashboard 的 Dodo Payments API key。
string
Environment mode:test_mode 或 live_mode。默认为 test_mode。但 Dodo Payments SDK 默认使用 live_mode,因此请在 production 中显式设置 live_mode。
string
必填
与 meter 的 Event Name 匹配的 event name(区分大小写)。此实例发送的每个事件都会使用该名称。

跟踪 API 调用选项

将以下选项传递给 trackAPICall() 和 batch.add():
string
必填
为该调用计费的 Dodo Payments customer ID,例如 cus_123。
object
有关 API 调用的可选 metadata,例如 endpoint、method、status code 和 response time。每个值都必须是 string、number 或 boolean。API 不接受嵌套对象、array 和 null 值。

Batch 配置

createBatch(ingestion, options) 会将事件加入内存队列,并返回一个包含三个 method 的对象:add() 将事件加入队列,flush() 发送队列中的事件,cleanup() 发送这些事件并停止 timer。一次 flush 会并行地为每个事件发送一个 ingest request。
number
触发立即 flush 的队列事件数量。默认值:100。
number
在最近一次 add() 后等待的毫秒数,等待结束后 batch 会执行 flush。每次 add() 都会重新启动 timer。默认值:5000(5 秒)。

最佳实践

高流量场景使用批处理:对于高流量应用,请使用 createBatch()。batch.add() 会立即返回,因此跟踪不会增加请求处理程序的延迟。
batch 会将事件保存在内存中,直到执行 flush,并且不会重试发送失败的事件。自动 flush 会使用 console.error 记录错误。调用 flush() 或 cleanup() 时会抛出该错误。
关闭时清理 Batch:应用关闭时调用 batch.cleanup(),以便 flush 待处理事件,避免其丢失。
最后修改于 2026年9月26日