phpguzzle.org
enrudees
Twilio – Docs

Twilio PHP SDK Setup: REST Client and First Request

How do you install the Twilio PHP SDK? Require the twilio/sdk package with Composer, load the autoloader and create a client with new Twilio\Rest\Client($sid, $token), taking the credentials from environment variables. Every API request after that goes through this client.

The same few things trip people up: Class "Twilio\Rest\Client" not found, empty credentials in Laravel after config:cache, test credentials in production, and Composer running out of memory on a cheap VPS.

Installing with Composer

composer require twilio/sdk

The SDK pulls in no other packages: the require section of its composer.json lists PHP and nothing else. It talks to the API through the cURL extension, so ext-curl has to be enabled, and Composer will not check that for you. Guzzle only matters if you want to plug in your own HTTP client.

Load the autoloader once, where the application boots:

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

The current branch is 8.x. Composer will install it on PHP 7.1 too, but the library itself is tested on 8.2, 8.3 and 8.4, so treat 8.2 as the floor. composer show twilio/sdk prints the version installed in your project.

Twilio’s docs call the package the PHP helper library, Composer knows it as twilio/sdk, and the repository on GitHub is twilio/twilio-php. All three are the same library. Classes and methods are listed in the official reference.

If an example you found uses the Services_Twilio class, it was written for versions before 5.0, the last of which came out in 2017. The package is the same but the API is not: everything now lives in the Twilio\Rest namespace, and old code has to be rewritten for it.

Without Composer

On shared hosting without SSH you can wire the library in by hand. Download the repository archive, unpack it next to your code and require the autoloader that ships with it:

// The archive of the main branch unpacks to twilio-php-main, a release archive has the version number in the folder name
require __DIR__ . '/twilio-php-main/src/Twilio/autoload.php';

$client = new Twilio\Rest\Client($sid, $token);

The other way is to build vendor/ on your own machine and upload the whole directory. If autoloading dies with a fatal error after a manual install, first check that every file made it to the server.

For a single request once a day you can skip the SDK entirely. Twilio is a plain HTTP API with Basic auth:

$ch = curl_init("https://api.twilio.com/2010-04-01/Accounts/{$sid}/Messages.json");
curl_setopt_array($ch, [
    CURLOPT_USERPWD        => $sid . ':' . $token,
    CURLOPT_POSTFIELDS     => http_build_query(['To' => $to, 'From' => $from, 'Body' => $text]),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 10,
]);

$raw = curl_exec($ch);
if (false === $raw) {
    throw new RuntimeException(curl_error($ch));
}

// A successful send answers 201, an error carries code and message in the body
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$response = json_decode($raw, true);

Beyond two or three calls like this it stops paying off: pagination, error parsing and webhook signature validation become your job.

REST client and credentials

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

use Twilio\Rest\Client;

function requireEnv(string $name): string
{
    $value = getenv($name);
    if (false === $value || '' === $value) {
        throw new RuntimeException("Environment variable {$name} is not set");
    }

    return $value;
}

$sid = requireEnv('TWILIO_ACCOUNT_SID');
$client = new Client($sid, requireEnv('TWILIO_AUTH_TOKEN'));

The Account SID starts with AC; both it and the Auth Token come from the Twilio console. The Auth Token gives full access to the account and its balance, so keep it in environment variables and out of git.

The check in requireEnv() is there for two reasons. Without credentials the constructor succeeds silently and only the first request fails, with the message username is required. The second case is worse: when an argument is empty, the client reads TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN from the environment on its own. That is what makes a bare new Client() work in scripts, but in an application with several accounts an empty string from config or the database quietly turns into the environment credentials, and the request goes out under the wrong account. So reject empty values before they reach the constructor, wherever they come from.

Laravel and Symfony

In Laravel the credentials go into config and the client is registered in the container:

// config/services.php
'twilio' => [
    'sid'   => env('TWILIO_ACCOUNT_SID'),
    'token' => env('TWILIO_AUTH_TOKEN'),
],

// AppServiceProvider::register()
$this->app->singleton(Client::class, fn () => new Client(
    config('services.twilio.sid'),
    config('services.twilio.token'),
));

Do not call env() or getenv() straight from a service. After php artisan config:cache Laravel stops loading .env, and for a variable defined only in that file env() returns null and getenv() returns false. Locally, with no cache, everything works; on the server the client is left without credentials.

