Pular para o conteúdo principal
O SDK C# fornece acesso conveniente à API REST do Dodo Payments a partir de aplicativos escritos em C#. Ele apresenta uma API assíncrona baseada em Task com tipagem forte.

Instalação

Instale o SDK usando o CLI do .NET:
dotnet add package DodoPayments.Client
O SDK requer .NET Standard 2.0 ou superior. Ele funciona com ASP.NET Core, aplicativos de Console e outros tipos de projetos .NET.

Início Rápido

Inicialize o cliente e crie uma sessão de checkout:
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);
Sempre armazene suas chaves da API de forma segura usando variáveis de ambiente, segredos de usuário ou Azure Key Vault. Nunca os codifique diretamente no seu código-fonte ou os envie para o controle de versão.

Recursos Principais

Async/Await

API totalmente assíncrona baseada em Task para operações não bloqueantes

Strong Typing

Segurança abrangente de tipo com tipos de referência anuláveis

Dependency Injection

Suporte de primeira classe para injeção de dependência .NET

Configuration

Configuração simples via variáveis de ambiente ou appsettings.json

Configuração

Variáveis de Ambiente

Configure usando variáveis de ambiente:
.env
DODO_PAYMENTS_API_KEY=your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new();
Consulte esta tabela para ver as opções disponíveis:
PropriedadeVariável de ambienteObrigatórioValor padrão
BearerTokenDODO_PAYMENTS_API_KEYtrue-
WebhookKeyDODO_PAYMENTS_WEBHOOK_KEYfalse-
BaseUrlDODO_PAYMENTS_BASE_URLtrue"https://live.dodopayments.com"

Configuração Manual

Configure manualmente com token bearer:
DodoPaymentsClient client = new() { BearerToken = "My Bearer Token" };

Operações Comuns

Criar uma Sessão de Checkout

Gere uma sessão de checkout:
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}");

Gerenciar Clientes

Crie e recupere informações de clientes:
// 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})");

Gerenciar Assinaturas

Crie e gerencie assinaturas recorrentes:
// 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);

Paginação

O SDK define métodos que retornam listas paginadas de resultados com formas convenientes de acessar resultados página por página ou item por item em todas as páginas.

Paginação Automática

Para iterar por todos os resultados em todas as páginas, use o método Paginate:
using System;

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

Paginação Manual

Para acessar itens de página individuais e solicitar manualmente a próxima página:
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();
}

Integração com ASP.NET Core

Registro de Serviço

Registre o cliente em 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();

Configuração

Adicione a configuração em appsettings.json:
appsettings.json
{
  "DodoPayments": {
    "ApiKey": "your_api_key_here"
  }
}

Controlador de API

Crie um controlador usando injeção de dependência:
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);

Padrão da Camada de Serviço

Crie um serviço para lógica de negócios:
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 (Desenvolvimento)

Para desenvolvimento, use user secrets para armazenar chaves da API:
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"

Testes

Exemplo de teste unitário 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

Suporte

Precisa de ajuda com o SDK C#?

Contribuindo

Recebemos contribuições! Consulte as diretrizes de contribuição para começar.