C# SDK 提供了从 C# 编写的应用程序访问 Dodo Payments REST API 的便捷方式。它具有基于 async Task 的 API,类型安全,目前处于测试阶段。
C# SDK 目前处于测试阶段。我们正在积极进行改进,并欢迎您的反馈。
使用 .NET CLI 安装 SDK:
dotnet add package DodoPayments.Client
该 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
完整的基于 async Task 的 API,支持非阻塞操作
配置
通过环境变量或 appsettings.json 进行简单配置
环境变量
使用环境变量进行配置:
DODO_PAYMENTS_API_KEY=your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new();
请参见此表以获取可用选项:
| 属性 | 环境变量 | 必需 | 默认值 |
|---|
BearerToken | DODO_PAYMENTS_API_KEY | true | - |
WebhookKey | DODO_PAYMENTS_WEBHOOK_KEY | false | - |
BaseUrl | DODO_PAYMENTS_BASE_URL | true | "https://live.dodopayments.com" |
手动配置
使用 Bearer 令牌手动配置:
DodoPaymentsClient client = new() { BearerToken = "My Bearer Token" };
常见操作
创建结账会话
生成结账会话:
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 createParams = new CustomerCreateParams
{
Email = "customer@example.com",
Name = "John Doe",
Metadata = new Dictionary<string, string>
{
{ "user_id", "12345" }
}
};
var customer = await client.Customers.Create(createParams);
// Retrieve customer
var retrieved = await client.Customers.Retrieve("cus_123");
Console.WriteLine($"Customer: {retrieved.Name} ({retrieved.Email})");
处理订阅
创建和管理定期订阅:
// Create a subscription
var subscriptionParams = new SubscriptionCreateParams
{
CustomerID = "cus_123",
ProductID = "prod_456",
PriceID = "price_789"
};
var subscription = await client.Subscriptions.Create(subscriptionParams);
// Cancel subscription
await client.Subscriptions.Cancel(subscription.Id);
该 SDK 定义了返回分页结果列表的方法,提供方便的方式逐页或逐项访问所有页面的结果。
自动分页
要遍历所有页面的所有结果,请使用 Paginate 方法:
using System;
var page = await client.Payments.List(parameters);
await foreach (var item in page.Paginate())
{
Console.WriteLine(item);
}
手动分页
要访问单个页面项并手动请求下一页:
using System;
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 集成
服务注册
在 Program.cs 中注册客户端:
using DodoPayments.Client;
var builder = WebApplication.CreateBuilder(args);
// Register DodoPayments client
builder.Services.AddSingleton<DodoPaymentsClient>(sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
return new DodoPaymentsClient
{
BearerToken = configuration["DodoPayments:ApiKey"]
};
});
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
在 appsettings.json 中添加配置:
{
"DodoPayments": {
"ApiKey": "your_api_key_here"
}
}
API 控制器
使用依赖注入创建控制器:
using Microsoft.AspNetCore.Mvc;
using DodoPayments.Client;
using DodoPayments.Client.Models.CheckoutSessions;
[ApiController]
[Route("api/[controller]")]
public class PaymentsController : ControllerBase
{
private readonly DodoPaymentsClient _client;
private readonly ILogger<PaymentsController> _logger;
public PaymentsController(DodoPaymentsClient client, ILogger<PaymentsController> logger)
{
_client = client;
_logger = logger;
}
[HttpPost("checkout")]
public async Task<IActionResult> CreateCheckout([FromBody] CheckoutRequest request)
{
try
{
var parameters = new CheckoutSessionCreateParams
{
ProductCart = request.Items,
ReturnUrl = Url.Action("Return", "Checkout", null, Request.Scheme)
};
var session = await _client.CheckoutSessions.Create(parameters);
return Ok(new { checkoutUrl = session.Url });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create checkout");
return BadRequest(new { error = ex.Message });
}
}
}
public record CheckoutRequest(List<ProductCartItem> Items);
服务层模式
为业务逻辑创建服务:
public interface IPaymentService
{
Task<CheckoutSessionResponse> CreateCheckoutAsync(List<ProductCartItem> items);
Task<PaymentResponse> ProcessPaymentAsync(decimal amount, string currency, string customerId);
}
public class PaymentService : IPaymentService
{
private readonly DodoPaymentsClient _client;
private readonly ILogger<PaymentService> _logger;
public PaymentService(DodoPaymentsClient client, ILogger<PaymentService> logger)
{
_client = client;
_logger = logger;
}
public async Task<CheckoutSessionResponse> CreateCheckoutAsync(List<ProductCartItem> items)
{
var parameters = new CheckoutSessionCreateParams
{
ProductCart = items,
ReturnUrl = "https://yourdomain.com/return"
};
return await _client.CheckoutSessions.Create(parameters);
}
public async Task<PaymentResponse> ProcessPaymentAsync(
decimal amount,
string currency,
string customerId)
{
try
{
var parameters = new PaymentCreateParams
{
Amount = (long)(amount * 100), // Convert to cents
Currency = currency,
CustomerID = customerId
};
return await _client.Payments.Create(parameters);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to process payment");
throw;
}
}
}
用户机密(开发)
在开发中,使用用户机密存储 API 密钥:
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"
使用 xUnit 的示例单元测试:
using Xunit;
using DodoPayments.Client;
using DodoPayments.Client.Models.CheckoutSessions;
public class PaymentServiceTests
{
private readonly DodoPaymentsClient _client;
public PaymentServiceTests()
{
_client = new DodoPaymentsClient
{
BearerToken = "test_key"
};
}
[Fact]
public async Task CreateCheckout_ShouldReturnSession()
{
// Arrange
var parameters = new CheckoutSessionCreateParams
{
ProductCart =
[
new()
{
ProductID = "prod_test",
Quantity = 1
}
]
};
// Act
var session = await _client.CheckoutSessions.Create(parameters);
// Assert
Assert.NotNull(session);
Assert.NotNull(session.SessionId);
}
}
需要 C# SDK 的帮助吗?
由于 SDK 处于测试阶段,您的反馈和贡献尤其重要!请查看 贡献指南 开始。