In Symfony the Dotenv component does not call putenv() by default, so getenv() will not see values from .env. Pass the credentials through the container, and the client arrives in services and controllers through the constructor:

# config/services.yaml
services:
    Twilio\Rest\Client:
        arguments:
            - '%env(TWILIO_ACCOUNT_SID)%'
            - '%env(TWILIO_AUTH_TOKEN)%'

API Key instead of the Auth Token

In production a separate API Key (SK...) is more convenient than the main Auth Token: if it leaks you revoke one key and the main token keeps working.

// The Account SID is required as the third argument: the key alone does not identify the account
$client = new Client(requireEnv('TWILIO_API_KEY'), requireEnv('TWILIO_API_SECRET'), $sid);

There are three key types. Standard opens everything except account resources and the keys themselves. Main has the same rights as the Auth Token. Restricted grants access only to the resources you pick. Standard is enough for sending messages and making calls.

First request

The easiest way to check credentials is a request that changes nothing and costs nothing. With the Auth Token, read your own account:

$account = $client->api->v2010->accounts($sid)->fetch();

echo $account->friendlyName, ' ', $account->status; // a working account has the status active

With a Standard key this call is rejected, because account resources are closed to it. Ask for the latest message instead. An empty array is a success too: authentication passed, there just are no messages yet.

$messages = $client->messages->read([], 1);

What the SDK returns

The response comes back as an object with the fields as properties, so there is no JSON to parse. When you need an array for a log or your own API, every resource has toArray():

$data = $account->toArray();

// The account array includes authToken, which must not reach logs or API responses
unset($data['authToken']);

// Dates come back as DateTime objects, for JSON a string is easier
$data['dateCreated'] = $account->dateCreated->format(DATE_ATOM);
$data['dateUpdated'] = $account->dateUpdated->format(DATE_ATOM);

echo json_encode($data, JSON_UNESCAPED_UNICODE);

The array keys are in camelCase, like the object properties. In the raw API response the same fields are in snake_case.

When the request fails

A wrong SID or token raises Twilio\Exceptions\RestException:

use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;

try {
    $account = $client->api->v2010->accounts($sid)->fetch();
} catch (RestException $e) {
    // getCode() returns the Twilio error code (20003 for failed authentication), the HTTP status is already at the start of the message
    error_log(sprintf('Twilio %d: %s', $e->getCode(), $e->getMessage()));
    throw $e;
} catch (TwilioException $e) {
    // No response: network, timeout, SSL
    error_log('Twilio unreachable: ' . $e->getMessage());
    throw $e;
}

When there is no response from the API at all, RestException does not help. Which exception you get then depends on the HTTP client: the default CurlClient throws EnvironmentException, the Guzzle wrapper from the timeouts section throws HttpException. Their common parent is TwilioException, so catch that in the second catch. The usual example, SSL certificate problem, has nothing to do with Twilio: PHP does not trust the certificate chain. The fix is a fresh cacert.pem and its path in curl.cainfo in php.ini. Never turn certificate verification off. The numeric codes are listed in Twilio’s error and warning dictionary.

Timeouts and a custom HTTP client

By default a request to the API can hang for 60 seconds. That is a lot for a web process or a worker, so in production the timeout gets cut. Your own CurlClient goes in as the fifth constructor argument, and its options override the library’s values:

use Twilio\Http\CurlClient;
use Twilio\Rest\Client;

$http = new CurlClient([
    CURLOPT_TIMEOUT        => 10, // whole request, seconds
    CURLOPT_CONNECTTIMEOUT => 5,  // connection setup only
]);

// The third and fourth arguments (Account SID and region) are not needed here
$client = new Client($sid, $token, null, null, $http);

If the project already has Guzzle set up with logging or a proxy, the same argument accepts a wrapper around it. There is a catch: the wrapper puts its own timeout value into every request, empty by default, and the timeout from the Guzzle config stops applying. The request is left with no time limit. Set the overall timeout through a curl option in that case; connect_timeout works as usual:

use GuzzleHttp\Client as Guzzle;
use Twilio\Http\GuzzleClient;
use Twilio\Rest\Client;

$guzzle = new Guzzle([
    'connect_timeout' => 5,
    'curl'            => [CURLOPT_TIMEOUT => 10],
]);

$client = new Client($sid, $token, null, null, new GuzzleClient($guzzle));

