# SDK para PHP

`tomba-io/php` é o cliente oficial em PHP para a [API da Tomba](/introduction). Cada área da API é uma classe de serviço, e cada método envia uma requisição.

## Requisitos

- PHP 8.1 ou posterior, conforme declarado em `composer.json`.
- As extensões `curl` e `json`.

## Instalação

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

As classes são carregadas automaticamente a partir do namespace `Tomba`; os serviços estão em `Tomba\Services`.

## Autenticação

Crie uma chave de API e copie seu secret na página [API keys](https://app.tomba.io/api) e depois exporte os dois:

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

O SDK não lê variáveis de ambiente. Passe os valores para `setKey()` e `setSecret()`, e o cliente os envia nos cabeçalhos `X-Tomba-Key` e `X-Tomba-Secret`. A expiração e a rotação das chaves são explicadas em [Autenticação](/authentication).

## Primeira requisição

Encontre o endereço de email de uma pessoa em uma empresa:

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

Todos os métodos retornam um array com duas chaves: `data`, o corpo JSON decodificado, e `rate_limit`. A API encapsula o payload no seu próprio objeto `data` ([Formato da resposta](/introduction#response-format)), então o endereço fica em `$result['data']['data']['email']`.

## Erros

O SDK lança `Tomba\TombaException` quando a API responde com status 400 ou superior, quando o cURL falha e, antes de enviar uma requisição, quando um argumento obrigatório está vazio.

| Método          | Valor                                                                                          |
| --------------- | ---------------------------------------------------------------------------------------------- |
| `getCode()`     | O status HTTP. `0` quando o erro aconteceu antes de uma resposta ser recebida.                   |
| `getMessage()`  | O `errors.message` da API, ou o erro do cURL.                                                 |
| `getResponse()` | O corpo do erro decodificado, `['errors' => ['type' => …, 'message' => …, 'code' => …]]`, ou `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()` e `combined()` não lançam exceções quando nada é encontrado: esses endpoints respondem com o status 200 e um corpo `errors`, então verifique `$result['data']['errors']`. Cada `errors.type` é descrito em [Erros](/error-handling#error-types).

## Limites de requisições e novas tentativas

O SDK não faz novas tentativas. `$result['rate_limit']` contém os [cabeçalhos de limite de requisições](/rate-limits#rate-limit-headers) da resposta, com o nome do cabeçalho como chave: `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` e `ratelimit`. Os números são inteiros, e um cabeçalho ausente é `null`.

Um `429` lança `TombaException` com o código 429, sem os cabeçalhos da resposta. Aguarde antes de tentar novamente, conforme descrito em [Tratar respostas 429](/rate-limits#handle-429-responses).

As requisições expiram após 120 segundos; o tempo limite não é configurável.

## Referência de métodos

Crie cada serviço com o cliente, por exemplo `new Finder($client)`.

| Método                                                                                                                                                       | Endpoint                                                                    |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| `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` é o segmento `{type}` listado em [Tipos de jobs em massa](/bulks#bulk-types); a ordem das chamadas é descrita em [Ciclo de vida](/bulks#lifecycle). `createBulk()` envia um corpo JSON, então não pode criar jobs que exigem o envio de um CSV, como os jobs de [Email Finder](/bulks#email-finder). `downloadBulk()` retorna o arquivo de resultados, um CSV, como string em `$result['data']`.

## Código-fonte

[github.com/tomba-io/php](https://github.com/tomba-io/php) (Apache-2.0). As notas de versão estão em [CHANGELOG.md](https://github.com/tomba-io/php/blob/master/CHANGELOG.md).
