跳转到主要内容

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.

C# SDK提供了从使用C#编写的应用程序方便访问Dodo Payments REST API的方式。它提供了基于async Task的API,具备强类型、自动重试和全面的错误处理功能。
C# SDK 当前处于测试阶段。我们正在积极改进,欢迎您的反馈。
NuGet安装该包: 使用 .NET CLI 安装 SDK:
该SDK需要.NET 8.0或更高版本。它可以与ASP.NET Core、控制台应用程序和其他.NET项目类型一起使用。
该 SDK 需要 .NET Standard 2.0 或更高版本。它适用于 ASP.NET Core、控制台应用程序以及其他 .NET 项目类型。

快速开始

初始化客户端并创建结账会话:
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);
务必使用环境变量、用户机密或 Azure Key Vault 安全地存储您的 API 密钥。切勿将其硬编码在源代码中或提交到版本控制。

核心功能

Async/Await

适用于非阻塞操作的完整基于 Task 的异步 API

Strong Typing

针对瞬时错误的指数退避自动重试

Smart Retries

内置异常层次结构以进行精确的错误管理

Configuration

通过环境变量或 appsettings.json 进行简单配置

配置

.env
DODO_PAYMENTS_API_KEY=your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new();
属性环境变量必需默认值
BearerTokenDODO_PAYMENTS_API_KEYtrue-
WebhookKeyDODO_PAYMENTS_WEBHOOK_KEYfalse-
BaseUrlDODO_PAYMENTS_BASE_URLtrue"https://live.dodopayments.com"

手动配置

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

环境

在实时模式和测试模式之间切换:
using DodoPayments.Client.Core;

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

重试

SDK默认情况下会自动重试2次,并应用指数退避。它会在连接错误以及状态码408、409、429和5xx时进行重试。
// Custom retry count
DodoPaymentsClient client = new() { MaxRetries = 3 };

超时

请求默认在1分钟后超时。
DodoPaymentsClient client = new() { Timeout = TimeSpan.FromSeconds(30) };

每请求覆盖

使用WithOptions临时修改单个请求的配置:
var response = await client
    .WithOptions(options => options with
    {
        Timeout = TimeSpan.FromSeconds(10),
        MaxRetries = 5,
    })
    .CheckoutSessions.Create(parameters);

常用操作

创建结帐会话

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

管理客户

// 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})");

处理订阅

using DodoPayments.Client.Models.Payments;
using DodoPayments.Client.Models.Subscriptions;

// Create a subscription
var subscription = await client.Subscriptions.Create(new SubscriptionCreateParams
{
    Billing = new BillingAddress
    {
        Country = "US",
        City = "San Francisco",
        State = "CA",
        Street = "1 Market St",
        Zipcode = "94105",
    },
    Customer = new AttachExistingCustomer { CustomerID = "cus_123" },
    ProductID = "pdt_456",
    Quantity = 1,
});

// Charge an on-demand subscription
// ProductPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
var charge = await client.Subscriptions.Charge(
    subscription.SubscriptionId,
    new SubscriptionChargeParams { ProductPrice = 2500 }
);
Billing 需要至少两个字母的 ISO Country 代码。 使用 AttachExistingCustomer 来附加现有客户,或使用 NewCustomer 来创建一个。 ProductPrice 以最低货币面值表示。

错误处理

SDK 根据 HTTP 状态码抛出特定异常。所有 4xx 错误都继承自 DodoPayments4xxException
状态异常
400DodoPaymentsBadRequestException
401DodoPaymentsUnauthorizedException
403DodoPaymentsForbiddenException
404DodoPaymentsNotFoundException
422DodoPaymentsUnprocessableEntityException
429DodoPaymentsRateLimitException
5xxDodoPayments5xxException
othersDodoPaymentsUnexpectedStatusCodeException
其他异常类型:
  • DodoPaymentsIOException: I/O 网络错误
  • DodoPaymentsInvalidDataException: 解析数据失败
  • DodoPaymentsException: 所有异常的基类

分页

自动分页

使用 Paginate 方法遍历所有页面的所有结果,该方法返回一个 IAsyncEnumerable:
var page = await client.Payments.List(parameters);
await foreach (var item in page.Paginate())
{
    Console.WriteLine(item);
}

手动分页

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

ASP.NET Core 集成

在你的 DI 容器中注册客户端:
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"
  }
}
对于开发,请使用 用户秘密 而不是将密钥存储在 appsettings.json 中。
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"

资源

NuGet Package

在 NuGet Gallery 上查看包

GitHub Repository

查看源代码并贡献

API Reference

完整的 API 文档

Discord Community

获取帮助并与开发者交流

支持

需要 C# SDK 帮助吗?
Last modified on May 14, 2026