> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# C#

> Integra Dodo Payments en tus aplicaciones .NET con soporte moderno de async/await

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](https://www.nuget.org/packages/DodoPayments.Client):

```bash theme={null}
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:

```csharp theme={null}
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);
```

<Warning>
  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.
</Warning>

## Funcionalidades principales

<CardGroup cols={2}>
  <Card title="Async/Await" icon="bolt">
    API completa basada en Task asíncronos para operaciones no bloqueantes
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Seguridad de tipos exhaustiva con tipos de referencia anulables
  </Card>

  <Card title="Smart Retries" icon="repeat">
    Reintentos automáticos con retroceso exponencial para errores transitorios
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Jerarquía de excepciones incorporada para una gestión precisa de errores
  </Card>
</CardGroup>

## Configuración

### Variables de entorno

```bash .env theme={null}
DODO_PAYMENTS_API_KEY=your_api_key_here
```

```csharp theme={null}
// Automatically reads from environment variables
DodoPaymentsClient client = new();
```

| Propiedad     | Variable de entorno         | Requerido | Valor por defecto                 |
| ------------- | --------------------------- | --------- | --------------------------------- |
| `BearerToken` | `DODO_PAYMENTS_API_KEY`     | true      | -                                 |
| `WebhookKey`  | `DODO_PAYMENTS_WEBHOOK_KEY` | false     | -                                 |
| `BaseUrl`     | `DODO_PAYMENTS_BASE_URL`    | true      | `"https://live.dodopayments.com"` |

### Configuración Manual

```csharp theme={null}
DodoPaymentsClient client = new() { BearerToken = "My Bearer Token" };
```

### Entornos

Cambia entre el modo en vivo y de prueba:

```csharp theme={null}
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.

```csharp theme={null}
// Custom retry count
DodoPaymentsClient client = new() { MaxRetries = 3 };
```

### Tiempos de Espera

Las solicitudes expiran después de 1 minuto por defecto.

```csharp theme={null}
DodoPaymentsClient client = new() { Timeout = TimeSpan.FromSeconds(30) };
```

### Anulaciones Por Solicitud

Modifica temporalmente la configuración para una sola solicitud usando `WithOptions`:

```csharp theme={null}
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

```csharp theme={null}
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.CheckoutUrl}");
```

### Gestionar Clientes

```csharp theme={null}
// 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

```csharp theme={null}
using DodoPayments.Client.Models.Payments;
using DodoPayments.Client.Models.Subscriptions;

// Create a subscription
var subscription = await client.Subscriptions.Create(new SubscriptionCreateParams
{
    Billing = new BillingAddress
    {
        Country = "US",
        City = "San Francisco",
        State = "CA",
        Street = "1 Market St",
        Zipcode = "94105",
    },
    Customer = new AttachExistingCustomer { CustomerID = "cus_123" },
    ProductID = "pdt_456",
    Quantity = 1,
});

// Charge an on-demand subscription
// ProductPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
var charge = await client.Subscriptions.Charge(
    subscription.SubscriptionId,
    new SubscriptionChargeParams { ProductPrice = 2500 }
);
```

<Info>
  `Billing` requiere al menos el código `Country` ISO de dos letras. Use `AttachExistingCustomer` para adjuntar un cliente existente, o `NewCustomer` para crear uno. `ProductPrice` está en la denominación más baja de la moneda.
</Info>

## 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    | `DodoPaymentsBadRequestException`           |
| 401    | `DodoPaymentsUnauthorizedException`         |
| 403    | `DodoPaymentsForbiddenException`            |
| 404    | `DodoPaymentsNotFoundException`             |
| 422    | `DodoPaymentsUnprocessableEntityException`  |
| 429    | `DodoPaymentsRateLimitException`            |
| 5xx    | `DodoPayments5xxException`                  |
| otros  | `DodoPaymentsUnexpectedStatusCodeException` |

Otros tipos de excepciones:

* `DodoPaymentsIOException`: errores de redes de E/S
* `DodoPaymentsInvalidDataException`: fallo al interpretar los datos analizados
* `DodoPaymentsException`: clase base para todas las excepciones

## Paginación

### Paginación Automática

Itere a través de todos los resultados en todas las páginas utilizando el método `Paginate`, que devuelve un `IAsyncEnumerable`:

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

### Paginación Manual

```csharp theme={null}
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 con ASP.NET Core

Registre el cliente en su contenedor DI:

```csharp Program.cs theme={null}
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();
```

```json appsettings.json theme={null}
{
  "DodoPayments": {
    "ApiKey": "your_api_key_here"
  }
}
```

<Tip>
  Para el desarrollo, use [secretos de usuario](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets) en lugar de almacenar claves en `appsettings.json`:

  ```bash theme={null}
  dotnet user-secrets init
  dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"
  ```
</Tip>

## Recursos

<CardGroup cols={2}>
  <Card title="NuGet Package" icon="box" href="https://www.nuget.org/packages/DodoPayments.Client">
    Ver paquete en NuGet Gallery
  </Card>

  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-csharp">
    Ver código fuente y contribuir
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Documentación completa de la API
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Obtenga ayuda y conéctese con desarrolladores
  </Card>
</CardGroup>

## Soporte

¿Necesita ayuda con el SDK de C#?

* **Discord**: Únase a nuestro [servidor de la comunidad](https://discord.gg/bYqAp4ayYh) para soporte en tiempo real
* **Email**: Contáctenos en [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Abra un issue en el [repositorio](https://github.com/dodopayments/dodopayments-csharp)
