To send an SMS from Symfony, configure a scoped HttpClient with the X-API-Key header, wrap the send in a Messenger message handled asynchronously, and set an Idempotency-Key on the request. Messenger's retry strategy then repeats a failed send safely, because every attempt carries the same key.

Symfony gives you the pieces already: HttpClient for the call, Messenger for the queue, the retry strategy for backoff and a failure transport for messages that give up. The work is wiring them so a retry cannot text someone twice. We make Ready, so the request is Ready's, and the structure works for any JSON texting API.

Configure a scoped client

A scoped client keeps the base URL, headers and timeouts in one place. Put the key in a secret, not in .env committed to git.

php bin/console secrets:set READY_API_KEY
# config/packages/framework.yaml
framework:
  http_client:
    scoped_clients:
      ready.client:
        base_uri: 'https://api.tryready.com'
        headers:
          X-API-Key: '%env(READY_API_KEY)%'
          Accept: 'application/json'
        timeout: 5
        max_duration: 15

timeout is the idle time between bytes and max_duration caps the whole request. Set both, since a client without them can hold a worker for as long as the other side stays silent. Symfony autowires the scoped client by name, so a service can ask for HttpClientInterface $readyClient.

The message

A Messenger message is a plain object. Everything the handler needs travels with it, including the idempotency key, created when the message is dispatched.

<?php
// src/Message/SendSms.php
namespace App\Message;

final class SendSms
{
    public function __construct(
        public readonly string $to,
        public readonly string $body,
        public readonly string $idempotencyKey,
    ) {
    }
}

When you dispatch, build the key from your own data:

$bus->dispatch(new SendSms(
    to: $order->getPhone(),
    body: sprintf('Your order #%d has shipped.', $order->getId()),
    idempotencyKey: sprintf('order-%d-shipped', $order->getId()),
));

The key identifies the logical message. A retry, a redelivery after a worker crash and a second dispatch from a duplicate event all produce the same key. A key generated inside the handler would change on each attempt and defeat the header. Our idempotency post explains why.

The handler

The handler makes the call and translates the outcome into Messenger's vocabulary. A recoverable exception means retry. An unrecoverable one means stop and send the message to the failure transport. Returning means done.

<?php
// src/MessageHandler/SendSmsHandler.php
namespace App\MessageHandler;

use App\Message\SendSms;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\RecoverableMessageHandlingException;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsMessageHandler]
final class SendSmsHandler
{
    public function __construct(
        private readonly HttpClientInterface $readyClient,
        private readonly LoggerInterface $logger,
    ) {
    }

    public function __invoke(SendSms $message): void
    {
        try {
            $response = $this->readyClient->request('POST', '/v1/messages', [
                'headers' => ['Idempotency-Key' => $message->idempotencyKey],
                'json' => [
                    'to' => $message->to,
                    'body' => $message->body,
                    'consent_attested' => true,
                ],
            ]);
            $status = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            // Timeout or dropped connection: the text may have gone out.
            // The same key makes a retry safe.
            throw new RecoverableMessageHandlingException($e->getMessage(), 0, $e);
        }

        if ($status >= 200 && $status < 300) {
            return;
        }

        $detail = $response->getContent(false);

        $body = json_decode($detail, true);
        $code = is_array($body) ? ($body['error_code'] ?? $body['code'] ?? '') : '';

        // Nothing ran, or the failure is not stored under the key: the same key is safe.
        if ($status === 429
            || in_array($code, ['idempotency_in_progress', 'send_failed', 'QUIET_HOURS_BLOCK'], true)) {
            throw new RecoverableMessageHandlingException(
                sprintf('Retryable %d %s for %s', $status, $code, $message->idempotencyKey)
            );
        }

        // Outcome unknown, or a stored 5xx that would only replay the same answer.
        // Check GET /v1/messages, then dispatch a new SendSms with a new key if it did not go out.
        if ($status >= 500 || $code === 'idempotency_outcome_unknown') {
            $this->logger->error('SMS needs a check before any resend', [
                'status' => $status,
                'code' => $code,
                'key' => $message->idempotencyKey,
            ]);
            throw new UnrecoverableMessageHandlingException(
                sprintf('Check before resending %d %s for %s', $status, $code, $message->idempotencyKey)
            );
        }

        $this->logger->warning('SMS refused', [
            'status' => $status,
            'key' => $message->idempotencyKey,
            'detail' => $detail,
        ]);
        throw new UnrecoverableMessageHandlingException(
            sprintf('Refused %d for %s', $status, $message->idempotencyKey)
        );
    }
}

to is E.164, and consent_attested is your statement that the recipient agreed to texts. Both are described in the messages API docs. Passing false to getContent() stops Symfony from throwing on a 4xx or 5xx, so you control the branch.

