跳转到主要内容
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({
  customer_id: 'cus_123',
  product_id: 'prod_456',
  price_id: 'price_789'
});

// Retrieve subscription usage history
const usageHistory = await client.subscriptions.retrieveUsageHistory('sub_123', {
  start_date: '2024-01-01T00:00:00Z',
  end_date: '2024-03-31T23:59:59Z'
});

基于使用的计费

记录使用事件

跟踪用于基于使用的计费的自定义事件:
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

Learn how to migrate from the Node.js SDK to the TypeScript SDK

自动分页

List methods in the DodoPayments API are paginated. You can use the for await … of syntax to iterate through items across all pages:
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();
  // ...
}

要求

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

资源

GitHub Repository

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

API Reference

完整的 API 文档

Discord Community

获取帮助并与开发者建立联系

Report Issues

报告错误或提出功能请求

支持

需要 TypeScript SDK 的帮助吗?

贡献

我们欢迎贡献!查看 贡献指南 开始。
Last modified on February 27, 2026