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

> Tích hợp Dodo Payments vào các ứng dụng .NET của bạn với hỗ trợ async/await hiện đại

SDK C# cung cấp quyền truy cập thuận tiện vào Dodo Payments REST API từ các ứng dụng viết bằng C#. Nó có API dựa trên async Task với kiểu dữ liệu mạnh, tự động thử lại và xử lý lỗi toàn diện.

## Cài đặt

Cài đặt gói từ [NuGet](https://www.nuget.org/packages/DodoPayments.Client):

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

<Info>
  SDK yêu cầu .NET 8.0 trở lên. Nó hoạt động với ASP.NET Core, các ứng dụng Console và các loại dự án .NET khác.
</Info>

## Bắt đầu nhanh

Khởi tạo client và tạo phiên thanh toán:

```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>
  Luôn lưu trữ khóa API của bạn một cách an toàn bằng biến môi trường, user secrets hoặc Azure Key Vault. Không bao giờ viết cứng chúng vào mã nguồn hoặc cam kết chúng lên hệ thống điều khiển phiên bản.
</Warning>

## Tính năng chính

<CardGroup cols={2}>
  <Card title="Async/Await" icon="bolt">
    API bất đồng bộ dựa trên Task đầy đủ cho các thao tác không chặn
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Đảm bảo kiểu dữ liệu toàn diện với nullable reference types
  </Card>

  <Card title="Smart Retries" icon="repeat">
    Tự động thử lại với độ trễ tăng dần cho các lỗi tạm thời
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Hệ thống ngoại lệ tích hợp cho việc quản lý lỗi chính xác
  </Card>
</CardGroup>

## Cấu hình

### Biến môi trường

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

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

| Thuộc tính    | Biến môi trường             | Bắt buộc | Giá trị mặc định                  |
| ------------- | --------------------------- | -------- | --------------------------------- |
| `BearerToken` | `DODO_PAYMENTS_API_KEY`     | true     | -                                 |
| `WebhookKey`  | `DODO_PAYMENTS_WEBHOOK_KEY` | false    | -                                 |
| `BaseUrl`     | `DODO_PAYMENTS_BASE_URL`    | true     | `"https://live.dodopayments.com"` |

### Cấu hình Thủ công

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

### Môi trường

Chuyển đổi giữa chế độ thực và chế độ kiểm tra:

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

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

### Thử Lại

SDK tự động thử lại 2 lần theo mặc định với độ trễ tăng dần. Nó thử lại trên các lỗi kết nối và mã trạng thái 408, 409, 429 và 5xx.

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

### Thời gian chờ

Các yêu cầu sẽ hết thời gian chờ sau 1 phút theo mặc định.

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

### Ghi đè theo Yêu cầu

Tạm thời thay đổi cấu hình cho một yêu cầu duy nhất bằng cách sử dụng `WithOptions`:

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

## Các Hoạt động Thông thường

### Tạo Phiên Thanh Toán

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

### Quản lý Khách hàng

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

### Xử lý Đăng ký

```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` yêu cầu tối thiểu mã ISO hai chữ cái `Country`. Sử dụng `AttachExistingCustomer` để đính kèm khách hàng hiện có, hoặc `NewCustomer` để tạo một khách hàng mới. `ProductPrice` là trong mệnh giá tiền tệ thấp nhất.
</Info>

## Xử lý lỗi

SDK ném ra các ngoại lệ cụ thể dựa trên mã trạng thái HTTP. Tất cả các lỗi 4xx đều kế thừa từ `DodoPayments4xxException`.

| Trạng thái | Ngoại lệ                                    |
| ---------- | ------------------------------------------- |
| 400        | `DodoPaymentsBadRequestException`           |
| 401        | `DodoPaymentsUnauthorizedException`         |
| 403        | `DodoPaymentsForbiddenException`            |
| 404        | `DodoPaymentsNotFoundException`             |
| 422        | `DodoPaymentsUnprocessableEntityException`  |
| 429        | `DodoPaymentsRateLimitException`            |
| 5xx        | `DodoPayments5xxException`                  |
| others     | `DodoPaymentsUnexpectedStatusCodeException` |

Các loại ngoại lệ khác:

* `DodoPaymentsIOException`: lỗi mạng I/O
* `DodoPaymentsInvalidDataException`: Thất bại trong xử lý dữ liệu đã phân tích
* `DodoPaymentsException`: Lớp cơ sở cho tất cả các ngoại lệ

## Phân trang

### Phân trang tự động

Lặp qua tất cả các kết quả trên tất cả các trang bằng phương thức `Paginate`, phương thức này trả về `IAsyncEnumerable`:

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

### Phân trang thủ công

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

## Tích hợp ASP.NET Core

Đăng ký khách hàng trong container DI của bạn:

```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>
  Trong quá trình phát triển, sử dụng [user secrets](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets) thay vì lưu trữ khóa trong `appsettings.json`:

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

## Tài nguyên

<CardGroup cols={2}>
  <Card title="NuGet Package" icon="box" href="https://www.nuget.org/packages/DodoPayments.Client">
    Xem gói trên NuGet Gallery
  </Card>

  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-csharp">
    Xem mã nguồn và đóng góp
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Tài liệu API hoàn chỉnh
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Nhận trợ giúp và kết nối với các nhà phát triển
  </Card>
</CardGroup>

## Hỗ trợ

Cần trợ giúp với C# SDK?

* **Discord**: Tham gia [máy chủ cộng đồng](https://discord.gg/bYqAp4ayYh) của chúng tôi để được hỗ trợ theo thời gian thực
* **Email**: Liên hệ với chúng tôi tại [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Mở một vấn đề trên [kho lưu trữ](https://github.com/dodopayments/dodopayments-csharp)
