Skip to main content

Telnyx PHP API library

[!NOTE] The Telnyx PHP API Library is currently in beta and we're excited for you to experiment with it!

This library has not yet been exhaustively tested in production environments and may be missing some features you'd expect in a stable release. As we continue development, there may be breaking changes that require updates to your code.

We'd love your feedback! Please share any suggestions, bug reports, feature requests, or general thoughts by filing an issue.

The Telnyx PHP library provides convenient access to the Telnyx REST API from any PHP 8.1.0+ application.

It is generated with Stainless.

Documentation

Installation

To use this package, install via Composer by adding the following to your application's composer.json:

{
"repositories": [
{
"type": "vcs",
"url": "git@github.com:team-telnyx/telnyx-php.git"
}
],
"require": {
"telnyx/telnyx-php": "dev-main"
}
}

Usage

This library uses named parameters to specify optional arguments. Parameters with a default value must be set by name.

<?php

use Telnyx\Client;

$client = new Client(apiKey: getenv("TELNYX_API_KEY") ?: "My API Key");

$response = $client->calls->dial(
connectionID: "conn12345", from: "+15557654321", to: "+15551234567"
);

var_dump($response->data);

Value Objects

It is recommended to use the static with constructor HangupTool::with(hangup: [], ...) and named parameters to initialize value objects.

However, builders are also provided (new HangupTool)->withHangup([]).

Handling errors

When the library is unable to connect to the API, or if the API returns a non-success status code (i.e., 4xx or 5xx response), a subclass of Telnyx\Core\Exceptions\APIException will be thrown:

<?php

use Telnyx\Core\Exceptions\APIConnectionException;

try {
$numberOrder = $client->numberOrders->create();
} catch (APIConnectionException $e) {
echo "The server could not be reached", PHP_EOL;
var_dump($e->getPrevious());
} catch (RateLimitError $_) {
echo "A 429 status code was received; we should back off a bit.", PHP_EOL;
} catch (APIStatusError $e) {
echo "Another non-200-range status code was received", PHP_EOL;
echo $e->getMessage();
}

Error codes are as follows:

CauseError Type
HTTP 400BadRequestException
HTTP 401AuthenticationException
HTTP 403PermissionDeniedException
HTTP 404NotFoundException
HTTP 409ConflictException
HTTP 422UnprocessableEntityException
HTTP 429RateLimitException
HTTP >= 500InternalServerException
Other HTTP errorAPIStatusException
TimeoutAPITimeoutException
Network errorAPIConnectionException

Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff.

Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts will all be retried by default.

You can use the maxRetries option to configure or disable this:

<?php

use Telnyx\Client;
use Telnyx\RequestOptions;

// Configure the default for all requests:
$client = new Client(maxRetries: 0);

// Or, configure per-request:
$result = $client->numberOrders->create(
requestOptions: RequestOptions::with(maxRetries: 5)
);

Advanced concepts

Making custom or undocumented requests

Undocumented properties

You can send undocumented parameters to any endpoint, and read undocumented response properties, like so:

Note: the extra* parameters of the same name overrides the documented parameters.

<?php

use Telnyx\RequestOptions;

$numberOrder = $client->numberOrders->create(
requestOptions: RequestOptions::with(
extraQueryParams: ["my_query_parameter" => "value"],
extraBodyParams: ["my_body_parameter" => "value"],
extraHeaders: ["my-header" => "value"],
),
);

var_dump($numberOrder["my_undocumented_property"]);

Undocumented request params

If you want to explicitly send an extra param, you can do so with the extra_query, extra_body, and extra_headers under the request_options: parameter when making a request, as seen in the examples above.

Undocumented endpoints

To make requests to undocumented endpoints while retaining the benefit of auth, retries, and so on, you can make requests using client.request, like so:

<?php

$response = $client->request(
method: "post",
path: '/undocumented/endpoint',
query: ['dog' => 'woof'],
headers: ['useful-header' => 'interesting-value'],
body: ['hello' => 'world']
);

Versioning

This package follows SemVer conventions. As the library is in initial development and has a major version of 0, APIs may change at any time.

This package considers improvements to the (non-runtime) PHPDoc type definitions to be non-breaking changes.

Requirements

PHP 8.1.0 or higher.

Contributing

See the contributing documentation.

<?php
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Credentials\CredentialProvider;
use Aws\Exception\AwsException;

$telnyxAPIKey = getenv('TELNYX_API_KEY');
if (!$telnyxAPIKey) {
die('TELNYX_API_KEY environment variable not set');
}

$region = 'us-central-1';
$endpoint = "https://{$region}.telnyxcloudstorage.com";

// 1. Initializing the AWS client with specific options
$s3Client = new S3Client([
'region' => $region,
'version' => 'latest',
'endpoint' => $endpoint,
'credentials' => [
'key' => $telnyxAPIKey,
'secret' => $telnyxAPIKey,
],
'use_path_style_endpoint' => true
]);

$bucketName = "test-bucket-" . $region . '-' . date('H-i') . '-' . rand(0, 1000000);
echo "Generated bucket name: " . $bucketName . PHP_EOL;

// 2. Create a bucket
try {
$s3Client->createBucket([
'Bucket' => $bucketName
]);
echo "Created bucket: {$bucketName}" . PHP_EOL;
} catch (AwsException $e) {
die("Unable to create bucket: " . $e->getMessage());
}

// 3. Upload two objects with random data
for ($i = 0; $i < 2; $i++) {
$content = random_bytes(1024 * 32); // 32KB of random data
$objName = "{$i}.txt";
try {
$s3Client->putObject([
'Bucket' => $bucketName,
'Key' => $objName,
'Body' => $content
]);
echo "Uploaded file ({$objName}) to bucket: {$bucketName}" . PHP_EOL;
} catch (AwsException $e) {
die("Unable to upload file ({$objName}): " . $e->getMessage());
}
}

// 4. List objects in the bucket
try {
$result = $s3Client->listObjects([
'Bucket' => $bucketName
]);
foreach ($result['Contents'] as $item) {
echo "Listed object: " . $item['Key'] . PHP_EOL;
}
} catch (AwsException $e) {
die("Unable to list objects: " . $e->getMessage());
}

// 5. Download the first object
try {
$result = $s3Client->getObject([
'Bucket' => $bucketName,
'Key' => '1.txt'
]);
$data = $result['Body']->getContents();
echo "Downloaded file size: " . strlen($data) . PHP_EOL;
} catch (AwsException $e) {
die("Unable to download object: " . $e->getMessage());
}

// 6. Create a presigned URL for the first file
$url = "https://api.telnyx.com/v2/storage/buckets/{$bucketName}/1.txt/presigned_url";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['TTL' => 30]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $telnyxAPIKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpcode != 200) {
die("Unexpected status code: {$httpcode} | response: {$response}");
}

$presignedData = json_decode($response, true);
$presignedURL = $presignedData['data']['presigned_url'];
echo "Generated presigned URL: {$presignedURL}" . PHP_EOL;

// 7. Download the file using the presigned URL
$ch = curl_init($presignedURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

echo "Downloaded presigned URL data size: " . strlen($result) . PHP_EOL;
?>