跳转到主要内容

Documentation Index

Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt

Use this file to discover all available pages before exploring further.

TypeScript SDK 提供了方便的服务器端访问 Dodo Payments REST API,适用于 TypeScript 和 JavaScript 应用程序。它具有全面的类型定义、错误处理、重试、超时和自动分页功能,以实现无缝的支付处理。

安装

使用你选择的包管理器安装 SDK:
npm install dodopayments

快速开始

使用您的 API 密钥初始化客户端并开始处理支付:
import DodoPayments from 'dodopayments';

const client = new DodoPayments({
  bearerToken: process.env['DODO_PAYMENTS_API_KEY'], // This is the default and can be omitted
  environment: 'test_mode', // defaults to 'live_mode'
});

const checkoutSessionResponse = await client.checkoutSessions.create({
  product_cart: [{ product_id: 'product_id', quantity: 1 }],
});

console.log(checkoutSessionResponse.session_id);
始终使用环境变量安全地存储你的 API 密钥。切勿将它们提交到版本控制或在客户端代码中暴露。

核心功能

TypeScript First

提供对所有 API 端点的全面类型定义的完整 TypeScript 支持

Auto-Pagination

自动分页处理列表响应,让处理大量数据集变得轻松无忧

Error Handling

内置错误类型带有针对不同失败场景的详细消息

Smart Retries

可配置的自动重试,针对瞬态错误提供指数退避策略

配置

环境变量

设置环境变量以进行安全配置:
.env
DODO_PAYMENTS_API_KEY=your_api_key_here

超时配置

全局或按请求配置请求超时:
// Configure default timeout for all requests (default is 1 minute)
const client = new DodoPayments({
  timeout: 20 * 1000, // 20 seconds
});

// Override per-request
await client.checkoutSessions.create(
  { product_cart: [{ product_id: 'product_id', quantity: 1 }] },
  { timeout: 5 * 1000 },
);

重试配置

配置自动重试行为:
// Configure default for all requests (default is 2 retries)
const client = new DodoPayments({
  maxRetries: 0, // disable retries
});

// Override per-request
await client.checkoutSessions.create(
  { product_cart: [{ product_id: 'product_id', quantity: 1 }] },
  { maxRetries: 5 },
);
SDK 会自动对因网络错误或服务器问题(5xx 响应)而失败的请求进行指数退避重试。

常见操作

创建结账会话

生成结账会话以收集支付信息:
const session = await client.checkoutSessions.create({
  product_cart: [
    {
      product_id: 'prod_123',
      quantity: 1
    }
  ],
  return_url: 'https://yourdomain.com/return'
});

console.log('Redirect to:', session.url);

管理客户

创建和检索客户信息:
// Create a customer
const customer = await client.customers.create({
  email: 'customer@example.com',
  name: 'John Doe',
  metadata: {
    user_id: '12345'
  }
});

// Retrieve customer
const retrieved = await client.customers.retrieve('cus_123');
console.log(`Customer: ${retrieved.name} (${retrieved.email})`);

处理订阅

创建和管理定期订阅:
// Create a subscription
const subscription = await client.subscriptions.create({
  billing: {
    country: 'US',
    city: 'San Francisco',
    state: 'CA',
    street: '1 Market St',
    zipcode: '94105',
  },
  customer: {
    customer_id: 'cus_123', // or pass { email, name } to create a new customer
  },
  product_id: 'pdt_456',
  quantity: 1,
});

// Charge an on-demand subscription
// product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
const chargeResponse = await client.subscriptions.charge(subscription.subscription_id, {
  product_price: 2500,
});

// Retrieve subscription usage history (for metered subscriptions)
const usageHistory = await client.subscriptions.retrieveUsageHistory(subscription.subscription_id, {
  start_date: '2024-01-01T00:00:00Z',
  end_date: '2024-03-31T23:59:59Z',
});
billing 至少需要使用两位的 ISO 国家代码。customer 是一个联合,由 { customer_id }(用于关联现有客户)或 { email, name? }(用于创建新客户)组成。product_price 以最低货币单位表示。

