---
title: PHP SDK
description: Use BillionSend from PHP with the billionsend/billionsend-php package.
---

The `billionsend/billionsend-php` package is the BillionSend client for PHP. It covers every operation of the [API reference](/docs/api-reference): sending, domains, contacts, broadcasts, templates, webhooks, inboxes with their threads and drafts, live inbox events and agent sign-up. The source is [billionsend/billionsend-php](https://github.com/billionsend/billionsend-php) on GitHub.

## Install

Needs PHP 8.1 or newer with the `curl` and `json` extensions, and nothing else.

```sh
composer require billionsend/billionsend-php:^0.1
```

## Send an email

```php
use BillionSend\Client;

$client = new Client(); // reads BILLIONSEND_API_KEY

$sent = $client->emails->send([
    'from' => 'Acme <hello@acme.dev>',
    'to' => ['ana@example.com'],
    'subject' => 'Welcome to Acme',
    'html' => '<p>Glad you are here.</p>',
], ['idempotency_key' => 'welcome/ana']);

echo $sent['id'];
```

`new Client('bs_...')` takes the key directly. The second argument sets the rest: `'base_url'`, `'timeout'` (seconds per attempt, default 60), `'max_retries'`, `'headers'` and `'transport'` (any `BillionSend\Transport`, to send through your own HTTP stack). `BILLIONSEND_BASE_URL` overrides the API URL.

## Method names

Each operation is a method named after its id in the [API reference](/docs/api-reference), the dotted path as a chain of services: `emails.send` is `$client->emails->send()`, `emails.receiving.attachments.list` is `$client->emails->receiving->attachments->list()`. `emails.metrics` is `$client->emails->metrics->get()`, beside `->links()`, `->countries()` and `->clients()`.

A method takes the path parameters in order, the request body, the query and header parameters, then the call's options. Bodies and answers are associative arrays with the API's own field names, so the API reference describes them field for field.

## Idempotency and retries

The eight sending operations (`emails->send`, `emails->batch`, received-mail replies and forwards, `inboxes->send`, `inboxes->drafts->send`, thread replies and forwards) always send an `Idempotency-Key`. Without `'idempotency_key'`, each call makes one up that its retries reuse, so a retry after a timeout never sends twice; your own key also makes a repeat from another process safe.

Failures worth retrying are retried twice by default: 429, 5xx, timeouts, network errors, and the `409 concurrent_idempotent_requests` answered while the first attempt with the same key is still running. Only requests safe to repeat are retried: `GET`, `PUT`, `DELETE` and the sending operations. The client waits as `Retry-After` asks, up to a minute, and otherwise backs off exponentially from 0.5 s to 8 s. The last argument of every method takes `'idempotency_key'`, `'headers'`, `'timeout'`, `'max_retries'` and `'response_headers' => &$headers` for that call.

## Errors

A failed call throws `ValidationError` (400, 422), `AuthenticationError` (401, or no key configured), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `getRetryAfter()` in seconds), `APIError` (5xx), `APIConnectionError` (no answer) or `APITimeoutError` (the attempt timed out). All are in `BillionSend\Exception` and extend `BillionSendError`, with `getStatusCode()`, `getErrorName()` (the API's error name), `getMessage()` and `getRequestId()`, the answer's `x-request-id`, which is the request's id on the dashboard's Logs page.

```php
use BillionSend\Exception\BillionSendError;
use BillionSend\Exception\NotFoundError;

try {
    $email = $client->emails->get($id);
} catch (NotFoundError) {
    // no such email
} catch (BillionSendError $e) {
    error_log(sprintf('%s %s: %s (request %s)', $e->getStatusCode(), $e->getErrorName(), $e->getMessage(), $e->getRequestId()));
}
```

## Lists

List methods return one page. Every cursor list also has an `...All()` generator that fetches the next pages as it goes, backward when `'before'` is set:

```php
foreach ($client->contacts->listAll(['limit' => 100]) as $contact) {
    echo $contact['email'], "\n";
}
```

## An agent's inbox

Wait for new mail on the [event stream](/docs/inboxes) and reply in its thread:

```php
use BillionSend\StreamGapEvent;

$stream = $client->inboxes->events->streamInbox('support@acme.dev', ['types' => 'inbox.email.received']);

foreach ($stream as $event) {
    if ($event instanceof StreamGapEvent) {
        continue; // events may be missing: read the threads again
    }
    $data = $event->payload();
    $client->inboxes->threads->emails->reply(
        $event->inboxId(),
        $data['thread_id'],
        $data['email_id'],
        ['text' => 'Thanks, we are on it.'],
        ['idempotency_key' => "reply/{$data['email_id']}"],
    );
}
```

The stream reconnects with `Last-Event-ID` when the connection drops and replays what it missed; keep `$stream->lastEventId()` and pass it back as the `'last_event_id'` option to resume after a restart. A `StreamGapEvent` comes once when the stream resumes from more than 24 hours back. The options `'max_reconnects'` (default 5), `'reconnect_delay'` and `'reconnect' => false` tune reconnecting. One inbox's stream ends after that inbox is deleted or expires; `$client->inboxes->events->stream()` follows every inbox the key can read.

## Verify webhooks

`Webhook::verify` checks a [webhook](/docs/concepts/webhooks) delivery's signature and timestamp with the endpoint's `whsec_` secret and returns the parsed event. Pass the body exactly as it arrived:

```php
use BillionSend\Exception\WebhookVerificationError;
use BillionSend\Webhook;

try {
    $event = Webhook::verify(file_get_contents('php://input'), getallheaders(), getenv('BILLIONSEND_WEBHOOK_SECRET'));
} catch (WebhookVerificationError) {
    http_response_code(400);
    exit;
}
if ($event['type'] === 'email.bounced') {
    // ...
}
```

A delivery older than five minutes is refused, and during a secret rotation either secret verifies.
