# PHP SDK

`tomba-io/php` 是 [Tomba API](/introduction) 的官方 PHP 客户端。每个 API 功能区对应一个服务类，每个方法发送 1 个请求。

## 要求

- PHP 8.1 或更高版本，如 `composer.json` 中所声明。
- `curl` 和 `json` 扩展。

## 安装

```bash
composer require tomba-io/php
```

类从 `Tomba` 命名空间自动加载；服务类位于 `Tomba\Services` 中。

## 认证

在 [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` 请求头发送。有关密钥过期和轮换，请参阅[认证](/authentication)。

## 首个请求

查找某家公司中某个人的邮箱地址：

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Tomba\Client;
use Tomba\Services\Finder;

$client = (new Client())
    ->setKey(getenv('TOMBA_API_KEY'))
    ->setSecret(getenv('TOMBA_SECRET_KEY'));

$result = (new Finder($client))->emailFinder('stripe.com', 'Jane', 'Doe');
echo $result['data']['data']['email'], PHP_EOL;
```

每个方法都返回一个包含 2 个键的数组：`data`（解码后的 JSON 响应体）和 `rate_limit`。API 会将有效负载包装在它自己的 `data` 对象中（[响应格式](/introduction#response-format)），因此邮箱地址位于 `$result['data']['data']['email']`。

## 错误

当 API 返回 400 或更高的状态码时、cURL 失败时，以及在发送请求之前发现必填参数为空时，SDK 都会抛出 `Tomba\TombaException`。

| 方法          | 值                                                                                          |
| --------------- | ---------------------------------------------------------------------------------------------- |
| `getCode()`     | HTTP 状态码。如果错误发生在收到响应之前，则为 `0`。                   |
| `getMessage()`  | API 的 `errors.message`，或 cURL 错误。                                                 |
| `getResponse()` | 解码后的错误响应体 `['errors' => ['type' => …, 'message' => …, 'code' => …]]`，或 `null`。 |

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Tomba\Client;
use Tomba\Services\Finder;
use Tomba\TombaException;

$client = (new Client())
    ->setKey(getenv('TOMBA_API_KEY'))
    ->setSecret(getenv('TOMBA_SECRET_KEY'));

try {
    $result = (new Finder($client))->emailFinder('stripe.com', 'Jane', 'Doe');
    echo $result['data']['data']['email'], PHP_EOL;
} catch (TombaException $e) {
    echo $e->getCode(), ' ', $e->getMessage(), PHP_EOL;
    echo $e->getResponse()['errors']['type'] ?? '', PHP_EOL;
}
```

`Enrichment::person()`、`company()` 和 `combined()` 在未找到结果时不会抛出异常：这些端点会返回状态码 200 和一个 `errors` 响应体，因此需检查 `$result['data']['errors']`。每个 `errors.type` 的说明请参阅[错误](/error-handling#error-types)。

## 速率限制和重试

SDK 不会重试。`$result['rate_limit']` 保存响应的[速率限制响应头](/rate-limits#rate-limit-headers)，以标头名称为键：`x-second-rate-limit`、`x-minute-rate-limit`、`x-daily-rate-limit`、`x-minute-request-left`、`x-daily-request-left`、`x-minute-reset-seconds`、`x-daily-reset-seconds`、`retry-after`、`ratelimit-policy` 和 `ratelimit`。数值为整数，缺失的响应头为 `null`。

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

请求在 120 秒后超时；超时时间不可配置。

## 方法参考

使用客户端创建各个服务，例如 `new Finder($client)`。

| 方法                                                                                                                                                       | 端点                                                                    |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| `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)                               |
| `Domain::domainSearch(string $domain, int $page = null, int $limit = null, string $department = null, bool $enrichMobile = null, string $webhookUrl = null)` | [`GET /domain-search`](/api/finder#domain-search)                           |
| `Finder::emailFinder(string $domain, string $firstName, string $lastName, string $webhookUrl = null)`                                                        | [`GET /email-finder`](/api/finder#email-finder)                             |
| `Finder::authorFinder(string $url, string $webhookUrl = null)`                                                                                               | [`GET /author-finder`](/api/finder#author-finder)                           |
| `Finder::linkedinFinder(string $url, string $webhookUrl = null)`                                                                                             | [`GET /linkedin`](/api/finder#linkedin-finder)                              |
| `Format::emailFormat(string $domain)`                                                                                                                        | [`GET /email-format`](/api/finder#email-format)                             |
| `Location::getLocation(string $domain)`                                                                                                                      | [`GET /location`](/api/finder#location)                                     |
| `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)                            |
| `Enrichment::person(string $email, string $webhookUrl = null)`                                                                                               | [`GET /people/find`](/api/enrichment#person-api)                            |
| `Enrichment::company(string $domain)`                                                                                                                        | [`GET /companies/find`](/api/enrichment#company-api)                        |
| `Enrichment::combined(string $email)`                                                                                                                        | [`GET /combined/find`](/api/enrichment#combined-api)                        |
| `Finder::phoneFinder(string $email, string $webhookUrl = null)`                                                                                              | [`GET /phone-finder`](/api/phone#phone-finder)                              |
| `Phone::phoneFinder(array $params, string $webhookUrl = null)`                                                                                               | [`GET /phone-finder`](/api/phone#phone-finder)                              |
| `Phone::phoneValidator(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) |
| `Similar::websites(string $domain)`                                                                                                                          | [`GET /similar`](/api/domain#similar)                                       |
| `Technology::list(string $domain)`                                                                                                                           | [`GET /technology`](/api/domain#technology)                                 |
| `Reveal::companiesSearch(array $params)`                                                                                                                     | [`POST /reveal/search`](/api/reveal#search-companies)                       |
| `Flag::listFlags(?int $page = null, ?int $limit = null)`                                                                                                     | [`GET /flag`](/api/flag#list-my-flags)                                      |
| `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::listLeads(?int $page = null, ?int $limit = null, ?string $domain = null)`                                                                            | [`GET /leads`](/api/leads#retrieve-leads)                                   |
| `Leads::getLead(string $id)`                                                                                                                                 | [`GET /leads/{id}`](/api/leads#retrieve-a-single-lead)                      |
| `Leads::createLead(array $data)`                                                                                                                             | [`POST /leads`](/api/leads#create-a-lead)                                   |
| `Leads::updateLead(string $id, array $data)`                                                                                                                 | [`PUT /leads/{id}`](/api/leads#update-a-lead)                               |
| `Leads::deleteLead(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)             |
| `LeadsAttributes::getLeadAttributes()`                                                                                                                       | [`GET /attributes`](/api/lead-attributes#retrieve-lead-attributes)          |
| `LeadsAttributes::deleteLeadAttribute(string $id)`                                                                                                           | [`DELETE /attributes/{id}`](/api/lead-attributes#delete-a-lead-attribute)   |
| `Bulk::listBulks(string $type, ?array $params = null)`                                                                                                       | [`GET /bulk/{type}`](/api/bulks)                                            |
| `Bulk::createBulk(string $type, array $data)`                                                                                                                | [`POST /bulk/{type}`](/api/bulks)                                           |
| `Bulk::getBulk(string $type, int $id)`                                                                                                                       | [`GET /bulk/{type}/{id}`](/api/bulks)                                       |
| `Bulk::launchBulk(string $type, int $id)`                                                                                                                    | [`PUT /bulk/{type}/{id}`](/api/bulks)                                       |
| `Bulk::bulkProgress(string $type, int $id)`                                                                                                                  | [`GET /bulk/{type}/{id}/progress`](/api/bulks)                              |
| `Bulk::downloadBulk(string $type, int $id)`                                                                                                                  | [`GET /bulk/{type}/{id}/download`](/api/bulks)                              |
| `Bulk::renameBulk(string $type, int $id, string $name)`                                                                                                      | [`PUT /bulk/{type}/{id}/rename`](/api/bulks)                                |
| `Bulk::archiveBulk(string $type, int $id)`                                                                                                                   | [`DELETE /bulk/{type}/{id}/archive`](/api/bulks)                            |
| `Bulk::deleteBulk(string $type, int $id)`                                                                                                                    | [`DELETE /bulk/{type}/{id}/delete`](/api/bulks)                             |

`$type` 是[批量类型](/bulks#bulk-types)中列出的 `{type}` 路径段；调用顺序请参阅[生命周期](/bulks#lifecycle)。`createBulk()` 发送 JSON 请求体，因此无法创建需要上传 CSV 的任务，例如[邮箱查找器](/bulks#email-finder)任务。`downloadBulk()` 以字符串形式在 `$result['data']` 中返回结果文件（一个 CSV）。

## 源代码

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