In this setup network errors and timeouts arrive as Twilio\Exceptions\HttpException, with the original Guzzle exception in getPrevious(). Pulling in Guzzle just for a timeout is not worth it.

Region

If account data has to be processed outside the US, the client needs a pair of values: the region is the fourth constructor argument, the edge is set with a separate method.

$client = new Client($sid, $token, null, 'au1');
$client->setEdge('sydney');

Requests then go to api.sydney.au1.twilio.com instead of api.twilio.com. Both values are required: without an edge Twilio processes the request in US1. Each region has its own credentials, so an Auth Token or API Key from US1 will not work in au1.

The client also picks the same values up from the TWILIO_REGION and TWILIO_EDGE variables. If requests suddenly go to the wrong host, check whether one of them is set on the server.

Subaccounts

When an application serves several independent customers, each one gets a Twilio subaccount with its own Account SID and Auth Token. The balance stays shared: subaccount usage is billed to the main account, and spending is tracked per subaccount. A subaccount is created with the main account’s credentials:

$main = new Client($mainSid, $mainToken);

$sub = $main->api->v2010->accounts->create(['friendlyName' => 'Tenant Acme']);

// There are many subaccount credentials, so .env is the wrong place: store them in the database, the token in an encrypted column
$tenant->update(['twilio_sid' => $sub->sid, 'twilio_token' => $sub->authToken]);

There are two ways to act on behalf of a subaccount. new Client($mainSid, $mainToken, $subSid) puts the subaccount SID into the request path, and only the classic API has such paths: messages, calls, phone numbers. Messaging Services, Studio and TaskRouter live on separate subdomains with no SID in the path, and the resource is silently created in the main account.

So build the customer’s client on the subaccount’s own credentials. Reject empty fields here as well, otherwise the environment fallback kicks in:

if ('' === (string) $tenant->twilio_sid || '' === (string) $tenant->twilio_token) {
    throw new RuntimeException("Tenant {$tenant->id} has no Twilio credentials");
}

$client = new Client($tenant->twilio_sid, $tenant->twilio_token);

An API Key of the main account gets no access to subaccount resources at all. If you would rather not store the subaccount’s Auth Token, create an API Key inside the subaccount.

Test credentials

Older accounts have a second set of credentials, the test one. Requests made with it cost nothing and send nothing, which suits automated tests. The new Twilio console no longer lets you create such a set, but the ones issued earlier keep working.

$test = new Client(requireEnv('TWILIO_TEST_ACCOUNT_SID'), requireEnv('TWILIO_TEST_AUTH_TOKEN'));

$message = $test->messages->create($to, [
    // Magic number: the only sender the request succeeds with
    'from' => '+15005550006',
    'body' => 'Delivery check',
]);

A regular number in from, even one you bought, returns error 21606. The recipient can be any valid number. Test credentials work with only four operations: sending a message, making a call, buying a number and Lookup. Everything else, including the account fetch from the section above, answers 403 Forbidden.

Common pitfalls

Class "Twilio\Rest\Client" not found. On PHP 7 the same message uses single quotes. The question has about 18,000 views on Stack Overflow. There are usually two causes. First: the autoloader is not required in the entry point that actually runs. For public/index.php the path is __DIR__ . '/../vendor/autoload.php', while './vendor/autoload.php' and '../vendor/autoload.php' are resolved from the current directory of the process and break when the script runs from cron. Second: composer require was run outside the project folder and the package landed in some other vendor/. Check that a twilio/sdk directory sits next to the autoload.php you require.

Auth Token in the repository. Deleting the file in the next commit is not enough, the token stays in git history. Rotate it in the console and put the new one in a .env file that is listed in .gitignore.

Test credentials in production. With a live number in from every send fails with 21606 even though the number is paid for. If the number +15005550006 made it into the config as well, requests go through, a message object comes back, and nothing reaches anyone. The reverse mistake costs more: automated tests on live credentials send real SMS for real money. Keep the two sets in different environments and under different variable names.

Composer runs out of memory. These are two different failures. Allowed memory size exhausted goes away once the limit is lifted:

COMPOSER_MEMORY_LIMIT=-1 composer require twilio/sdk

proc_open(): fork failed - Cannot allocate memory means the VPS ran out of physical memory and has no swap. The variable does not help here, a swap file does.

Next steps

The client is ready. What comes next depends on the task: sending SMS, one-time codes with Verify or validating incoming webhooks.

Spotted something inaccurate on this page?

Report an error