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

> 타입 안전성과 현대적인 async/await 지원을 통해 TypeScript 및 Node.js 애플리케이션에 Dodo Payments를 통합하세요.

TypeScript SDK는 TypeScript 및 JavaScript 애플리케이션을 위한 Dodo Payments REST API에 대한 편리한 서버 측 액세스를 제공합니다. 포괄적인 타입 정의, 오류 처리, 재시도, 타임아웃 및 원활한 결제 처리를 위한 자동 페이지 매김 기능을 갖추고 있습니다.

## 설치

선호하는 패키지 관리자를 사용하여 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 이상 ([non-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)에 가입하세요
* **이메일**: [support@dodopayments.com](mailto:support@dodopayments.com)으로 연락하십시오
* **GitHub**: [레포지토리](https://github.com/dodopayments/dodopayments-typescript)에서 이슈를 등록하세요

## 기여하기

우리는 기여를 환영합니다! [기여 가이드라인](https://github.com/dodopayments/dodopayments-typescript/blob/main/CONTRIBUTING.md)을 확인하여 시작하세요.
