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

> Dodo Paymentsを.NETアプリケーションに統合するためのモダンなasync/awaitサポート

C# SDK は、C# で書かれたアプリケーションから Dodo Payments REST API へ便利にアクセスできるようにします。強い型付け、非同期タスクベース API、自動リトライ、および包括的なエラー処理を特徴としています。

## インストール

[NuGet](https://www.nuget.org/packages/DodoPayments.Client)からパッケージをインストールします。

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

<Info>
  このSDKは .NET 8.0 以降が必要です。ASP.NET Core、コンソールアプリケーション、その他の .NET プロジェクトタイプで動作します。
</Info>

## クイックスタート

クライアントを初期化し、チェックアウト セッションを作成します:

```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>
  API キーは常に、環境変数、ユーザー シークレット、または Azure Key Vault を使用して安全に保管してください。ソース コードにハードコードしたり、バージョン管理にコミットしたりしないでください。
</Warning>

## 主な機能

<CardGroup cols={2}>
  <Card title="Async/Await" icon="bolt">
    ノンブロッキング操作のための完全な async Task ベースの API
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Nullable 参照型を活用した包括的な型安全性
  </Card>

  <Card title="Smart Retries" icon="repeat">
    　一時的なエラーに対する指数バックオフでの自動リトライ
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    　正確なエラーマネジメントのための組み込み例外階層
  </Card>
</CardGroup>

## 構成

### 環境変数

```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"` |

### マニュアル設定

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

### 環境

ライブモードとテストモードを切り替えます。

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

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

### リトライ

SDK はデフォルトで 2 回、指数バックオフを伴って自動的にリトライします。接続エラーやステータスコード 408、409、429、および 5xx に対してリトライします。

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

### タイムアウト

リクエストはデフォルトで1分後にタイムアウトします。

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

### リクエストごとのオーバーライド

単一のリクエスト用に設定を一時的に変更するには、`WithOptions` を使用します。

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

## 共通の操作

### チェックアウトセッションを作成する

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

### 顧客を管理する

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

### サブスクリプションを処理する

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

## エラー処理

SDK は HTTP ステータスコードに基づいて特定の例外をスローします。すべての 4xx エラーは `DodoPayments4xxException` を継承します。

| Status | Exception                                   |
| ------ | ------------------------------------------- |
| 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ギャラリーでパッケージを表示する
  </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 についてのサポートが必要ですか？

* **Discord**: リアルタイムサポートのために[コミュニティサーバー](https://discord.gg/bYqAp4ayYh)に参加してください

* **Email**: [support@dodopayments.com](mailto:support@dodopayments.com) にご連絡ください

* **GitHub**: [リポジトリ](https://github.com/dodopayments/dodopayments-csharp)で問題を開いてください

* **Discord**: リアルタイムサポートのために[コミュニティサーバー](https://discord.gg/bYqAp4ayYh)に参加してください

* **Email**: [support@dodopayments.com](mailto:support@dodopayments.com) までお問い合わせください

* **GitHub**: [リポジトリ](https://github.com/dodopayments/dodopayments-csharp)でissueを開いてください
