Search by

sendrail / sendrail-php

sendrail

Official PHP SDK for Sendrail, the Czech SMS API: send SMS and verification codes (OTP), check numbers, manage opt-outs and templates, verify webhooks

v0.1.0 2026-11-27 11:26 UTC

This package is auto-updated.

Last update: 2026-11-27 11:34:40 UTC


README

Official PHP library for Sendrail, the Czech SMS API: transactional SMS, verification codes (OTP), number check, opt-outs, templates and signed webhooks.

  • PHP 8.1 or newer
  • Works with any PSR-18 HTTP client (Guzzle, Symfony HttpClient, ...); no hard dependency on either
  • Typed exceptions carrying Sendrail's error code and the HTTP status
  • Never silently repeats a send that has no idempotency key

Česky: stručný návod níže.

Installation

composer require sendrail/sendrail-php

The library needs a PSR-18 client and PSR-17 factories and finds them automatically through php-http/discovery. If your project has none yet, add one:

composer require guzzlehttp/guzzle
# or
composer require symfony/http-client nyholm/psr7

When Composer asks whether to allow the php-http/discovery plugin, saying yes lets it install a missing implementation for you. Without any, creating the client fails with a discovery exception that names what to install.

Quick start

$sendrail = new Sendrail\Client(getenv('SENDRAIL_API_KEY'));

$message = $sendrail->messages->send(
    '+420777123456',
    'Your code is 482913',
    idempotencyKey: 'order-1042-code',
);

echo $message['id'], ' ', $message['status']; // msg_5f0c9a1e7b2d4c8a9e01 queued

queued means accepted, not delivered. Read the final status from the webhook or with $sendrail->messages->get($id).

Develop with a test key (sr_test_…): same answers, nothing is sent or charged, numbers ending in 0000 fail.

Answers are returned as arrays decoded from the API's JSON, with the field names used in the documentation.

Messages

// Price and segments without sending or charging; the answer has status dry_run and no id
$estimate = $sendrail->messages->estimate('+420777123456', 'Dobrý den, objednávka je připravena.');

// A stored template with {{name}} places
$sendrail->messages->sendTemplate('+420777123456', 'order-ready', ['name' => 'Jana', 'order' => '1042'], idempotencyKey: 'order-1042-ready');

// Status, cancel
$message = $sendrail->messages->get('msg_5f0c9a1e7b2d4c8a9e01');
$sendrail->messages->cancel('msg_5f0c9a1e7b2d4c8a9e01'); // ConflictException when it already left

// Any field of POST /v1/messages
$sendrail->messages->create(['to' => '+420777123456', 'message' => 'Hi', 'type' => 'bulk', 'dry_run' => true]);

Listing

GET /v1/messages returns the messages sent with the key, newest first, each with its text (message):

// One page: 1 to 100 messages, optionally filtered by status and recipient
$page = $sendrail->messages->list(limit: 50, status: 'failed', to: '+420777123456');
foreach ($page['items'] as $message) { /* … */ }
$older = $sendrail->messages->list(limit: 50, status: 'failed', before: $page['next_before']); // next_before is null on the last page

// Or let the SDK fetch page after page as you iterate
foreach ($sendrail->messages->iterate(status: 'sent', max: 1000) as $message) {
    echo $message['id'], ' ', $message['to'], ' ', $message['message'], "\n";
}

iterate() takes status:, to:, pageSize: (default 100), max: (stop after that many) and before:. It requests lazily, so API exceptions are thrown from inside the loop.

Idempotency and repeats

After a timeout you cannot know whether a message was accepted. Give every message an idempotencyKey (your own unique id, up to 120 characters): repeating the call with the same key returns the first message with 'duplicate' => true and sends nothing.

The client repeats a call on its own (twice by default, after 0.5 s and 1 s, or after Retry-After) only when repeating cannot do anything twice:

Repeated automatically Never repeated automatically
reads (get, list, iterate, account, prices, number check) a send without an idempotency key
a send with an idempotency key, a dry run a batch unless every message has its own key
template, opt-out and webhook changes sending and checking a verification code, cancel

It happens after a network error, 429 rate_limited and HTTP 502, 503, 504. Other errors (including 429 daily_limit_reached) are thrown at once. Switch it off with new Sendrail\Client($key, maxRetries: 0).

Bulk sending

Mass mailings must be marked as bulk. Up to 500 recipients per call:

$result = $sendrail->messages->sendBulk(['+420777123456', '+420777123457'], 'Sleva 20 % do neděle. STOP pro odhlášení.');
echo $result['accepted'], ' accepted, ', $result['rejected'], ' rejected';

// A text or template values per recipient, each with its own idempotency key
$sendrail->messages->batch([
    'template' => 'order-ready',
    'messages' => [
        ['to' => '+420777123456', 'variables' => ['name' => 'Jana'], 'idempotency_key' => 'campaign-7-1'],
        ['to' => '+420777123457', 'variables' => ['name' => 'Petr'], 'idempotency_key' => 'campaign-7-2'],
    ],
]);

