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

> Integrate Dodo Payments into your .NET applications with modern async/await support

The C# SDK provides convenient access to the Dodo Payments REST API from applications written in C#. It features an async Task-based API with strong typing, automatic retries, and comprehensive error handling.

## Installation

Install the package from [NuGet](https://www.nuget.org/packages/DodoPayments.Client):

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

<Info>
  The SDK requires .NET 8.0 or later. It works with ASP.NET Core, Console applications, and other .NET project types.
</Info>

## Quick Start

Initialize the client and create a checkout session:

```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>
  Always store your API keys securely using environment variables, user secrets, or Azure Key Vault. Never hardcode them in your source code or commit them to version control.
</Warning>

## Core Features

<CardGroup cols={2}>
  <Card title="Async/Await" icon="bolt">
    Full async Task-based API for non-blocking operations
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Comprehensive type safety with nullable reference types
  </Card>

  <Card title="Smart Retries" icon="repeat">
    Automatic retries with exponential backoff for transient errors
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Built-in exception hierarchy for precise error management
  </Card>
</CardGroup>

## Configuration

### Environment Variables

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

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

| Property      | Environment variable        | Required | Default value                     |
| ------------- | --------------------------- | -------- | --------------------------------- |
| `BearerToken` | `DODO_PAYMENTS_API_KEY`     | true     | -                                 |
| `WebhookKey`  | `DODO_PAYMENTS_WEBHOOK_KEY` | false    | -                                 |
| `BaseUrl`     | `DODO_PAYMENTS_BASE_URL`    | true     | `"https://live.dodopayments.com"` |

### Manual Configuration

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

### Environments

Switch between live and test mode:

```csharp theme={null}
using DodoPayments.Client.Core;

DodoPaymentsClient client = new() { BaseUrl = EnvironmentUrl.TestMode };
```

### Retries

The SDK automatically retries 2 times by default with exponential backoff. It retries on connection errors and status codes 408, 409, 429, and 5xx.

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

### Timeouts

Requests time out after 1 minute by default.

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

### Per-Request Overrides

Temporarily modify configuration for a single request using `WithOptions`:

```csharp theme={null}
var response = await client
    .WithOptions(options => options with
    {
        Timeout = TimeSpan.FromSeconds(10),
        MaxRetries = 5,
    })
    .CheckoutSessions.Create(parameters);
```

## Common Operations

### Create a Checkout Session

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

### Manage Customers

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

### Handle Subscriptions

```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`은 최소한 두 자리 ISO `Country` 코드를 요구합니다. 기존 고객을 첨부하려면 `AttachExistingCustomer`를 사용하거나, 새로 생성하려면 `NewCustomer`를 사용하세요. `ProductPrice`는 가장 낮은 화폐 단위입니다.
</Info>

## 에러 처리

SDK는 HTTP 상태 코드에 따라 특정 예외를 던집니다. 모든 4xx 오류는 `DodoPayments4xxException`로부터 상속됩니다.

| 상태     | 예외                                          |
| ------ | ------------------------------------------- |
| 400    | `DodoPaymentsBadRequestException`           |
| 401    | `DodoPaymentsUnauthorizedException`         |
| 403    | `DodoPaymentsForbiddenException`            |
| 404    | `DodoPaymentsNotFoundException`             |
| 422    | `DodoPaymentsUnprocessableEntityException`  |
| 429    | `DodoPaymentsRateLimitException`            |
| 5xx    | `DodoPayments5xxException`                  |
| others | `DodoPaymentsUnexpectedStatusCodeException` |

다른 예외 유형:

* `DodoPaymentsIOException`: I/O 네트워킹 오류
* `DodoPaymentsInvalidDataException`: 파싱된 데이터를 해석하는 데 실패함
* `DodoPaymentsException`: 모든 예외의 기본 클래스

## 페이지 매기기

### 자동 페이지 매기기

모든 페이지의 모든 결과를 반복 처리하려면 `Paginate` 메서드를 사용하여 `IAsyncEnumerable`를 반환합니다:

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

### 수동 페이지 매기기

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

## ASP.NET Core 통합

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>
  개발 중에는 키를 `appsettings.json`에 저장하는 대신 [사용자 비밀](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets)을 사용하세요:

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

## 리소스

<CardGroup cols={2}>
  <Card title="NuGet Package" icon="box" href="https://www.nuget.org/packages/DodoPayments.Client">
    NuGet Gallery에서 패키지 보기
  </Card>

  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-csharp">
    소스 코드 보기 및 기여
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    완전한 API 문서
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    도움 받기 및 개발자와 연결
  </Card>
</CardGroup>

## 지원

C# SDK에 대한 도움이 필요하신가요?

* **디스코드**: 실시간 지원을 위해 [커뮤니티 서버](https://discord.gg/bYqAp4ayYh)에 참여하세요
* **이메일**: [support@dodopayments.com](mailto:support@dodopayments.com)으로 연락하세요
* **GitHub**: [저장소](https://github.com/dodopayments/dodopayments-csharp)에서 이슈를 열어주세요
