# C# SDK

`Tomba` NuGet 包是 [Tomba API](/introduction) 的官方 .NET 客户端。每个 API 功能区对应一个服务类，每个方法发送 1 个请求，并返回原始的 `HttpResponseMessage`。

## 要求

- .NET 10。该包的 1.0.1 版本仅面向 `net10.0`。
- [`Newtonsoft.Json`](https://www.nuget.org/packages/Newtonsoft.Json)，作为依赖项安装。

## 安装

```bash
dotnet add package Tomba
```

这些类位于 `Tomba` 命名空间中。

## 认证

在 [API keys](https://app.tomba.io/api) 页面创建 API 密钥并复制您的 Secret，然后将它们都导出：

```bash
export TOMBA_API_KEY="ta_xxxx"
export TOMBA_SECRET_KEY="ts_xxxx"
```

SDK 不会读取环境变量。将这些值传给 `SetKey()` 和 `SetSecret()`，客户端会将它们作为 `X-Tomba-Key` 和 `X-Tomba-Secret` 请求头发送。每个 setter 在每个客户端上只能调用一次：第二次调用会抛出 `ArgumentException`。有关密钥过期和轮换，请参阅[认证](/authentication)。

## 首个请求

验证一个邮箱地址。

```csharp
using Newtonsoft.Json.Linq;
using Tomba;

var client = new Client()
    .SetKey(Environment.GetEnvironmentVariable("TOMBA_API_KEY"))
    .SetSecret(Environment.GetEnvironmentVariable("TOMBA_SECRET_KEY"));

var response = await new Verifier(client).EmailVerifier("jane.doe@stripe.com");
var body = JObject.Parse(await response.Content.ReadAsStringAsync());
Console.WriteLine(body["data"]?["email"]?["status"]);
```

该示例是一个使用顶级语句的 `dotnet new console` 程序。方法返回未经解析的 `HttpResponseMessage`，因此需要您自行读取并解析 JSON 响应体。API 会将有效负载包装在 `data` 对象中（[响应格式](/introduction#response-format)）；验证状态位于 `data.email.status`。

## 错误

当 API 返回 400 或更高的状态码时，以及请求失败时，SDK 会抛出 `TombaException`。对于 API 错误，该异常是嵌套的：外层 `TombaException` 的 `Message` 是 API 的 `errors.message`，其 `InnerException` 是一个 `TombaException`，其中 `Code` 为 HTTP 状态码，`Response` 为原始响应体。

```csharp
using Newtonsoft.Json.Linq;
using Tomba;

var client = new Client()
    .SetKey(Environment.GetEnvironmentVariable("TOMBA_API_KEY"))
    .SetSecret(Environment.GetEnvironmentVariable("TOMBA_SECRET_KEY"));

try
{
    var response = await new Verifier(client).EmailVerifier("jane.doe@stripe.com");
    var body = JObject.Parse(await response.Content.ReadAsStringAsync());
    Console.WriteLine(body["data"]?["email"]?["status"]);
}
catch (TombaException e)
{
    var inner = e.InnerException as TombaException;
    Console.WriteLine($"{inner?.Code} {e.Message}");
    Console.WriteLine(inner?.Response);
}
```

如果请求在收到响应之前就已失败，`inner` 为 `null`。原始 `Response` 是 JSON 错误响应体；其中每个 `errors.type` 的说明请参阅[错误](/error-handling#error-types)。

## 速率限制和重试

SDK 不会重试。`Client.ParseRateLimit(response)` 会将成功响应的[速率限制响应头](/rate-limits#rate-limit-headers)读取到一个 `RateLimit` 中，它包含 `int?` 类型的属性 `SecondRateLimit`、`MinuteRateLimit`、`DailyRateLimit`、`MinuteRequestLeft`、`DailyRequestLeft`、`MinuteResetSeconds`、`DailyResetSeconds` 和 `RetryAfter`，以及 `string` 类型的属性 `RateLimitPolicy` 和 `RateLimitValue`。

收到 `429` 时会抛出 `TombaException`，但不包含响应头。按照[处理 429 响应](/rate-limits#handle-429-responses)中的说明，等待一段时间后再重试。

请求在 120 秒后超时。

## 方法参考

使用客户端创建各个服务，例如 `new Verifier(client)`。每个方法都返回 `Task<HttpResponseMessage>`。

| 方法                                                                               | 端点                                                                    |
| ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| `Account.GetAccount()`                                                               | [`GET /me`](/api/account#get-account)                                       |
| `Usage.GetUsage()`                                                                   | [`GET /usage`](/api/account#retrieve-api-usage)                             |
| `Logs.GetLogs(int? page = null, int? limit = null)`                                  | [`GET /logs`](/api/account#retrieve-api-logs)                               |
| `Format.EmailFormatAsync(string domain)`                                             | [`GET /email-format`](/api/finder#email-format)                             |
| `Count.EmailCount(string domain)`                                                    | [`GET /email-count`](/api/finder#email-count)                               |
| `Verifier.EmailVerifier(string email, string webhookUrl = null)`                     | [`GET /email-verifier`](/api/verifier#email-verifier)                       |
| `Sources.EmailSources(string email)`                                                 | [`GET /email-sources`](/api/email#email-sources)                            |
| `Phone.FinderAsync(Dictionary<string, object> parameters, string webhookUrl = null)` | [`GET /phone-finder`](/api/phone#phone-finder)                              |
| `Phone.ValidatorAsync(string phone, string countryCode = null)`                      | [`GET /phone-validator`](/api/phone#phone-validator)                        |
| `Status.DomainStatus(string domain)`                                                 | [`GET /domain-status`](/api/domain#domain-status)                           |
| `Status.AutoComplete(string query)`                                                  | [`GET /domain-suggestions`](/api/domain-suggestions#get-domain-suggestions) |
| `Keys.GetKeys()`                                                                     | [`GET /keys`](/api/keys#retrieve-api-keys)                                  |
| `Keys.GetKey(string id)`                                                             | [`GET /keys/{id}`](/api/keys#retrieve-a-single-api-key)                     |
| `Keys.CreateKey()`                                                                   | [`POST /keys`](/api/keys#create-an-api-key)                                 |
| `Keys.ResetKey(string id)`                                                           | [`PUT /keys/{id}`](/api/keys#reset-an-api-key)                              |
| `Keys.DeleteKey(string id)`                                                          | [`DELETE /keys/{id}`](/api/keys#delete-an-api-key)                          |
| `Leads.ListLeadsAsync(int? page = 1, int? limit = 10, string domain = null)`         | [`GET /leads`](/api/leads#retrieve-leads)                                   |
| `Leads.GetLeadAsync(string id)`                                                      | [`GET /leads/{id}`](/api/leads#retrieve-a-single-lead)                      |
| `Leads.CreateLeadAsync(Dictionary<string, object> data)`                             | [`POST /leads`](/api/leads#create-a-lead)                                   |
| `Leads.UpdateLeadAsync(string id, Dictionary<string, object> data)`                  | [`PUT /leads/{id}`](/api/leads#update-a-lead)                               |
| `Leads.DeleteLeadAsync(string id)`                                                   | [`DELETE /leads/{id}`](/api/leads#delete-a-lead)                            |
| `LeadsLists.GetLists()`                                                              | [`GET /leads_lists`](/api/lead-lists#retrieve-leads-lists)                  |
| `LeadsLists.DeleteListId(string id)`                                                 | [`DELETE /leads_lists/{id}`](/api/lead-lists#delete-leads-list)             |
| `Bulk.ListAsync(string type, Dictionary<string, object> parameters = null)`          | [`GET /bulk/{type}`](/api/bulks)                                            |
| `Bulk.CreateAsync(string type, Dictionary<string, object> data)`                     | [`POST /bulk/{type}`](/api/bulks)                                           |
| `Bulk.GetAsync(string type, string id)`                                              | [`GET /bulk/{type}/{id}`](/api/bulks)                                       |
| `Bulk.ProgressAsync(string type, string id)`                                         | [`GET /bulk/{type}/{id}/progress`](/api/bulks)                              |
| `Bulk.DownloadAsync(string type, string id)`                                         | [`GET /bulk/{type}/{id}/download`](/api/bulks)                              |
| `Bulk.RenameAsync(string type, string id, string name)`                              | [`PUT /bulk/{type}/{id}/rename`](/api/bulks)                                |

`type` 是[批量类型](/bulks#bulk-types)中列出的 `{type}` 路径段。`CreateAsync` 发送 JSON 请求体，因此无法创建需要上传 CSV 的任务，例如[邮箱查找器](/bulks#email-finder)任务。

## 源代码

[github.com/tomba-io/csharp](https://github.com/tomba-io/csharp)（Apache-2.0）。版本说明见 [CHANGELOG.md](https://github.com/tomba-io/csharp/blob/master/CHANGELOG.md)。
