الانتقال إلى المحتوى الرئيسي

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.

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:
npm install dodopayments

Quick Start

Initialize the client with your API key and start processing payments:
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);
Always store your API keys securely using environment variables. Never commit them to version control or expose them in client-side code.

Core Features

TypeScript First

Full TypeScript support with comprehensive type definitions for all API endpoints

Auto-Pagination

Automatic pagination for list responses makes working with large datasets effortless

Error Handling

Built-in error types with detailed messages for different failure scenarios

Smart Retries

Configurable automatic retries with exponential backoff for transient errors

Configuration

Environment Variables

Set environment variables for secure configuration:
.env
DODO_PAYMENTS_API_KEY=your_api_key_here

Timeout Configuration

Configure request timeouts globally or per-request:
// 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:
// 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 },
);
The SDK automatically retries requests that fail due to network errors or server issues (5xx responses) with exponential backoff.

Common Operations

Create a Checkout Session

Generate a checkout session for collecting payment information:
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);

Manage Customers

Create and retrieve customer information:
// 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:
// 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',
});
billing يتطلب الحد الأدنى من رمز البلد ISO ذو الحرفين. customer هو اتحاد من { customer_id } (لإرفاق عميل موجود) أو { email, name? } (لإنشاء عميل جديد). product_price يُعبر عنها بأصغر وحدة نقدية.

الفوترة المستندة إلى الاستخدام

إدخال أحداث الاستخدام

تتبع الأحداث المخصصة للفوترة المستندة إلى الاستخدام:
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 فريدة لضمان عدم التكرار. يتم رفض المعرفات المكررة ضمن نفس الطلب، وتُتجاهل الطلبات اللاحقة التي تحتوي على معرفات موجودة بالفعل.

استرجاع أحداث الاستخدام

جلب معلومات مفصلة عن أحداث الاستخدام:
// 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

تعلم كيفية الانتقال من Node.js SDK إلى TypeScript SDK

التصفح التلقائي

طرق القائمة في DodoPayments API مجزأة. يمكنك استخدام صيغة for await … of للتنقل عبر العناصر عبر جميع الصفحات:
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();
  // ...
}

المتطلبات

تدعم السيناريوهات التالية:
  • المتصفحات ويب (Chrome، Firefox، Safari، Edge، والمزيد) الأحدث
  • Node.js 20 LTS أو أحدث (غير منتهي الدعم)
  • Deno v1.28.0 أو أعلى
  • Bun 1.0 أو أحدث
  • Cloudflare Workers
  • Vercel Edge Runtime
  • Jest 28 أو أكبر مع بيئة "node"
  • Nitro v2.6 أو أكبر
TypeScript >= 4.9 مدعومة.

الموارد

GitHub Repository

عرض الكود المصدر والمساهمة

API Reference

وثائق API الكاملة

Discord Community

الحصول على المساعدة والتواصل مع المطورين

Report Issues

الإبلاغ عن الأخطاء أو طلب الميزات

الدعم

هل تحتاج إلى مساعدة مع TypeScript SDK؟

المساهمة

نرحب بالمساهمات! اطلع على إرشادات المساهمة للبدء.
Last modified on May 14, 2026