# PHP SDK

`tomba-io/php`는 [Tomba API](/introduction)의 공식 PHP 클라이언트입니다. 각 API 영역은 서비스 클래스이며, 각 메서드는 요청 하나를 보냅니다.

## 요구 사항

- `composer.json`에 선언된 대로 PHP 8.1 이상.
- `curl` 및 `json` 확장.

## 설치

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

클래스는 `Tomba` 네임스페이스에서 자동 로드되며, 서비스는 `Tomba\Services`에 있습니다.

## 인증

[API keys](https://app.tomba.io/api) 페이지에서 API 키를 만들고 시크릿 키를 복사한 다음, 두 값을 환경 변수로 내보냅니다.

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

모든 메서드는 디코딩된 JSON 본문인 `data`와 `rate_limit`, 두 키를 가진 배열을 반환합니다. API는 페이로드를 자체 `data` 객체로 감싸므로([응답 형식](/introduction#response-format)) 주소는 `$result['data']['data']['email']`에 있습니다.

## 오류

SDK는 API가 400 이상의 상태로 응답할 때, cURL이 실패할 때, 그리고 필수 인수가 비어 있는 경우 요청을 보내기 전에 `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 본문을 보내므로 [Email Finder](/bulks#email-finder) 작업처럼 CSV 업로드가 필요한 작업은 만들 수 없습니다. `downloadBulk()`는 결과 파일(CSV)을 `$result['data']`에 문자열로 반환합니다.

## 소스

[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)에 있습니다.
