Saltar al contenido principal
El SDK de C# proporciona acceso conveniente a la API REST de Dodo Payments desde aplicaciones escritas en C#. Presenta una API basada en tareas asíncronas con tipado fuerte y actualmente está en beta.
El SDK de C# está actualmente en beta. Estamos trabajando activamente en mejoras y agradecemos tus comentarios.

Instalación

Instala el SDK usando la CLI de .NET:
dotnet add package DodoPayments.Client
El SDK requiere .NET 8.0 o superior. Funciona con ASP.NET Core, aplicaciones de consola y otros tipos de proyectos .NET.

Inicio Rápido

Inicializa el cliente y crea una sesión de pago:
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);
Siempre almacena tus claves API de forma segura utilizando variables de entorno, secretos de usuario o Azure Key Vault. Nunca las codifiques directamente en tu código fuente ni las cometas en el control de versiones.

Características Principales

Async/Await

API completa basada en tareas asíncronas para operaciones no bloqueantes

Tipado Fuerte

Seguridad de tipo integral con tipos de referencia anulables

Inyección de Dependencias

Soporte de primera clase para la inyección de dependencias en .NET

Configuración

Configuración simple a través de variables de entorno o appsettings.json

Configuración

Variables de Entorno

Configura usando variables de entorno:
.env
DODO_PAYMENTS_API_KEY=your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new();

Configuración Manual

Configura manualmente con el token de portador:
DodoPaymentsClient client = new() { BearerToken = "My Bearer Token" };

Operaciones Comunes

Crear una Sesión de Pago

Genera una sesión de pago:
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}");

Gestionar Clientes

Crea y recupera información del cliente:
// Create a customer
var createParams = new CustomerCreateParams
{
    Email = "[email protected]",
    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})");

Manejar Suscripciones

Crea y gestiona suscripciones recurrentes:
// 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);

Integración con ASP.NET Core

Registro de Servicios

Registra el cliente en 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();

Configuración

Agrega configuración en appsettings.json:
appsettings.json
{
  "DodoPayments": {
    "ApiKey": "your_api_key_here"
  }
}

Controlador API

Crea un controlador usando inyección de dependencias:
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);

Patrón de Capa de Servicio

Crea un servicio para la lógica de negocio:
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;
        }
    }
}

Secretos de Usuario (Desarrollo)

Para desarrollo, usa secretos de usuario para almacenar claves API:
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"

Pruebas

Ejemplo de prueba unitaria usando 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);
    }
}

Recursos

Soporte

¿Necesitas ayuda con el SDK de C#?

Contribuyendo

Dado que el SDK está en beta, ¡tus comentarios y contribuciones son especialmente valiosos! Consulta las directrices de contribución para comenzar.