メインコンテンツへスキップ
TypeScript SDKは、TypeScriptおよびJavaScriptアプリケーション向けにDodo Payments REST APIへの便利なサーバーサイドアクセスを提供します。包括的な型定義、エラーハンドリング、リトライ、タイムアウト、自動ページネーションを特徴としており、シームレスな支払い処理を実現します。

インストール

お好みのパッケージマネージャーを使用して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ファースト

すべてのAPIエンドポイントに対する包括的な型定義を持つ完全なTypeScriptサポート

自動ページネーション

大規模データセットの操作を容易にするリストレスポンスの自動ページネーション

エラーハンドリング

異なる失敗シナリオに対する詳細なメッセージを持つ組み込みエラータイプ

スマートリトライ

一時的なエラーに対する指数バックオフを伴う構成可能な自動リトライ

設定

環境変数

安全な設定のために環境変数を設定します:
.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: 0 }] },
  { 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: 0 }] },
  { 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: '[email protected]',
  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は型安全性と機能が向上しています:

移行ガイドを見る

Node.js SDKからTypeScript SDKへの移行方法を学ぶ

リソース

サポート

TypeScript SDKに関して助けが必要ですか?

貢献

貢献を歓迎します!始めるために貢献ガイドラインを確認してください。