Quick answer
To send SMS in Laravel, call the SMS API with the Http facade: Http::withToken(config('services.onlinesmsservice.key'))->acceptJson()->post('https://whitelabled.securesmsc.com/api/v2/sms/send', [...]) with sender_id, recipient and message. For Laravel SMS notifications, write a small channel class that makes this call, add a toSms() method to your notification, and implement ShouldQueue so failed sends are retried by the queue instead of slowing down the request.
What you'll build
| File | What it does |
|---|---|
.env, config/services.php | Your API key, sender ID and DLT entity ID |
app/Services/SmsClient.php | The API calls, with timeouts and safe retries |
app/Services/SmsException.php | The API's error as an exception |
app/Notifications/Channels/SmsChannel.php | The SMS notification channel |
app/Notifications/OrderShipped.php | An example queued notification with toSms() |
app/Jobs/SendBulkSms.php | Bulk sends, up to 1,000 numbers per job |
tests/Feature/SmsNotificationTest.php | Tests with Http::fake() |
Before you start you need an API key (free, from whitelabled.securesmsc.com/register, then API & Integrations → API Management), a DLT-approved sender ID such as ACMEIN, and approved message templates. We help with DLT registration at no extra charge. There is no sandbox mode: a successful call sends a real SMS and uses credits.
Whitelist every server that runs your queue workers. The first IP that uses a key successfully is added to the key's allowed list automatically, and other IPs then get HTTP 403 "IP address not allowed". If the web app, the queue workers and your laptop are on different machines — or you run several workers or containers — add each IP or an IPv4 CIDR range under API & Integrations → API Management → IP Whitelisting before the first call, or use one key per server.
Create an account and generate an API key straight away. Verified businesses also get 100 free test SMS once KYC and DLT mapping are done.
Step 1: Add the key to .env and config/services.php
SMS_API_KEY=your_api_key_here
SMS_SENDER_ID=ACMEIN
SMS_DLT_ENTITY_ID=1201160000000000000 'onlinesmsservice' => [
'key' => env('SMS_API_KEY'),
'sender_id' => env('SMS_SENDER_ID'),
'dlt_entity_id' => env('SMS_DLT_ENTITY_ID'),
],In your code, read these with config(), not env(): after php artisan config:cache, env() returns null outside the config files. The DLT entity ID stays a string, which is what the API expects.
Step 2: An SmsClient service on the Http facade
All API calls go through one class. It sets the base URL, the bearer token and Accept: application/json, a 5-second connect timeout and a 30-second total timeout (120 seconds for bulk calls), and turns any error into an SmsException with the API's own error text. Create the files with php artisan make:class Services/SmsClient or by hand.
<?php
namespace App\Services;
use Illuminate\Http\Client\Response;
use RuntimeException;
class SmsException extends RuntimeException
{
public function __construct(
string $message,
public readonly int $status = 0, // HTTP status; 0 = no response (network error)
public readonly ?string $error = null, // error_code, else error: "TEMPLATE_MISMATCH", "Unauthorized" …
public readonly array $errors = [], // details from the API's "errors" field
public readonly bool $retryable = false, // worth trying again later (429, 5xx, some network errors)
public readonly ?int $retryAfter = null, // seconds, sent with HTTP 429
) {
parent::__construct($message, $status);
}
public static function fromResponse(Response $response, bool $retryable): self
{
$json = $response->json() ?? [];
$details = collect($json['errors'] ?? [])->flatten()->implode('; ');
return new self(
($json['message'] ?? $json['error'] ?? 'HTTP '.$response->status()).($details !== '' ? ": $details" : ''),
status: $response->status(),
error: $json['error_code'] ?? $json['error'] ?? null,
errors: (array) ($json['errors'] ?? []),
retryable: $retryable,
retryAfter: $response->status() === 429
? (int) ($response->header('Retry-After') ?: ($json['retry_after'] ?? 60)) : null,
);
}
public function isTemplateMismatch(): bool
{
return $this->error === 'TEMPLATE_MISMATCH'
|| str_contains($this->getMessage(), 'Template verification failed');
}
}<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;
class SmsClient
{
public const BASE_URL = 'https://whitelabled.securesmsc.com/api/v2';
public function __construct(
#[\SensitiveParameter] private string $apiKey,
private string $senderId,
private ?string $dltEntityId = null,
private int $timeout = 30,
) {}
/** One SMS. $options: route, dlt_template_id, unicode, flash, schedule_at, timezone, sender_id. */
public function send(string $to, string $message, array $options = []): array
{
return $this->call('POST', 'sms/send', $options + ['recipient' => $to, 'message' => $message]);
}
/** The same SMS to 1–1,000 numbers. Check "failed" and "results" in the reply. */
public function sendBulk(array $to, string $message, array $options = []): array
{
return $this->call('POST', 'sms/send-bulk',
$options + ['recipients' => array_values($to), 'message' => $message], timeout: 120);
}
/** GET calls: tick "Allow GET Method" for the key first, or the API answers 403. */
public function status(int|string $messageId): array
{
return $this->call('GET', 'sms/status/'.rawurlencode((string) $messageId));
}
public function balance(): array
{
return $this->call('GET', 'balance');
}
private function call(string $method, string $path, array $body = [], ?int $timeout = null): array
{
$request = Http::baseUrl(self::BASE_URL)
->withToken($this->apiKey)
->acceptJson()
->connectTimeout(5)
->timeout($timeout ?? $this->timeout)
// Two quick retries (after 0.5 s, then 1.5 s) for 5xx and network errors.
// A 429 is not retried here: the queue retries the job after Retry-After.
->retry([500, 1500], throw: false, when: fn (Throwable $e) => self::retryable($e, $method)
&& ! ($e instanceof RequestException && $e->response->status() === 429));
try {
$response = $method === 'GET'
? $request->get($path)
: $request->post($path, $body + array_filter([
'sender_id' => $this->senderId, // $options can override both
'dlt_entity_id' => $this->dltEntityId,
]));
} catch (ConnectionException $e) {
throw new SmsException('Network error: '.$e->getMessage(), retryable: self::retryable($e, $method));
}
if ($response->successful() && $response->json('success') === true) {
return $response->json('data');
}
throw SmsException::fromResponse($response, self::retryable(new RequestException($response), $method));
}
/** 429, 5xx (except a 504 on a POST) and network errors where the request never left. Never other 4xx. */
private static function retryable(Throwable $e, string $method): bool
{
if ($e instanceof RequestException) {
$status = $e->response->status();
return $status === 429 || ($status >= 500 && ! ($method === 'POST' && $status === 504));
}
if ($e instanceof ConnectionException) {
// cURL error 6 (host not found) or 7 (could not connect): the SMS was never sent.
preg_match('/cURL error (\d+)/', $e->getMessage(), $m);
return $method === 'GET' || in_array((int) ($m[1] ?? 0), [6, 7], true);
}
return false;
}
}Register it once, so Laravel can inject it anywhere:
<?php
namespace App\Providers;
use App\Services\SmsClient;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(SmsClient::class, fn () => new SmsClient(
apiKey: (string) config('services.onlinesmsservice.key'),
senderId: (string) config('services.onlinesmsservice.sender_id'),
dltEntityId: config('services.onlinesmsservice.dlt_entity_id'),
));
}
public function boot(): void
{
//
}
}When it retries
- HTTP 500, 502, 503 and network errors where the request never left (host not found, could not connect): two quick retries inside the same call, after 0.5 and 1.5 seconds. GET calls are also retried after a timeout.
- HTTP 429 (rate limit): no quick retry. The exception has
retryableset and carriesretryAfterfrom theRetry-Afterheader, and the queue tries again later (step 4). - A POST that timed out, or got HTTP 504: not repeated, because the SMS may already be queued.
- Any other 4xx — a wrong key, an IP that isn't whitelisted, an unapproved sender ID, a template mismatch, too little balance: never retried.
You can call it directly, for example to send an OTP from a controller:
use App\Services\SmsClient;
use App\Services\SmsException;
try {
$sms = app(SmsClient::class)->send('9876543210', '482910 is your OTP to log in to Acme. Valid for 10 minutes. Do not share it. -Acme');
// $sms['message_id']: save it to check delivery later
} catch (SmsException $e) {
report($e); // $e->status, $e->error and $e->getMessage() hold the API's answer
}Status and balance are GET calls. They return HTTP 403 "GET method is not allowed for this API key" until you tick "Allow GET Method" for the key under API & Integrations → API Management.
Step 3: A Laravel SMS notification channel
First give users a mobile number. Create a migration with php artisan make:migration add_mobile_to_users_table, then run php artisan migrate:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('mobile', 15)->nullable()->after('email');
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('mobile');
});
}
};Tell Laravel which number to use for the sms channel:
use Illuminate\Notifications\Notification;
public function routeNotificationForSms(Notification $notification): ?string
{
return $this->mobile; // e.g. "9876543210"
}The channel takes the number and the text from the notification and calls SmsClient. Errors worth retrying are thrown, so the queue can try again. Others are logged, a NotificationFailed event is fired, and the channel stops.
<?php
namespace App\Notifications\Channels;
use App\Services\SmsClient;
use App\Services\SmsException;
use Illuminate\Notifications\Events\NotificationFailed;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
class SmsChannel
{
public function __construct(private SmsClient $sms) {}
public function send(object $notifiable, Notification $notification): ?array
{
$to = $notifiable->routeNotificationFor('sms', $notification);
if (! $to) {
return null; // no mobile number on file
}
// toSms() returns the text, or ['message' => …, 'dlt_template_id' => …]
$sms = $notification->toSms($notifiable);
$sms = is_string($sms) ? ['message' => $sms] : $sms;
$message = $sms['message'];
unset($sms['message']);
try {
return $this->sms->send($to, $message, $sms);
} catch (SmsException $e) {
if ($e->retryable) {
throw $e; // 429 / 5xx / network: the queue tries again ($tries, $backoff)
}
// Other 4xx: retrying can't help. Record it and stop.
Log::error('SMS notification not sent', [
'notification' => $notification::class,
'to' => '******'.substr($to, -4),
'status' => $e->status,
'error' => $e->getMessage(),
]);
event(new NotificationFailed($notifiable, $notification, 'sms', [
'status' => $e->status, 'error' => $e->getMessage(),
]));
return null;
}
}
}Now any notification can send SMS. Create one with php artisan make:notification OrderShipped. toSms() returns the text, or an array with message plus any API option, such as dlt_template_id, route or sender_id.
<?php
namespace App\Notifications;
use App\Notifications\Channels\SmsChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use Throwable;
class OrderShipped extends Notification implements ShouldQueue
{
use Queueable;
public $tries = 3; // for 429 / 5xx / network errors
public $backoff = [60, 300]; // wait 1 minute, then 5 minutes
public function __construct(public string $orderNo, public string $trackingUrl) {}
public function via(object $notifiable): array
{
return [SmsChannel::class]; // add 'mail', 'database' … as needed
}
public function toSms(object $notifiable): array|string
{
// Must match your approved DLT template word for word.
return [
'message' => "Your Acme order {$this->orderNo} has shipped. Track it at {$this->trackingUrl} -Acme",
'dlt_template_id' => '1207160000000000001', // optional; a string, not an int
];
}
/** Runs once all $tries are used up (the job is then in failed_jobs). */
public function failed(Throwable $e): void
{
Log::error('OrderShipped SMS failed after retries', ['order' => $this->orderNo, 'error' => $e->getMessage()]);
}
}Send it to a user, or to any number with an on-demand notification:
use App\Notifications\OrderShipped;
use Illuminate\Support\Facades\Notification;
$user->notify(new OrderShipped('A1001', 'https://acme.in/t/A1001'));
// Or to a number that isn't a user:
Notification::route('sms', '9876543210')->notify(new OrderShipped('A1001', 'https://acme.in/t/A1001'));Step 4: Queued notifications, retries and failed jobs
Because OrderShipped implements ShouldQueue, notify() only stores a job, and a queue worker makes the API call. The page your user is waiting for doesn't wait for the SMS. What happens when a send fails:
| The API returns | What happens |
|---|---|
| 429, 5xx, or a network error before sending | The channel throws. The queue tries again after 60 seconds, then after 300 seconds ($backoff). After the third try ($tries), failed() runs and the job is stored in failed_jobs. |
| 400, 401, 403, 404, 422 | Logged as "SMS notification not sent" and a NotificationFailed event is fired. The job ends without retrying — a wrong key or template won't fix itself. |
| A timeout after sending, or 504 | Treated like a 4xx and not retried, so a customer doesn't get the same SMS twice. Check the status before you resend. |
php artisan queue:work # run the worker (keep it running with Supervisor or systemd)
php artisan queue:failed # list jobs that used up their tries
php artisan queue:retry all # push them back onto the queueLaravel 11 and later use the database queue by default, and the default migrations already create the jobs and failed_jobs tables.
Step 5: Bulk SMS in chunks of 1,000
The send-bulk endpoint sends the same text to up to 1,000 numbers per call. Use one queued job per 1,000 numbers:
<?php
namespace App\Jobs;
use App\Services\SmsClient;
use App\Services\SmsException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
class SendBulkSms implements ShouldQueue
{
use Queueable;
public $tries = 3;
public $timeout = 150; // longer than the 120 s HTTP timeout for bulk calls
/** @param string[] $numbers up to 1,000 numbers */
public function __construct(public array $numbers, public string $message, public array $options = []) {}
public function handle(SmsClient $sms): void
{
try {
$result = $sms->sendBulk($this->numbers, $this->message, $this->options);
} catch (SmsException $e) {
// 429 / 5xx: try again later. Anything else: stop (the job goes to failed_jobs).
$e->retryable ? $this->release($e->retryAfter ?? 60) : $this->fail($e);
return;
}
// HTTP 200 does not mean every number was queued: check each result.
$failed = collect($result['results'])->where('status', 'failed');
if ($failed->isNotEmpty()) {
Log::warning('Bulk SMS: some numbers not queued', [
'broadcast_id' => $result['broadcast_id'],
'failed' => $failed->count(),
'reasons' => $failed->countBy('error')->all(),
]);
}
}
}use App\Jobs\SendBulkSms;
use App\Models\User;
User::whereNotNull('mobile')->select('id', 'mobile')->chunkById(1000, function ($users) {
SendBulkSms::dispatch($users->pluck('mobile')->all(), 'Our Sulur store is open till 9 PM today. -Acme');
});- Check every number. The API returns HTTP 200 even when some numbers were not queued. Each result is
queued,held(waiting for review) orfailedwith an error. - Balance is all-or-nothing. If your credit can't cover the whole chunk, every number comes back
failedwith "Insufficient credits. Required: X, Available: Y". The job logs the count per reason, so you see this as one line, not 1,000. - Rate limits. Each key allows 60 requests a minute and 10,000 a day by default; a bulk call counts as one. On a 429 the job is released for the
Retry-Afterseconds. - Promotional campaigns go out only between 9 AM and 9 PM. Pass
['route' => 'promotional']as the options.
Step 6: Test with Http::fake()
Tests should never reach the real API. Give the test run a dummy key in phpunit.xml:
<env name="SMS_API_KEY" value="test-key"/>
<env name="SMS_SENDER_ID" value="ACMEIN"/><?php
namespace Tests\Feature;
use App\Models\User;
use App\Notifications\OrderShipped;
use App\Services\SmsClient;
use App\Services\SmsException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Sleep;
use Tests\TestCase;
class SmsNotificationTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Http::preventStrayRequests(); // nothing may reach the real API
Sleep::fake(); // skip retry waits
}
public function test_order_shipped_sends_an_sms(): void
{
Http::fake(['*/sms/send' => Http::response([
'success' => true,
'message' => 'SMS queued successfully',
'data' => ['message_id' => 123, 'queue_id' => 123, 'status' => 'queued'],
])]);
User::factory()->create(['mobile' => '9876543210'])
->notify(new OrderShipped('A1001', 'https://acme.in/t/A1001'));
Http::assertSent(fn (Request $r) => $r->url() === 'https://whitelabled.securesmsc.com/api/v2/sms/send'
&& $r->hasHeader('Authorization', 'Bearer test-key')
&& $r['sender_id'] === 'ACMEIN'
&& $r['recipient'] === '9876543210'
&& str_contains($r['message'], 'A1001'));
}
public function test_a_wrong_key_is_not_retried(): void
{
Http::fake(['*/sms/send' => Http::response([
'success' => false, 'error' => 'Unauthorized', 'message' => 'Invalid API key',
], 401)]);
try {
app(SmsClient::class)->send('9876543210', 'Test');
$this->fail('Expected SmsException');
} catch (SmsException $e) {
$this->assertSame(401, $e->status);
$this->assertFalse($e->retryable);
}
Http::assertSentCount(1);
}
public function test_a_server_error_is_retried(): void
{
Http::fake(['*/sms/send' => Http::sequence()
->push(['success' => false, 'error' => 'Internal server error'], 500)
->push(['success' => true, 'data' => ['message_id' => 7, 'status' => 'queued']])]);
$this->assertSame(7, app(SmsClient::class)->send('9876543210', 'Test')['message_id']);
Http::assertSentCount(2);
}
}Run it with php artisan test. The default phpunit.xml sets QUEUE_CONNECTION=sync, so the queued notification runs straight away inside the test.
Our own test suite for this page goes further: every 4xx (401, 403, 400, 422) is sent once and not retried; a 500 is retried; a POST timeout is not repeated but a GET is; 2,001 users become three bulk calls of 1,000, 1,000 and 1; and on the database queue a 5xx is tried three times and then lands in failed_jobs. All 21 of those tests, plus one call to the live API with a dummy key (it returns the 401 JSON), pass on Laravel 11.57, 12.71 and 13.40.
Laravel 11, 12 and 13 notes
- Same code on all three. We ran it on Laravel 11.57.1, 12.71.0 and 13.40.0 with PHP 8.3.6, without changes.
- Laravel 13 needs PHP 8.3 or newer. It also lets you set
#[Tries]and#[Backoff]as attributes; the$triesand$backoffproperties used here still work. - Laravel 12 needs PHP 8.2 or newer and gets security fixes until 24 February 2027.
- Laravel 11 stopped getting security fixes on 12 March 2026. The code works, but plan an upgrade.
- Apps created on Laravel 11 or later have no
app/Http/Kernel.php; the binding goes inAppServiceProvider, andconfig/services.phpis included. Jobs use the singleIlluminate\Foundation\Queue\Queueabletrait, which Laravel 10 doesn't have. We have not tested Laravel 10 or older.
Support dates are from Laravel's own release notes, checked on 7 November 2026.
Not using Laravel?
The PHP SMS guide has the same API in plain PHP with cURL, a dependency-free class, and the full table of error codes. There are also guides for Node.js and Python, and the complete API reference. SMS sent through the API cost the same as any other: ₹0.20 on Starter or ₹0.15 on Business, plus GST — see pricing.