O SDK C# fornece acesso conveniente à API REST do Dodo Payments a partir de aplicativos escritos em C#. Ele possui uma API baseada em Tarefas assíncronas com forte tipagem, tentativas automáticas e tratamento de erros abrangente.
Instalação
Instale o pacote do NuGet :
dotnet add package DodoPayments.Client
O SDK requer .NET 8.0 ou posterior. 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
Smart Retries Tentativas automáticas com recuo exponencial para erros transitórios
Error Handling Hierarquia de exceções integrada para gerenciamento preciso de erros
Configuração
Variáveis de Ambiente
DODO_PAYMENTS_API_KEY = your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new ();
Propriedade Variável de ambiente Obrigatório Valor padrão BearerTokenDODO_PAYMENTS_API_KEYtrue - WebhookKeyDODO_PAYMENTS_WEBHOOK_KEYfalse - BaseUrlDODO_PAYMENTS_BASE_URLtrue "https://live.dodopayments.com"
Configuração Manual
DodoPaymentsClient client = new () { BearerToken = "My Bearer Token" };
Ambientes
Alterne entre modo ao vivo e teste:
using DodoPayments . Client . Core ;
DodoPaymentsClient client = new () { BaseUrl = EnvironmentUrl . TestMode };
Retentativas
O SDK tenta novamente automaticamente 2 vezes por padrão com recuo exponencial. Ele tenta novamente em erros de conexão e códigos de status 408, 409, 429 e 5xx.
// Custom retry count
DodoPaymentsClient client = new () { MaxRetries = 3 };
Timeouts
As requisições expiram após 1 minuto por padrão.
DodoPaymentsClient client = new () { Timeout = TimeSpan . FromSeconds ( 30 ) };
Substituições por Solicitação
Modifique temporariamente a configuração para uma única solicitação usando WithOptions:
var response = await client
. WithOptions ( options => options with
{
Timeout = TimeSpan . FromSeconds ( 10 ),
MaxRetries = 5 ,
})
. CheckoutSessions . Create ( parameters );
Operações Comuns
Criar 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
// Create a customer
var customer = await client . Customers . Create ( new CustomerCreateParams
{
Email = "customer@example.com" ,
Name = "John Doe"
});
// Retrieve customer
var retrieved = await client . Customers . Retrieve ( "cus_123" );
Console . WriteLine ( $"Customer: { retrieved . Name } ( { retrieved . Email } )" );
Manipular Assinaturas
// Create a subscription
var subscription = await client . Subscriptions . Create ( new SubscriptionCreateParams
{
CustomerID = "cus_123" ,
ProductID = "prod_456" ,
PriceID = "price_789"
});
// Cancel subscription
await client . Subscriptions . Cancel ( subscription . Id );
Tratamento de Erros
O SDK lança exceções específicas com base no código de status HTTP. Todos os erros 4xx herdam de DodoPayments4xxException.
Status Exceção 400 DodoPaymentsBadRequestException401 DodoPaymentsUnauthorizedException403 DodoPaymentsForbiddenException404 DodoPaymentsNotFoundException422 DodoPaymentsUnprocessableEntityException429 DodoPaymentsRateLimitException5xx DodoPayments5xxExceptionoutros DodoPaymentsUnexpectedStatusCodeException
Outros tipos de exceção:
DodoPaymentsIOException: Erros de rede I/O
DodoPaymentsInvalidDataException: Falha ao interpretar dados analisados
DodoPaymentsException: Classe base para todas as exceções
Paginação
Paginação Automática
Itere por todos os resultados em todas as páginas usando o método Paginate, que retorna um IAsyncEnumerable:
var page = await client . Payments . List ( parameters );
await foreach ( var item in page . Paginate ())
{
Console . WriteLine ( item );
}
Paginação Manual
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 ();
}
Registre o cliente em seu contêiner de DI:
using DodoPayments . Client ;
var builder = WebApplication . CreateBuilder ( args );
builder . Services . AddSingleton < DodoPaymentsClient >( sp =>
{
var configuration = sp . GetRequiredService < IConfiguration >();
return new DodoPaymentsClient
{
BearerToken = configuration [ "DodoPayments:ApiKey" ]
};
});
var app = builder . Build ();
app . Run ();
{
"DodoPayments" : {
"ApiKey" : "your_api_key_here"
}
}
Para desenvolvimento, use segredos do usuário em vez de armazenar chaves no appsettings.json: dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"
Recursos
NuGet Package Veja o pacote na Galeria do NuGet
GitHub Repository Veja o código-fonte e contribua
API Reference Documentação completa da API
Discord Community Obtenha ajuda e conecte-se com desenvolvedores
Suporte
Precisa de ajuda com o SDK C#?