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

> Integrate Dodo Payments into your TypeScript and Node.js applications with type safety and modern async/await support

The TypeScript SDK provides convenient server-side access to the Dodo Payments REST API for TypeScript and JavaScript applications. It features comprehensive type definitions, error handling, retries, timeouts, and auto-pagination for seamless payment processing.

## Installation

Install the SDK using your package manager of choice:

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

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

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

## Quick Start

Initialize the client with your API key and start processing payments:

```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>
  Always store your API keys securely using environment variables. Never commit them to version control or expose them in client-side code.
</Warning>

## Core Features

<CardGroup cols={2}>
  <Card title="TypeScript First" icon="shield-check">
    Full TypeScript support with comprehensive type definitions for all API endpoints
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    Automatic pagination for list responses makes working with large datasets effortless
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Built-in error types with detailed messages for different failure scenarios
  </Card>

  <Card title="Smart Retries" icon="repeat">
    Configurable automatic retries with exponential backoff for transient errors
  </Card>
</CardGroup>

## Configuration

### Environment Variables

Set environment variables for secure configuration:

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

### Timeout Configuration

Configure request timeouts globally or per-request:

```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 },
);
```

### Retry Configuration

Configure automatic retry behavior:

```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>
  The SDK automatically retries requests that fail due to network errors or server issues (5xx responses) with exponential backoff.
</Tip>

## Common Operations

### Create a Checkout Session

Generate a checkout session for collecting payment information:

```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);
```

### Manage Customers

Create and retrieve customer information:

```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})`);
```

### Handle Subscriptions

Create and manage recurring subscriptions:

```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` yêu cầu tối thiểu mã quốc gia ISO hai chữ cái. `customer` là một liên minh của `{ customer_id }` (để đính kèm khách hàng hiện có) hoặc `{ email, name? }` (để tạo mới). `product_price` được biểu thị bằng đơn vị tiền tệ thấp nhất.
</Info>

## Tính phí dựa trên mức sử dụng

### Tiếp nhận Sự kiện Sử dụng

Theo dõi sự kiện tùy chỉnh cho tính phí dựa trên mức sử dụng:

```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>
  Sự kiện phải có giá trị `event_id` độc nhất để đảm bảo idempotency. ID trùng lặp trong cùng yêu cầu bị từ chối và yêu cầu tiếp theo với ID hiện có sẽ bị bỏ qua.
</Info>

### Lấy Sự kiện Sử dụng

Truy xuất thông tin chi tiết về các sự kiện sử dụng:

```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'
});
```

## Cấu hình Proxy

Cấu hình cài đặt proxy cho các runtime khác nhau:

### Node.js (sử dụng 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,
  },
});
```

## Logging

Kiểm soát độ chi tiết của bản ghi sử dụng biến môi trường hoặc tùy chọn của client:

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

**Các mức độ bản ghi có sẵn:**

* `'debug'` - Hiển thị thông điệp gỡ lỗi, thông tin, cảnh báo và lỗi
* `'info'` - Hiển thị thông điệp thông tin, cảnh báo và lỗi
* `'warn'` - Hiển thị cảnh báo và lỗi (mặc định)
* `'error'` - Chỉ hiển thị lỗi
* `'off'` - Tắt hoàn toàn ghi nhật ký

<Warning>
  Ở mức gỡ lỗi, tất cả các yêu cầu và phản hồi HTTP đều được ghi lại, bao gồm tiêu đề và nội dung. Một số tiêu đề xác thực bị ẩn, nhưng dữ liệu nhạy cảm trong nội dung có thể vẫn hiển thị.
</Warning>

## Di cư từ SDK Node.js

Nếu bạn đang nâng cấp từ SDK Node.js cũ, SDK TypeScript cung cấp độ an toàn kiểu tốt hơn và các tính năng mới:

<Card title="View Migration Guide" icon="arrow-right" href="https://github.com/dodopayments/dodopayments-typescript/blob/main/MIGRATION.md">
  Tìm hiểu cách di cư từ SDK Node.js sang SDK TypeScript
</Card>

## Tự động phân trang

Phương thức danh sách trong API DodoPayments được phân trang. Bạn có thể sử dụng cú pháp `for await … of` để lặp qua các mục trên tất cả các trang:

```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;
}
```

Ngoài ra, bạn có thể yêu cầu từng trang một:

```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();
  // ...
}
```

## Yêu cầu

Các runtime sau đây được hỗ trợ:

* Trình duyệt web (Chrome, Firefox, Safari, Edge và nhiều hơn nữa được cập nhật)
* Node.js 20 LTS hoặc mới hơn ([không hết hạn](https://endoflife.date/nodejs))
* Deno v1.28.0 hoặc cao hơn
* Bun 1.0 hoặc mới hơn
* Cloudflare Workers
* Vercel Edge Runtime
* Jest 28 hoặc cao hơn với môi trường `"node"`
* Nitro v2.6 hoặc lớn hơn

TypeScript >= 4.9 được hỗ trợ.

## Tài nguyên

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-typescript">
    Xem mã nguồn và đóng góp
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Tài liệu API đầy đủ
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Nhận sự trợ giúp và kết nối với các nhà phát triển
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-typescript/issues">
    Báo cáo lỗi hoặc yêu cầu tính năng
  </Card>
</CardGroup>

## Hỗ trợ

Cần hỗ trợ với SDK TypeScript?

* **Discord**: Tham gia [server cộng đồng](https://discord.gg/bYqAp4ayYh) của chúng tôi để được hỗ trợ ngay lập tức
* **Email**: Liên hệ với chúng tôi tại [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Mở một vấn đề tại [repository](https://github.com/dodopayments/dodopayments-typescript)

## Đóng góp

Chúng tôi hoan nghênh sự đóng góp! Kiểm tra [hướng dẫn đóng góp](https://github.com/dodopayments/dodopayments-typescript/blob/main/CONTRIBUTING.md) để bắt đầu.