// One bulk message
$sendrail->messages->send('+420777123456', 'Newsletter', bulk: true);

Verification codes (OTP)

$verification = $sendrail->verify->send('+420777123456', app: 'My shop'); // length:, ttl:, lang:, template:
// store $verification['id'] in the session, then:

if ($sendrail->verify->isValid($verification['id'], $codeTypedByUser)) {
    // verified; true exactly once
}

$state = $sendrail->verify->get($verification['id']); // pending, approved, failed, expired, cancelled (a newer code was sent)

Never show the code (or test_code of a test key) to the person being verified.

Number check, opt-outs, templates, account

$sendrail->numbers->check('777 123 456');               // valid, number, country, type, price_per_segment, opted_out, ...
$sendrail->numbers->checkMany(['777123456', '+421…']);  // up to 100

$sendrail->optOuts->list();
$sendrail->optOuts->add('+420777123456', 'bulk', note: 'asked by phone'); // scope: all | bulk
$sendrail->optOuts->remove('+420777123456');

$sendrail->templates->list();
$sendrail->templates->save('order-ready', 'Dobrý den {{name}}, objednávka {{order}} je připravena.');
$sendrail->templates->delete('order-ready');

$sendrail->account->get();   // credit, trial, plan, rules, limits and usage of the key
$sendrail->prices->get();    // price of a segment per country and plan
$sendrail->inbound->list();  // replies and missed calls (inbound must be switched on)

Webhooks

Sendrail posts message.final, message.received, call.missed and optout.created to the webhook address of the key and signs the body: X-Sendrail-Signature: sha256=<hex HMAC-SHA256 of the raw body>. Every body starts with the id of the event and the timestamp of the delivery attempt:

{"id":"evt_msg_5f0c9a1e7b2d4c8a9e01","timestamp":1795867200,"event":"message.final","message":{"id":"msg_…","status":"sent", …}}
$verifier = new Sendrail\Webhook\Verifier(getenv('SENDRAIL_WEBHOOK_SECRET'));

try {
    $event = $verifier->parse(
        file_get_contents('php://input'),               // the raw body, not re-encoded JSON
        $_SERVER['HTTP_X_SENDRAIL_SIGNATURE'] ?? null,
    );
} catch (Sendrail\Exception\SignatureVerificationException $e) {
    http_response_code(401);
    exit;
}

if ($alreadyHandled($event->id)) {   // your own storage of handled event ids
    http_response_code(204);
    exit;
}

if ($event->is(Sendrail\Webhook\Event::MESSAGE_FINAL)) {
    $event->data['id'];     // msg_…
    $event->data['status']; // sent, failed, cancelled, rejected
}
http_response_code(204);
$event->id evt_…, the same for every repeat of one event
$event->timestamp Unix time of this delivery attempt
$event->type message.final, message.received, call.missed, optout.created
$event->data the message of message.final, the data object of the other events
$event->payload the whole decoded body

Repeats. Answer with a 2xx within 5 seconds, otherwise the event is posted again (after 1, 5 and 15 minutes, 1 hour and 6 hours), so the same event can arrive more than once. Deduplicate by $event->id: store the ids you have handled (a unique column or a cache key kept for at least a day) and acknowledge a repeat without doing the work again.

Replays. parse() checks two things: the signature, compared in constant time (hash_equals), and the age of the request. The timestamp inside the signed body must be within 300 seconds of your server's clock, in either direction; otherwise it throws WebhookTimestampException (a SignatureVerificationException). Somebody who recorded a request therefore cannot send it again later. Keep the server clock synchronised. The timestamp is read from the signed body only; the X-Sendrail-Timestamp and X-Sendrail-Event-Id headers merely repeat it and are not trusted.

new Sendrail\Webhook\Verifier($secret);                              // default: 300 s, a timestamp is required
new Sendrail\Webhook\Verifier($secret, tolerance: 600);              // a wider window
new Sendrail\Webhook\Verifier($secret, tolerance: 0);                // no age check at all
new Sendrail\Webhook\Verifier($secret, allowMissingTimestamp: true); // also accept bodies without a timestamp

A correctly signed body that has no timestamp is refused by default. Sendrail sends one with every event, so a body without it is either very old or not from Sendrail, and accepting it would let a recorded old request through forever. allowMissingTimestamp: true accepts such bodies (a timestamp that is present is still checked); use it only if you must process requests recorded in the old format. tolerance: 0 switches the age check off completely.

$verifier->isValid($body, $header) returns a boolean for the same checks. Sendrail\Webhook\Signature::verify($body, $header, $secret) checks the signature alone.

The address can be managed through the API when the owner of the key allows it in the dashboard (otherwise 403 webhook_api_disabled). A key has one address:

