> ## 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

> 将 Dodo Payments 集成到您的 TypeScript 和 Node.js 应用程序中，支持类型安全和现代的 async/await。

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

## 安装

使用你选择的包管理器安装 SDK：

<CodeGroup>
  ```bash npm theme={null}
  npm install dodopayments
  ```

  ```bash yarn theme={null}
  yarn add dodopayments
  ```

  ```bash pnpm theme={null}
  pnpm add dodopayments
  ```
</CodeGroup>

## 快速开始

使用您的 API 密钥初始化客户端并开始处理支付：

```javascript theme={null}
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);
```

<Warning>
  始终使用环境变量安全地存储你的 API 密钥。切勿将它们提交到版本控制或在客户端代码中暴露。
</Warning>

## 核心功能

<CardGroup cols={2}>
  <Card title="TypeScript First" icon="shield-check">
    提供对所有 API 端点的全面类型定义的完整 TypeScript 支持
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    自动分页处理列表响应，让处理大量数据集变得轻松无忧
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    内置错误类型带有针对不同失败场景的详细消息
  </Card>

  <Card title="Smart Retries" icon="repeat">
    可配置的自动重试，针对瞬态错误提供指数退避策略
  </Card>
</CardGroup>

## 配置

### 环境变量

设置环境变量以进行安全配置：

```bash .env theme={null}
DODO_PAYMENTS_API_KEY=your_api_key_here
```

### 超时配置

全局或按请求配置请求超时：

```typescript theme={null}
// 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 },
);
```

### 重试配置

配置自动重试行为：

```javascript theme={null}
// 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 },
);
```

<Tip>
  SDK 会自动对因网络错误或服务器问题（5xx 响应）而失败的请求进行指数退避重试。
</Tip>

## 常见操作

### 创建结账会话

生成结账会话以收集支付信息：

```typescript theme={null}
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.checkout_url);
```

### 管理客户

创建和检索客户信息：

```typescript theme={null}
// 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})`);
```

### 处理订阅

创建和管理定期订阅：

```typescript theme={null}
// 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',
});
```

<Info>
  `billing` 至少需要使用两位的 ISO 国家代码。`customer` 是一个联合，由 `{ customer_id }`（用于关联现有客户）或 `{ email, name? }`（用于创建新客户）组成。`product_price` 以最低货币单位表示。
</Info>

## 基于使用量的计费

### 收集使用事件

跟踪基于使用量计费的自定义事件：

```typescript theme={null}
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'
      }
    }
  ]
});
```

<Info>
  事件必须拥有唯一的 `event_id` 值以确保幂等性。同一请求中的重复 ID 将被拒绝，后续请求中的现有 ID 将被忽略。
</Info>

### 检索使用事件

获取使用事件的详细信息：

```typescript theme={null}
// 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）

```typescript theme={null}
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

```typescript theme={null}
import DodoPayments from 'dodopayments';

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

### Deno

```typescript theme={null}
import DodoPayments from 'npm:dodopayments';

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

## 日志记录

使用环境变量或客户端选项控制日志的详细程度：

```typescript theme={null}
// Via client option
const client = new DodoPayments({
  logLevel: 'debug', // Show all log messages
});
```

```bash theme={null}
# Via environment variable
export DODO_PAYMENTS_LOG=debug
```

**可用的日志级别：**

* `'debug'` - 显示调试消息、信息、警告和错误
* `'info'` - 显示信息消息、警告和错误
* `'warn'` - 显示警告和错误（默认）
* `'error'` - 仅显示错误
* `'off'` - 禁用所有日志记录

<Warning>
  在调试级别，所有 HTTP 请求和响应都被记录，包括头和主体。一些身份验证头被编辑掉，但主体中的敏感数据可能仍然可见。
</Warning>

## 从 Node.js SDK 迁移

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

<Card title="View Migration Guide" icon="arrow-right" href="https://github.com/dodopayments/dodopayments-typescript/blob/main/MIGRATION.md">
  了解如何从 Node.js SDK 迁移到 TypeScript SDK
</Card>

## 自动分页

DodoPayments API 中的方法是分页的。您可以使用 `for await … of` 语法遍历跨所有页面的项目：

```typescript theme={null}
async function fetchAllPayments() {
  const allPayments = [];
  // Automatically fetches more pages as needed.
  for await (const paymentListResponse of client.payments.list()) {
    allPayments.push(paymentListResponse);
  }
  return allPayments;
}
```

或者，您可以一次请求一个单一页面：

```typescript theme={null}
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](https://endoflife.date/nodejs)）
* Deno v1.28.0 或更高版本
* Bun 1.0 或更高版本
* Cloudflare Workers
* Vercel Edge Runtime
* Jest 28 或更高级别环境下的 `"node"`
* Nitro v2.6 或更高版本

支持 TypeScript >= 4.9。

## 资源

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-typescript">
    查看源代码并贡献
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    完整的 API 文档
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    获取帮助并与开发者联系
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-typescript/issues">
    报告错误或请求功能
  </Card>
</CardGroup>

## 支持

需要 TypeScript SDK 的帮助？

* **Discord**：加入我们的[社区服务器](https://discord.gg/bYqAp4ayYh)以获得实时支持
* **Email**：通过 [support@dodopayments.com](mailto:support@dodopayments.com) 联系我们
* **GitHub**：在[仓库](https://github.com/dodopayments/dodopayments-typescript)上打开一个问题

## 贡献

我们欢迎贡献！查看[贡献指南](https://github.com/dodopayments/dodopayments-typescript/blob/main/CONTRIBUTING.md)开始吧。
