メインコンテンツへスキップ
C# SDK は、C# で記述されたアプリケーションから Dodo Payments REST API への便利なアクセス手段を提供します。強い型付けを備えた async Task ベースの API を特徴としています。

インストール

.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);
API キーは常に、環境変数、ユーザー シークレット、または Azure Key Vault を使用して安全に保管してください。ソース コードにハードコードしたり、バージョン管理にコミットしたりしないでください。

主な機能

Async/Await

ノンブロッキング操作のための完全な async Task ベースの API

Strong Typing

Nullable 参照型を活用した包括的な型安全性

Dependency Injection

.NET の依存性注入に対するファーストクラス サポート

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

よく使う操作

チェックアウト セッションの作成

チェックアウト セッションを生成します:
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 でクライアントを登録します:
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 に構成を追加します:
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 に関して支援が必要ですか?

コントリビューション

ご協力を歓迎します!contributing guidelines を確認して始めてください。