To send a text from PHP, POST JSON to your SMS provider's REST endpoint with an API key in a header. In Laravel, the built-in Http facade does it in one chained call. You don't need a provider SDK, and you can fake the API in tests without touching the network. The part that takes thought is the queue: a job that retries must reuse the same idempotency key, or a retry can text the same person twice.

We make Ready, so the examples use the Ready REST API and only the request shape we document. The patterns hold for any provider. We show plain PHP first, then the Laravel version with config, a service class, a queued job and a test.

What you need before the first request

  • An API key, sent in an X-API-Key header. Keep it in .env, never in the repository.
  • A card and a number. Both are required to send. The number is $2 a month. To build and test first, create a test key (Settings, Developers, Environment: Test): it simulates every send, with no card, number or charge. Add the card and number before you go live.
  • Consent. Every request carries consent_attested: true, your promise that the recipient agreed to texts. Set it only when that's true.
  • A registration plan. An account can send up to 500 texts a month before it registers for 10DLC, at its normal per-text rate. After that it has to register, and most approvals take 2 to 7 days. See what 10DLC is for the background.

Every text is charged from the first one: a segment costs $0.0075 plus a $0.0045 carrier fee, passed through at cost, and screening is extra when switched on.

Plain PHP with cURL

The endpoint is POST https://api.tryready.com/v1/messages. The body takes to in E.164 format (a 10-digit US number is treated as +1), body and consent_attested.

<?php

function sendText(string $to, string $body, string $idempotencyKey): array
{
    $payload = json_encode([
        'to' => $to,
        'body' => $body,
        'consent_attested' => true,
    ], JSON_THROW_ON_ERROR);

    $ch = curl_init('https://api.tryready.com/v1/messages');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_HTTPHEADER => [
            'X-API-Key: ' . getenv('READY_API_KEY'),
            'Content-Type: application/json',
            'Idempotency-Key: ' . $idempotencyKey,
        ],
    ]);

    $response = curl_exec($ch);
    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new RuntimeException('Request failed: ' . $error);
    }
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ['status' => $status, 'body' => $response];
}

$result = sendText('+12125550199', 'Your order #1042 has shipped.', bin2hex(random_bytes(16)));
echo $result['status'] . ' ' . $result['body'] . PHP_EOL;

json_encode builds the payload, so a name with a quote or a newline can't break the JSON. The timeout stops a slow network from hanging a worker. For the exact response fields and errors, read the messages API reference.

The Laravel version

Config

Put the key in .env and expose it through config/services.php, so code reads config rather than the environment directly. That keeps config:cache working.

// config/services.php
'ready' => [
    'key' => env('READY_API_KEY'),
    'base_url' => env('READY_BASE_URL', 'https://api.tryready.com'),
],

A small service class

<?php

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;

class ReadySms
{
    public function send(string $to, string $body, string $idempotencyKey): Response
    {
        return Http::baseUrl(config('services.ready.base_url'))
            ->withHeaders([
                'X-API-Key' => config('services.ready.key'),
                'Idempotency-Key' => $idempotencyKey,
            ])
            ->acceptJson()
            ->asJson()
            ->timeout(15)
            ->retry(
                3,
                500,
                fn ($exception) => $exception instanceof ConnectionException,
                throw: false,
            )
            ->post('/v1/messages', [
                'to' => $to,
                'body' => $body,
                'consent_attested' => true,
            ]);
    }
}

Two details matter. retry here fires only on connection errors, and throw: false hands you the response instead of throwing on a 4xx, so your code decides what each status means. Because the idempotency key is set once outside the retry loop, every attempt in that loop carries the same key.

The queue: where double sends happen

Most Laravel apps send from a queued job. Queue workers retry failed jobs, and that's where a duplicate text is born, unless the key survives the retry. Generate the key when you dispatch, store it on the job, and let every attempt use it:

<?php

namespace App\Jobs;

use App\Services\ReadySms;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;

