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, reintentos automáticos y manejo integral de errores.
Instalación
Instala el paquete desde NuGet :
dotnet add package DodoPayments.Client
El SDK requiere .NET 8.0 o posterior. 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 );
Guarda siempre tus claves de API de forma segura usando variables de entorno, secretos de usuario o Azure Key Vault. Nunca las codifiques directamente en tu código fuente ni las comprometas al control de versiones.
Funcionalidades principales
Async/Await API completa basada en Task asíncronos para operaciones no bloqueantes
Strong Typing Seguridad de tipos exhaustiva con tipos de referencia anulables
Smart Retries Reintentos automáticos con retroceso exponencial para errores transitorios
Error Handling Jerarquía de excepciones incorporada para una gestión precisa de errores
Configuración
Variables de entorno
DODO_PAYMENTS_API_KEY = your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new ();
Propiedad Variable de entorno Requerido Valor por defecto BearerTokenDODO_PAYMENTS_API_KEYtrue - WebhookKeyDODO_PAYMENTS_WEBHOOK_KEYfalse - BaseUrlDODO_PAYMENTS_BASE_URLtrue "https://live.dodopayments.com"
Configuración Manual
DodoPaymentsClient client = new () { BearerToken = "My Bearer Token" };
Entornos
Cambia entre el modo en vivo y de prueba:
using DodoPayments . Client . Core ;
DodoPaymentsClient client = new () { BaseUrl = EnvironmentUrl . TestMode };
Reintentos
El SDK vuelve a intentar automáticamente 2 veces por defecto con retroceso exponencial. Reintenta en errores de conexión y códigos de estado 408, 409, 429 y 5xx.
// Custom retry count
DodoPaymentsClient client = new () { MaxRetries = 3 };
Tiempos de Espera
Las solicitudes expiran después de 1 minuto por defecto.
DodoPaymentsClient client = new () { Timeout = TimeSpan . FromSeconds ( 30 ) };
Anulaciones Por Solicitud
Modifica temporalmente la configuración para una sola solicitud usando WithOptions:
var response = await client
. WithOptions ( options => options with
{
Timeout = TimeSpan . FromSeconds ( 10 ),
MaxRetries = 5 ,
})
. CheckoutSessions . Create ( parameters );
Operaciones Comunes
Crear 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
// 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 } )" );
Manejar Suscripciones
// 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 );
Manejo de Errores
El SDK lanza excepciones específicas basadas en el código de estado HTTP. Todos los errores 4xx heredan de DodoPayments4xxException.
Estado Excepción 400 DodoPaymentsBadRequestException401 DodoPaymentsUnauthorizedException403 DodoPaymentsForbiddenException404 DodoPaymentsNotFoundException422 DodoPaymentsUnprocessableEntityException429 DodoPaymentsRateLimitException5xx DodoPayments5xxExceptionotros DodoPaymentsUnexpectedStatusCodeException
Otros tipos de excepción:
DodoPaymentsIOException: Errores de red de E/S
DodoPaymentsInvalidDataException: Error al interpretar datos analizados
DodoPaymentsException: Clase base para todas las excepciones
Paginación
Auto-Paginación
Itera a través de todos los resultados en todas las páginas usando el método Paginate, que devuelve un IAsyncEnumerable:
var page = await client . Payments . List ( parameters );
await foreach ( var item in page . Paginate ())
{
Console . WriteLine ( item );
}
Paginación 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 ();
}
Integración ASP.NET Core
Registra el cliente en tu contenedor 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 el desarrollo, utiliza secretos de usuario en lugar de almacenar claves en appsettings.json:
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"
Recursos
Ver paquete en NuGet Gallery
Ver código fuente y contribuir
Documentación completa de la API
Obtén ayuda y conéctate con desarrolladores
Soporte
¿Necesitas ayuda con el SDK de C#?