$sendrail->webhook->get();                                  // ['url' => null|string, 'secret' => '…', 'events' => ['message.final', …]]
$sendrail->webhook->set('https://example.com/sendrail');    // 400 invalid_url unless public https
$sendrail->webhook->delete();

Errors

Everything the library throws implements Sendrail\Exception\SendrailException.

use Sendrail\Exception;

try {
    $sendrail->messages->send($to, $text, idempotencyKey: $key);
} catch (Exception\PermissionDeniedException $e) {
    if ($e->is('recipient_opted_out')) { /* do not retry */ }
} catch (Exception\RateLimitException $e) {
    $e->retryAfter; // seconds from Retry-After, or null
} catch (Exception\ApiException $e) {
    $e->httpStatus; // 402
    $e->errorCode;  // insufficient_credit (null when the answer carried no Sendrail code)
    $e->getMessage();
} catch (Exception\TransportException $e) {
    // no answer: repeat with the same idempotency key
}
Exception HTTP Codes
BadRequestException 400 missing_field, invalid_number, message_too_long, missing_variable, batch_too_large, invalid_cursor, invalid_url, …
AuthenticationException 401 invalid_api_key
PaymentRequiredException 402 insufficient_credit, trial_exhausted, plan_requires_credit
PermissionDeniedException 403 recipient_opted_out, country_not_allowed, recipient_not_allowed, trial_recipient, webhook_api_disabled, …
NotFoundException 404 not_found, template_not_found
ConflictException 409 already_final, already_sending
ValidationException 422 country_not_supported, or field errors in getErrors()
RateLimitException 429 rate_limited, bulk_queue_full, daily_limit_reached, verify_rate_limited
ServerException 5xx gateway_error
TransportException – network failure, timeout
InvalidArgumentException – wrong arguments, nothing was requested
SignatureVerificationException – webhook signature is missing or wrong
WebhookTimestampException – webhook is signed correctly but too old (or has no timestamp); extends SignatureVerificationException
InvalidWebhookPayloadException – signed webhook body is not an event; extends SignatureVerificationException

The exceptions with an HTTP status extend ApiException.

Your own HTTP client

$sendrail = new Sendrail\Client(
    $apiKey,
    httpClient: new GuzzleHttp\Client(['timeout' => 20]),
);

// Symfony HttpClient
$sendrail = new Sendrail\Client(
    $apiKey,
    httpClient: new Symfony\Component\HttpClient\Psr18Client(Symfony\Component\HttpClient\HttpClient::create(['timeout' => 20])),
);

PSR-18 has no setting for timeouts, so the library cannot set one: give the client a timeout of at least 20 seconds. requestFactory: and streamFactory: take PSR-17 factories, baseUrl: another API address.

An endpoint the SDK does not know yet can be called with $sendrail->request('GET', '/v1/…').

Framework packages

Česky

Oficiální PHP knihovna pro Sendrail, české SMS API.

composer require sendrail/sendrail-php
$sendrail = new Sendrail\Client(getenv('SENDRAIL_API_KEY'));

// Odeslání zprávy; idempotencyKey zaručí, že opakované volání nepošle SMS dvakrát
$zprava = $sendrail->messages->send('+420777123456', 'Váš kód je 482913', idempotencyKey: 'objednavka-1042');

// Ověřovací kód (OTP)
$overeni = $sendrail->verify->send('+420777123456', app: 'Můj obchod');
$plati = $sendrail->verify->isValid($overeni['id'], $kodOdUzivatele);

// Ověření podpisu a stáří webhooku; $udalost->id použijte k deduplikaci
$udalost = (new Sendrail\Webhook\Verifier($podpisovyKlic))
    ->parse(file_get_contents('php://input'), $_SERVER['HTTP_X_SENDRAIL_SIGNATURE'] ?? null);

// Výpis odeslaných zpráv po stránkách
foreach ($sendrail->messages->iterate(status: 'failed') as $zprava) { /* … */ }
  • Stav queued znamená přijato, ne doručeno; konečný stav přijde webhookem nebo ho vrátí messages->get($id).
  • Při vývoji použijte testovací klíč sr_test_…: nic se neodešle ani neúčtuje.
  • Chyby API jsou výjimky Sendrail\Exception\ApiException s vlastnostmi httpStatus a errorCode (např. insufficient_credit, recipient_opted_out).
  • Odeslání bez idempotencyKey knihovna nikdy sama neopakuje.
  • Hromadné rozesílky posílejte přes messages->sendBulk() nebo messages->batch().
  • Webhook: Verifier odmítne tělo starší než 300 s (ochrana proti přehrání; tolerance: 0 kontrolu vypne) a tělo bez timestamp. Stejná událost může přijít víckrát, opakování poznáte podle stejného $udalost->id.

Úplná dokumentace API: https://sendrail.cz/docs. Podpora: info@sendrail.cz.

Development

composer install
composer check   # composer validate, PHPStan, PHPUnit

The tests use a mocked HTTP client and never touch the network.

License

MIT, see LICENSE.