> ## 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#

> Integre os pagamentos Dodo em suas aplicações .NET com suporte moderno a async/await

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

```bash theme={null}
dotnet add package DodoPayments.Client
```

<Info>
  O SDK requer .NET 8.0 ou posterior. Funciona com ASP.NET Core, aplicativos de console e outros tipos de projetos .NET.
</Info>

## Início Rápido

Inicialize o cliente e crie uma sessão de checkout:

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

## Recursos Principais

<CardGroup cols={2}>
  <Card title="Async/Await" icon="bolt">
    API totalmente assíncrona baseada em Task para operações não bloqueantes
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Segurança abrangente de tipo com tipos de referência anuláveis
  </Card>

  <Card title="Smart Retries" icon="repeat">
    Tentativas automáticas com recuo exponencial para erros transitórios
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Hierarquia de exceções integrada para gerenciamento preciso de erros
  </Card>
</CardGroup>

## Configuração

### Variáveis de Ambiente

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

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

| Propriedade   | Variável de ambiente        | Obrigatório | Valor padrão                      |
| ------------- | --------------------------- | ----------- | --------------------------------- |
| `BearerToken` | `DODO_PAYMENTS_API_KEY`     | true        | -                                 |
| `WebhookKey`  | `DODO_PAYMENTS_WEBHOOK_KEY` | false       | -                                 |
| `BaseUrl`     | `DODO_PAYMENTS_BASE_URL`    | true        | `"https://live.dodopayments.com"` |

### Configuração Manual

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

### Ambientes

Alterne entre modo ao vivo e teste:

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

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

### Timeouts

As requisições expiram após 1 minuto por padrão.

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

### Substituições por Solicitação

Modifique temporariamente a configuração para uma única solicitação usando `WithOptions`:

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

```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}");
```

### Gerenciar 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})");
```

### Manipular Assinaturas

```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` requer, no mínimo, o código `Country` ISO de duas letras. Use `AttachExistingCustomer` para associar um cliente existente, ou `NewCustomer` para criar um. `ProductPrice` está na menor denominação de moeda.
</Info>

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

Outros tipos de exceções:

* `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`:

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

### Paginação 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();
}
```

## Integração com ASP.NET Core

Registre o cliente no seu contêiner de 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 desenvolvimento, use [segredos de usuário](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets) em vez de armazenar chaves no `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">
    Veja o pacote na NuGet Gallery
  </Card>

  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-csharp">
    Veja o código fonte e contribua
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Documentação completa da API
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Obtenha ajuda e conecte-se com desenvolvedores
  </Card>
</CardGroup>

## Suporte

Precisa de ajuda com o SDK C#?

* **Discord**: Junte-se ao nosso [servidor da comunidade](https://discord.gg/bYqAp4ayYh) para suporte em tempo real
* **Email**: Entre em contato pelo [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Abra uma issue no [repositório](https://github.com/dodopayments/dodopayments-csharp)