class SendOrderText implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public array $backoff = [30, 120];

    public function __construct(
        public string $to,
        public string $body,
        public string $idempotencyKey = '',
    ) {
        $this->idempotencyKey = $idempotencyKey ?: (string) Str::uuid();
    }

    public function handle(ReadySms $sms): void
    {
        $response = $sms->send($this->to, $this->body, $this->idempotencyKey);

        if ($response->successful()) {
            return;
        }

        $status = $response->status();
        $retryable = $status === 429
            || ($status === 409 && str_contains($response->body(), 'idempotency_in_progress'));

        if ($retryable) {
            $this->release(30); // same job, same key
            return;
        }

        $this->fail(new \RuntimeException("SMS not sent: {$status} {$response->body()}"));
    }
}

The key is created in the constructor, which runs once at dispatch. Laravel serializes the job with that value, so attempt two and attempt three send the same key. Better still, store the key on your own database row for the message, so a duplicate dispatch of the same logical message reuses it too.

Dispatch it like any job: SendOrderText::dispatch('+12125550199', 'Your order #1042 has shipped.');

Which failures to retry

ResponseWhat to do
Network error or timeoutRetry with the same key
429Back off, retry with the same key
409 idempotency_in_progressWait, retry with the same key
503Not sent and not charged. Resend with a new key
504, or a code ending in OUTCOME_UNKNOWNCheck GET /v1/messages before resending
Other 4xxDon't retry. Log the body and fix the input

Ready also refuses opted-out numbers, numbers on your Ban list and known landlines up front, without charging. Treat those as final. Our posts on idempotency keys and retries and failure handling explain the reasoning.

Test it without texting anyone

Laravel's Http::fake() replaces the network, so tests are fast, free and safe. Assert that the request carries the headers and that the key doesn't change:

use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;

it('sends the same idempotency key on a retried job', function () {
    Http::fake(['*/v1/messages' => Http::response(['ok' => true], 200)]);

    $job = new SendOrderText('+12125550199', 'Your order #1042 has shipped.');
    $job->handle(app(ReadySms::class));
    $job->handle(app(ReadySms::class));

    Http::assertSent(fn (Request $r) => $r->hasHeader('Idempotency-Key', $job->idempotencyKey)
        && $r->hasHeader('X-API-Key')
        && $r['consent_attested'] === true);
    Http::assertSentCount(2);
});

A faked test proves your code builds the right request and handles each status. It doesn't prove a text reaches a phone, so send a few real texts to numbers you own before launch. The sandbox and test numbers guide lays out the layers. Use 555-01xx placeholder numbers in E.164 form, like +12125550199, in fixtures, never real ones.

Sending to many numbers

To send the same message to many recipients, POST /v1/messages/bulk takes to as an array, with at most 100 recipients per call. In Laravel, $contacts->pluck('phone')->chunk($limit) gives you the batches, with $limit set to that per-call maximum, and each batch becomes its own queued job with its own stored key. If the process dies halfway, a restart reuses each batch's key, so a batch that already went out isn't sent again. The bulk messages docs have the request and response details.

Keep the queue worker count modest. A 429 means slow down, so back off instead of adding workers. And remember that segments are what's metered: an emoji cuts a segment to 70 characters, so a 140-character text with one emoji is 3 segments, not 1.

Receiving replies in Laravel

For delivery reports and inbound replies, add a POST route that the provider calls. Exclude it from CSRF verification, since the caller has no session. Read the raw body with $request->getContent(), verify the signature over those exact bytes, dispatch a job, and return a 200 right away. Payload fields and the signature header are in the docs, so follow them there. Our inbound webhooks guide covers the pattern, and testing it on your machine is covered in testing SMS webhooks locally with a tunnel.

Wrapping up

In Laravel, the Http facade makes the request short. The decisions that matter are a key created once per logical message, retries only on safe failures, and a webhook route that acknowledges fast. Comparing stacks? The Node.js and Python guides use the same request. When you're ready, sign up and follow the API quickstart.