Route the message and set the retry strategy

Send SendSms to an async transport and give that transport a retry strategy.

# config/packages/messenger.yaml
framework:
  messenger:
    failure_transport: failed
    transports:
      sms:
        dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
        options:
          queue_name: sms
        retry_strategy:
          max_retries: 5
          delay: 30000
          multiplier: 3
          max_delay: 3600000
          jitter: 0.2
      failed: 'doctrine://default?queue_name=failed'
    routing:
      'App\Message\SendSms': sms

With these numbers the waits grow from 30 seconds to 90 seconds, 4.5 minutes, about 13 minutes and then 40 minutes, with a little jitter so a burst of failures does not retry in lockstep. After the last retry the message lands in the failed transport, where you can inspect it with messenger:failed:show and replay it with messenger:failed:retry.

Run the consumer under a process supervisor, and give it a time limit and a memory limit (the messenger:consume command has an option for each) so a leak never grows unnoticed and the worker restarts with fresh code after a deploy:

php bin/console messenger:consume sms -vv

Before you retry an old failed message, call GET /v1/messages to see whether it already went out. A replay long after Ready has stopped remembering the key can send again. See retries and failure handling for sorting failures into temporary, permanent and held.

What each outcome should do

OutcomeExceptionResult
2xxnoneMessage acknowledged
Transport error, timeoutRecoverableRetry with the same key
429, 409 idempotency_in_progress, 500 send_failedRecoverableRetry with backoff and the same key
409 QUIET_HOURS_BLOCKRecoverable, or avoid itTiming rule, not a bad request
Other 5xx, 409 idempotency_outcome_unknownUnrecoverableCheck GET /v1/messages, then send again with a new key if it did not go out; a stored 5xx only replays under the old key
Other 4xxUnrecoverableStraight to the failure transport

An API text is held only if the quiet-hours window opens within 6 hours. Otherwise the API answers 409 QUIET_HOURS_BLOCK, and the sender sends it again once the window opens. Add 'hold_until_allowed' => true to the json array and Ready holds the text up to 24 hours, so the handler finishes on the first call. Exact error bodies are in the error reference.

An inbound webhook controller

Replies and delivery reports arrive as requests to your app. Payload fields and the signature scheme come from your provider's docs, so the names below are generic placeholders.

<?php
// src/Controller/SmsWebhookController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;

final class SmsWebhookController extends AbstractController
{
    #[Route('/webhooks/sms', methods: ['POST'])]
    public function __invoke(Request $request, MessageBusInterface $bus): Response
    {
        $raw = $request->getContent();
        $expected = hash_hmac('sha256', $raw, $_ENV['WEBHOOK_SIGNING_SECRET']);
        $received = (string) $request->headers->get('X-Signature-Placeholder');

        if (!hash_equals($expected, $received)) {
            return new Response('', Response::HTTP_UNAUTHORIZED);
        }

        $bus->dispatch(new \App\Message\ProcessInboundEvent($raw));

        return new Response('', Response::HTTP_OK);
    }
}

Verify over the raw bytes, hand the work to a message and answer 200 quickly. Take the real header name and algorithm from the API quickstart. For the pattern in general, see receiving inbound SMS webhooks.

Test the handler

Mock HttpClientInterface with Symfony's MockHttpClient and MockResponse. Give it a 500 with error_code send_failed and assert RecoverableMessageHandlingException; give it a 500 hold_not_returned or a 422 and assert UnrecoverableMessageHandlingException. Give it a 422 and assert the unrecoverable one. Because nothing in the handler touches the network, these tests run in milliseconds.

Cost and registration

On Ready's Standard rate a segment costs $0.0075 plus a $0.0045 carrier fee, or $0.012 all-in, which does not include screening. Screening, the optional scrub and number validation, is $0.003 extra per segment for each switch turned on. A card on file and a number at $2 a month are required to send. An account can send up to 500 texts a month until its 10DLC registration is approved, and most approvals take 2 to 7 days. Accounts opened before November 12, 2026 keep the prices they signed up with, shown under Billing.

Ready's all-in prices per segment include the carrier fee but not screening: Scrub lists and Number validation, the two switches in Settings under Compliance, each add $0.003 per segment when switched on, shown as screening on your bill, and both are off by default. Unless you turn the opt-out footer off, the first text to each contact, and one again from time to time, also gets "Reply STOP to opt out" and your business name if the message does not already have them, so a text close to the segment limit can bill one more segment.

The short version

Use a scoped HttpClient with both timeouts, a Messenger message that carries its own idempotency key, a handler that maps statuses to recoverable and unrecoverable exceptions, and a failure transport someone watches. If you work in the other big PHP framework, the same request is in sending SMS from Laravel. When you want to try it, create an account and dispatch one message to your own phone.