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

# C#・.NET SDK：KYC・AML・取引モニタリング

> Didit公式C#・.NET SDKのクイックスタート。サーバーAPIの非同期型付き呼び出し、依存性注入、Webhook検証、トークンチェックに対応しています。

Didit公式のC#および.NET向けライブラリです。.NET 8と.NET Standard 2.0を対象としており、すべてのAPIメソッドは`async`です。.NET Frameworkでは、C# 11以降を使用してください。すべてのSDKに共通する事項については、[サーバーSDKの概要](https://docs.didit.me/ja/integration/server-sdks/overview.md)を参照してください。

## インストール

```bash theme={null}
dotnet add package Didit
```

ASP.NET Coreの依存性注入を使う場合は、`Didit.Extensions.DependencyInjection`も追加し、`services.AddDidit()`でクライアントを登録します。

パッケージはNuGet上の[`Didit`](https://www.nuget.org/packages/Didit)と[`Didit.Extensions.DependencyInjection`](https://www.nuget.org/packages/Didit.Extensions.DependencyInjection)です。ソースコードと変更履歴はGitHubの[didit-protocol/sdk-dotnet](https://github.com/didit-protocol/sdk-dotnet)にあります。

## クライアントを設定する

`new DiditClient()`は環境変数から`DIDIT_API_KEY`を読み込みます。これを上書きする場合や、アプリケーション単位の呼び出し(ケース、ネットワーク、規制レポート)に必要な組織IDとアプリケーションIDを設定する場合は、`DiditClientOptions`を渡してください。クライアントは1つ作成して再利用します。

```csharp theme={null}
using System;
using Didit;

using var client = new DiditClient(new DiditClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("DIDIT_API_KEY"),
    OrganizationId = Environment.GetEnvironmentVariable("DIDIT_ORGANIZATION_ID"),
    ApplicationId = Environment.GetEnvironmentVariable("DIDIT_APPLICATION_ID"),
    Timeout = TimeSpan.FromSeconds(30),
    MaxRetries = 2,
});

// Options for a single call.
var decision = await client.Sessions.RetrieveDecisionAsync(
    "11111111-2222-3333-4444-555555555555",
    requestOptions: new RequestOptions { Timeout = TimeSpan.FromSeconds(5), MaxRetries = 0 });
Console.WriteLine(decision.Status);
```

必須のリクエストプロパティには`required`が付いているため、指定し忘れるとコンパイルに失敗します。未設定のままにした任意のプロパティは送信されません。

## セッションを作成する

ワークフローに対して[検証セッション](https://docs.didit.me/ja/sessions-api/create-session.md)を作成し、ユーザーをそのURLに誘導します。

```csharp theme={null}
using System;
using Didit;

using var client = new DiditClient();

var session = await client.Sessions.CreateAsync(new SessionsCreateParams
{
    WorkflowId = "11111111-2222-3333-4444-555555555555",
    VendorData = "user-123",
    Callback = "https://example.com/verification/done",
});
Console.WriteLine(session.Url);
```

## 判定を読み取る

ユーザーが完了したとき、またはWebhookが届いたときに、[判定を読み取ってください](https://docs.didit.me/ja/sessions-api/retrieve-session.md)。各機能の結果はリストで、ワークフローのノードごとに1つのエントリがあります。

```csharp theme={null}
using System;
using Didit;

using var client = new DiditClient();

var decision = await client.Sessions.RetrieveDecisionAsync("11111111-2222-3333-4444-555555555555");
Console.WriteLine(decision.Status);
foreach (var verification in decision.IdVerifications ?? Array.Empty<SessionDecisionIdVerifications>())
{
    Console.WriteLine(verification.Status);
}
```

## Webhookを検証する

受信したままの生のボディと、リクエストヘッダーを読み取る手段を渡します。`DiditWebhooks.Verify`は、有効かつ有効期限内の配信でないものに対しては`WebhookVerificationException`をスローし、それ以外の場合は型付きのイベントを返します。

```csharp theme={null}
using System;
using Didit;

var secret = Environment.GetEnvironmentVariable("DIDIT_WEBHOOK_SECRET") ?? "";

int HandleWebhook(string rawBody, Func<string, string?> header)
{
    try
    {
        var evt = DiditWebhooks.Verify(rawBody, header, secret);
        if (evt is SessionStatusUpdatedEvent updated)
        {
            Console.WriteLine($"{updated.SessionId} {updated.Status}");
        }
        return 200;
    }
    catch (WebhookVerificationException error)
    {
        Console.WriteLine($"rejected: {error.Reason}");
        return 400;
    }
}
```

ASP.NET CoreのMinimal APIでは、`StreamReader`でボディを読み取り、`name => request.Headers[name].FirstOrDefault()`を渡します。シークレットをローテーションしている間は、`new[] { newSecret, oldSecret }`のように両方を渡してください。イベントと署名方式については[Webhook](https://docs.didit.me/ja/integration/webhooks.md)を参照してください。

## 取引をスクリーニングする

支払い、出金、または暗号資産の送金を[取引モニタリング](https://docs.didit.me/ja/transaction-monitoring/overview.md)に送信します。レスポンスにはそのステータスとリスクスコアが含まれます。

```csharp theme={null}
using System;
using Didit;

using var client = new DiditClient();

var transaction = await client.Transactions.CreateAsync(new TransactionsCreateParams
{
    TransactionId = "txn-1001",
    TransactionCategory = "finance",
    TransactionDetails = new()
    {
        Direction = "outbound",
        Amount = 1500,
        Currency = "EUR",
    },
    Subject = new()
    {
        EntityType = "individual",
        VendorData = "user-123",
        FullName = "Maria Garcia",
    },
});
Console.WriteLine($"{transaction.Status} {transaction.Score}");
```

## Authenticationトークンを検証する

`Authentication`は、[Authentication](https://docs.didit.me/ja/authentication/overview.md)の発行者が署名したアクセストークンを、リクエストごとにDiditを呼び出すことなくバックエンドで検証します。また、コードの交換、トークンの更新、セッションの確認と失効、ステップアップ認証の実行も行います。

> [!NOTE]
>
> トークンの検証では、アプリケーションの発行者と署名鍵に対して、[サーバーでトークンを検証する](https://docs.didit.me/ja/authentication/tokens-and-jwks.md#サーバーでトークンを検証する)に記載されたチェックを行います。

```csharp theme={null}
using System;
using System.Threading.Tasks;
using Didit;

// The publishable key (pk_live_... or pk_test_...) carries your issuer URL.
var auth = Authentication.FromPublishableKey("pk_live_...");

async Task<string?> CurrentUserAsync(string accessToken)
{
    try
    {
        var claims = await auth.VerifyAccessTokenAsync(accessToken, audience: "your-application-id");
        return claims.Subject;
    }
    catch (TokenVerificationException error)
    {
        Console.WriteLine($"rejected: {error.Reason}");
        return null;
    }
}
```

## エラー

```csharp theme={null}
using System;
using Didit;

using var client = new DiditClient();

try
{
    await client.Sessions.RetrieveDecisionAsync("11111111-2222-3333-4444-555555555555");
}
catch (NotFoundException)
{
    Console.WriteLine("no such session");
}
catch (ApiStatusException error)
{
    Console.WriteLine($"{error.StatusCode} {error.RequestId}");
}
```

## リストとファイル

```csharp theme={null}
using System;
using Didit;

using var client = new DiditClient();

// Lists page through every result.
await foreach (var session in await client.Sessions.ListAsync(new SessionsListParams { Status = "Approved" }))
{
    Console.WriteLine(session.SessionId);
}

// Uploads take FileUpload.FromPath, FromBytes or FromStream.
var result = await client.IdVerification.VerifyAsync(new IdVerificationVerifyParams
{
    FrontImage = FileUpload.FromPath("id-front.jpg"),
    BackImage = FileUpload.FromPath("id-back.jpg"),
});
Console.WriteLine(result.IdVerification?.Status);
```

[APIリファレンス](https://docs.didit.me/ja/api-reference/overview.md)のサーバーエンドポイントの各ページには、その操作の.NETサンプルが掲載されています。ただし、[概要](https://docs.didit.me/ja/integration/server-sdks/overview.md)に記載されている、まだどの1.0.1リリースにも含まれていないエンドポイントとフィールドは除きます。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.