Chuyển đến nội dung chính
SDK C# cung cấp quyền truy cập thuận tiện vào Dodo Payments REST API từ các ứng dụng viết bằng C#. Nó có API dựa trên async Task với kiểu dữ liệu mạnh, tự động thử lại và xử lý lỗi toàn diện.

Cài đặt

Cài đặt gói từ NuGet:
dotnet add package DodoPayments.Client
SDK yêu cầu .NET 8.0 trở lên. Nó hoạt động với ASP.NET Core, các ứng dụng Console và các loại dự án .NET khác.

Bắt đầu nhanh

Khởi tạo client và tạo phiên thanh toán:
using System;
using DodoPayments.Client;
using DodoPayments.Client.Models.CheckoutSessions;

// Configured using the DODO_PAYMENTS_API_KEY and DODO_PAYMENTS_BASE_URL environment variables
DodoPaymentsClient client = new();

CheckoutSessionCreateParams parameters = new()
{
    ProductCart =
    [
        new()
        {
            ProductID = "product_id",
            Quantity = 1,
        },
    ],
};

var checkoutSessionResponse = await client.CheckoutSessions.Create(parameters);

Console.WriteLine(checkoutSessionResponse.SessionId);
Luôn lưu trữ khóa API của bạn một cách an toàn bằng biến môi trường, user secrets hoặc Azure Key Vault. Không bao giờ viết cứng chúng vào mã nguồn hoặc cam kết chúng lên hệ thống điều khiển phiên bản.

Tính năng chính

Async/Await

API bất đồng bộ dựa trên Task đầy đủ cho các thao tác không chặn

Strong Typing

Đảm bảo kiểu dữ liệu toàn diện với nullable reference types

Smart Retries

Tự động thử lại với độ trễ tăng dần cho các lỗi tạm thời

Error Handling

Hệ thống ngoại lệ tích hợp cho việc quản lý lỗi chính xác

Cấu hình

Biến môi trường

.env
DODO_PAYMENTS_API_KEY=your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new();
Thuộc tínhBiến môi trườngBắt buộcGiá trị mặc định
BearerTokenDODO_PAYMENTS_API_KEYtrue-
WebhookKeyDODO_PAYMENTS_WEBHOOK_KEYfalse-
BaseUrlDODO_PAYMENTS_BASE_URLtrue"https://live.dodopayments.com"

Cấu hình Thủ công

DodoPaymentsClient client = new() { BearerToken = "My Bearer Token" };

Môi trường

Chuyển đổi giữa chế độ thực và chế độ kiểm tra:
using DodoPayments.Client.Core;

DodoPaymentsClient client = new() { BaseUrl = EnvironmentUrl.TestMode };

Thử Lại

SDK tự động thử lại 2 lần theo mặc định với độ trễ tăng dần. Nó thử lại trên các lỗi kết nối và mã trạng thái 408, 409, 429 và 5xx.
// Custom retry count
DodoPaymentsClient client = new() { MaxRetries = 3 };

Thời gian chờ

Các yêu cầu sẽ hết thời gian chờ sau 1 phút theo mặc định.
DodoPaymentsClient client = new() { Timeout = TimeSpan.FromSeconds(30) };

Ghi đè theo Yêu cầu

Tạm thời thay đổi cấu hình cho một yêu cầu duy nhất bằng cách sử dụng WithOptions:
var response = await client
    .WithOptions(options => options with
    {
        Timeout = TimeSpan.FromSeconds(10),
        MaxRetries = 5,
    })
    .CheckoutSessions.Create(parameters);

Các Hoạt động Thông thường

Tạo Phiên Thanh Toán

var parameters = new CheckoutSessionCreateParams
{
    ProductCart =
    [
        new()
        {
            ProductID = "prod_123",
            Quantity = 1
        }
    ],
    ReturnUrl = "https://yourdomain.com/return"
};

var session = await client.CheckoutSessions.Create(parameters);
Console.WriteLine($"Checkout URL: {session.Url}");

Quản lý Khách hàng

// Create a customer
var customer = await client.Customers.Create(new CustomerCreateParams
{
    Email = "customer@example.com",
    Name = "John Doe"
});

// Retrieve customer
var retrieved = await client.Customers.Retrieve("cus_123");
Console.WriteLine($"Customer: {retrieved.Name} ({retrieved.Email})");

Xử lý Đăng ký

// Create a subscription
var subscription = await client.Subscriptions.Create(new SubscriptionCreateParams
{
    CustomerID = "cus_123",
    ProductID = "prod_456",
    PriceID = "price_789"
});

// Cancel subscription
await client.Subscriptions.Cancel(subscription.Id);

Xử lý Lỗi

SDK đưa ra các ngoại lệ cụ thể dựa trên mã trạng thái HTTP. Tất cả các lỗi 4xx kế thừa từ DodoPayments4xxException.
Trạng tháiNgoại lệ
400DodoPaymentsBadRequestException
401DodoPaymentsUnauthorizedException
403DodoPaymentsForbiddenException
404DodoPaymentsNotFoundException
422DodoPaymentsUnprocessableEntityException
429DodoPaymentsRateLimitException
5xxDodoPayments5xxException
khácDodoPaymentsUnexpectedStatusCodeException
Các loại ngoại lệ khác:
  • DodoPaymentsIOException: Lỗi I/O mạng
  • DodoPaymentsInvalidDataException: Không phân tích được dữ liệu đã phân tích
  • DodoPaymentsException: Lớp cơ sở cho tất cả các ngoại lệ

Phân trang

Tự động Phân trang

Lặp qua tất cả kết quả trên tất cả các trang bằng cách sử dụng phương thức Paginate, phương thức này trả về một IAsyncEnumerable:
var page = await client.Payments.List(parameters);
await foreach (var item in page.Paginate())
{
    Console.WriteLine(item);
}

Phân trang Thủ công

var page = await client.Payments.List();
while (true)
{
    foreach (var item in page.Items)
    {
        Console.WriteLine(item);
    }
    if (!page.HasNext())
    {
        break;
    }
    page = await page.Next();
}

Tích hợp ASP.NET Core

Đăng ký client trong container DI của bạn:
Program.cs
using DodoPayments.Client;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<DodoPaymentsClient>(sp =>
{
    var configuration = sp.GetRequiredService<IConfiguration>();
    return new DodoPaymentsClient
    {
        BearerToken = configuration["DodoPayments:ApiKey"]
    };
});

var app = builder.Build();
app.Run();
appsettings.json
{
  "DodoPayments": {
    "ApiKey": "your_api_key_here"
  }
}
Trong quá trình phát triển, sử dụng user secrets thay vì lưu trữ khóa trong appsettings.json:
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"

Tài nguyên

NuGet Package

Xem gói trên NuGet Gallery

GitHub Repository

Xem mã nguồn và đóng góp

API Reference

Tài liệu API đầy đủ

Discord Community

Nhận sự trợ giúp và kết nối với các nhà phát triển

Hỗ trợ

Cần sự trợ giúp với SDK C#?
Last modified on March 24, 2026