Zum Hauptinhalt springen
Das C#-SDK bietet einen bequemen Zugriff auf die Dodo Payments REST-API aus Anwendungen, die in C# geschrieben sind. Es verfügt über eine asynchrone Task-basierte API mit starker Typisierung.

Installation

Installieren Sie das SDK mit der .NET CLI:
dotnet add package DodoPayments.Client
Das SDK erfordert .NET Standard 2.0 oder neuer. Es funktioniert mit ASP.NET Core, Konsolenanwendungen und anderen .NET-Projekttypen.

Schnellstart

Initialisieren Sie den Client und erstellen Sie eine Checkout-Sitzung:
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);
Speichern Sie Ihre API-Schlüssel stets sicher, z. B. über Umgebungsvariablen, Benutzerdaten oder Azure Key Vault. Hardcodieren Sie sie niemals im Quellcode oder übergeben Sie sie an die Versionskontrolle.

Kernfunktionen

Async/Await

Vollständige asynchrone Task-basierte API für nicht blockierende Operationen

Strong Typing

Umfassende Typensicherheit mit nullable Referenztypen

Dependency Injection

Erstklassige Unterstützung für .NET Dependency Injection

Configuration

Einfache Konfiguration über Umgebungsvariablen oder appsettings.json

Konfiguration

Umgebungsvariablen

Konfigurieren Sie über Umgebungsvariablen:
.env
DODO_PAYMENTS_API_KEY=your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new();
Siehe diese Tabelle für die verfügbaren Optionen:
PropertyEnvironment variableRequiredDefault value
BearerTokenDODO_PAYMENTS_API_KEYtrue-
WebhookKeyDODO_PAYMENTS_WEBHOOK_KEYfalse-
BaseUrlDODO_PAYMENTS_BASE_URLtrue"https://live.dodopayments.com"

Manuelle Konfiguration

Konfigurieren Sie manuell mit einem Bearer-Token:
DodoPaymentsClient client = new() { BearerToken = "My Bearer Token" };

Häufige Operationen

Erstellen einer Checkout-Sitzung

Generieren Sie eine Checkout-Sitzung:
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}");

Kunden verwalten

Erstellen und holen Sie Kundeninformationen ab:
// 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})");

Abonnements verwalten

Erstellen und verwalten Sie wiederkehrende Abonnements:
// 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);

Pagination

Das SDK definiert Methoden, die paginierte Ergebnislisten zurückgeben, und bietet praktische Möglichkeiten, Ergebnisse entweder seitenweise oder Element für Element über alle Seiten hinweg zu durchlaufen.

Automatische Paginierung

Um alle Ergebnisse über alle Seiten hinweg zu iterieren, verwenden Sie die Paginate-Methode:
using System;

var page = await client.Payments.List(parameters);
await foreach (var item in page.Paginate())
{
    Console.WriteLine(item);
}

Manuelle Paginierung

Um einzelne Seitenelemente abzurufen und die nächste Seite manuell anzufordern:
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-Integration

Dienstregistrierung

Registrieren Sie den Client in 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();

Konfiguration

Fügen Sie die Konfiguration in appsettings.json hinzu:
appsettings.json
{
  "DodoPayments": {
    "ApiKey": "your_api_key_here"
  }
}

API-Controller

Erstellen Sie einen Controller mithilfe von Dependency Injection:
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);

Service-Layer-Muster

Erstellen Sie einen Service für die Geschäftslogik:
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;
        }
    }
}

User Secrets (Entwicklung)

Verwenden Sie für die Entwicklung User Secrets zur Speicherung von API-Schlüsseln:
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"

Tests

Beispiel für einen Unit-Test mit 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);
    }
}

Ressourcen

Support

Brauchen Sie Hilfe mit dem C#-SDK?

Beiträge

Wir freuen uns über Beiträge! Lesen Sie die Contributing Guidelines, um loszulegen.