基于使用量的计费

收集使用事件

跟踪基于使用量计费的自定义事件:
await client.usageEvents.ingest({
  events: [
    {
      event_id: 'api_call_12345',
      customer_id: 'cus_abc123',
      event_name: 'api_request',
      timestamp: '2024-01-15T10:30:00Z',
      metadata: {
        endpoint: '/api/v1/users',
        method: 'GET',
        tokens_used: '150'
      }
    }
  ]
});
事件必须拥有唯一的 event_id 值以确保幂等性。同一请求中的重复 ID 将被拒绝,后续请求中的现有 ID 将被忽略。

检索使用事件

获取使用事件的详细信息:
// Get a specific event
const event = await client.usageEvents.retrieve('api_call_12345');

// List events with filtering
const events = await client.usageEvents.list({
  customer_id: 'cus_abc123',
  event_name: 'api_request',
  start: '2024-01-14T10:30:00Z',
  end: '2024-01-15T10:30:00Z'
});

代理配置

为不同的运行时配置代理设置:

Node.js(使用 undici)

import DodoPayments from 'dodopayments';
import * as undici from 'undici';

const proxyAgent = new undici.ProxyAgent('http://localhost:8888');
const client = new DodoPayments({
  fetchOptions: {
    dispatcher: proxyAgent,
  },
});

Bun

import DodoPayments from 'dodopayments';

const client = new DodoPayments({
  fetchOptions: {
    proxy: 'http://localhost:8888',
  },
});

Deno

import DodoPayments from 'npm:dodopayments';

const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });
const client = new DodoPayments({
  fetchOptions: {
    client: httpClient,
  },
});

日志记录

使用环境变量或客户端选项控制日志的详细程度:
// Via client option
const client = new DodoPayments({
  logLevel: 'debug', // Show all log messages
});
# Via environment variable
export DODO_PAYMENTS_LOG=debug
可用的日志级别:
  • 'debug' - 显示调试消息、信息、警告和错误
  • 'info' - 显示信息消息、警告和错误
  • 'warn' - 显示警告和错误(默认)
  • 'error' - 仅显示错误
  • 'off' - 禁用所有日志记录
在调试级别,所有 HTTP 请求和响应都被记录,包括头和主体。一些身份验证头被编辑掉,但主体中的敏感数据可能仍然可见。

从 Node.js SDK 迁移

如果您正在从遗留的 Node.js SDK 升级,TypeScript SDK 提供了改进的类型安全性和功能:

View Migration Guide

了解如何从 Node.js SDK 迁移到 TypeScript SDK

自动分页

DodoPayments API 中的方法是分页的。您可以使用 for await … of 语法遍历跨所有页面的项目:
async function fetchAllPayments() {
  const allPayments = [];
  // Automatically fetches more pages as needed.
  for await (const paymentListResponse of client.payments.list()) {
    allPayments.push(paymentListResponse);
  }
  return allPayments;
}
或者,您可以一次请求一个单一页面:
let page = await client.payments.list();
for (const paymentListResponse of page.items) {
  console.log(paymentListResponse);
}

// Convenience methods are provided for manually paginating:
while (page.hasNextPage()) {
  page = await page.getNextPage();
  // ...
}

要求

支持以下运行时:
  • 网络浏览器(最新的 Chrome、Firefox、Safari、Edge 等)
  • Node.js 20 LTS 或更高版本(非 EOL
  • Deno v1.28.0 或更高版本
  • Bun 1.0 或更高版本
  • Cloudflare Workers
  • Vercel Edge Runtime
  • Jest 28 或更高级别环境下的 "node"
  • Nitro v2.6 或更高版本
支持 TypeScript >= 4.9。

资源

GitHub Repository

查看源代码并贡献

API Reference

完整的 API 文档

Discord Community

获取帮助并与开发者联系

Report Issues

报告错误或请求功能

支持

需要 TypeScript SDK 的帮助?

贡献

我们欢迎贡献!查看贡献指南开始吧。
Last modified on May 14, 2026