# SDK PHP

`tomba-io/php` est le client PHP officiel de l'[API Tomba](/introduction). Chaque domaine de l'API est une classe de service, et chaque méthode envoie une requête.

## Prérequis

- PHP 8.1 ou version ultérieure, comme déclaré dans `composer.json`.
- Les extensions `curl` et `json`.

## Installer

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

Les classes sont chargées automatiquement depuis l'espace de noms `Tomba` ; les services se trouvent dans `Tomba\Services`.

## S'authentifier

Créez une clé API et copiez votre secret sur la page [API keys](https://app.tomba.io/api), puis exportez les deux :

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

Le SDK ne lit pas les variables d'environnement. Passez les valeurs à `setKey()` et `setSecret()`, et le client les envoie dans les en-têtes `X-Tomba-Key` et `X-Tomba-Secret`. L'expiration et la rotation des clés sont traitées dans [Authentification](/authentication).

## Première requête

Trouvez l'adresse email d'une personne dans une entreprise :

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

Chaque méthode renvoie un tableau avec deux clés : `data`, le corps JSON décodé, et `rate_limit`. L'API enveloppe son payload dans son propre objet `data` ([Format de réponse](/introduction#response-format)) : l'adresse se trouve donc dans `$result['data']['data']['email']`.

## Erreurs

Le SDK lève une `Tomba\TombaException` quand l'API répond avec un statut 400 ou supérieur, quand cURL échoue, et avant d'envoyer une requête quand un argument obligatoire est vide.

| Méthode          | Valeur                                                                                          |
| --------------- | ---------------------------------------------------------------------------------------------- |
| `getCode()`     | Le statut HTTP. `0` quand l'erreur s'est produite avant la réception d'une réponse.                   |
| `getMessage()`  | Le `errors.message` de l'API, ou l'erreur cURL.                                                 |
| `getResponse()` | Le corps de l'erreur décodé, `['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()` et `combined()` ne lèvent pas d'exception quand rien n'est trouvé : ces endpoints répondent avec le statut 200 et un corps `errors`, vérifiez donc `$result['data']['errors']`. Chaque `errors.type` est décrit dans [Erreurs](/error-handling#error-types).

## Limites de débit et nouvelles tentatives

Le SDK ne fait aucune nouvelle tentative. `$result['rate_limit']` contient les [en-têtes de limite de débit](/rate-limits#rate-limit-headers) de la réponse, indexés par nom d'en-tête : `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` et `ratelimit`. Les nombres sont des entiers, et un en-tête absent vaut `null`.

Un `429` lève une `TombaException` avec le code 429, sans les en-têtes de la réponse. Attendez avant de réessayer, comme décrit dans [Gérer les réponses 429](/rate-limits#handle-429-responses).

Les requêtes expirent après 120 secondes ; le délai d'expiration n'est pas configurable.

## Référence des méthodes

Créez chaque service avec le client, par exemple `new Finder($client)`.

| Méthode                                                                                                                                                       | 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` est le segment `{type}` listé dans [Types de tâches en masse](/bulks#bulk-types) ; l'ordre des appels est décrit dans [Cycle de vie](/bulks#lifecycle). `createBulk()` envoie un corps JSON et ne peut donc pas créer les tâches qui nécessitent l'import d'un fichier CSV, comme les tâches [Email Finder](/bulks#email-finder). `downloadBulk()` renvoie le fichier de résultats, un CSV, sous forme de chaîne dans `$result['data']`.

## Code source

[github.com/tomba-io/php](https://github.com/tomba-io/php) (Apache-2.0). Les notes de version se trouvent dans [CHANGELOG.md](https://github.com/tomba-io/php/blob/master/CHANGELOG.md).
