Quick answer
To send SMS in PHP, POST JSON to https://whitelabled.securesmsc.com/api/v2/sms/send with the header Authorization: Bearer YOUR_API_KEY and three fields: sender_id (your approved DLT header), recipient (a 10-digit Indian mobile number) and message (text that matches an approved DLT template). HTTP 200 with "success": true means the SMS is queued, and data.message_id identifies it. Use PHP's curl extension — there is no SDK to install.
What you need before the first call
- An account and an API keySign up at whitelabled.securesmsc.com/register, then create a key under API & Integrations → API Management. The key is free.
- An approved sender ID and templateBusiness SMS in India go out under a DLT-registered header (for example
ACMEIN) and must match a DLT-approved template. We help with DLT registration at no extra charge; approval usually takes 2–7 business days. See the DLT registration guide. - PHP with the curl and json extensionsCheck with
php -m. We tested every sample on PHP 8.3.6. The class further down uses PHP 8.1 syntax. - A list of the servers that will call the APIKeys are locked to IP addresses, as explained below.
Each API key is locked to IP addresses. The first IP that uses a key successfully is added to that key's allowed list automatically. After that, calls from any other IP get HTTP 403 "IP address not allowed". If your code runs on more than one server, on your laptop and a server, or on serverless functions, add every IP (or an IPv4 CIDR range) under API & Integrations → API Management → IP Whitelisting before the first call — or create a separate key for each server.
There is no sandbox mode. Every successful call sends a real SMS and uses credits, so test with your own mobile number. A call with a wrong key is safe: it returns 401 and sends nothing.
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.
Quick start: send an SMS with PHP cURL
Save this as send-sms.php. It reads the API key from an environment variable, so the key never sits in your code.
<?php
// send-sms.php: run with SMS_API_KEY=your_key php send-sms.php
$ch = curl_init('https://whitelabled.securesmsc.com/api/v2/sms/send');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('SMS_API_KEY'),
'Content-Type: application/json',
'Accept: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'sender_id' => 'ACMEIN', // your approved DLT header
'recipient' => '9876543210', // 10-digit Indian mobile number
'message' => '482910 is your OTP to log in to Acme. Valid for 10 minutes. Do not share it. -Acme',
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$res = json_decode((string) $body, true);
if ($body === false) {
echo 'Network error: ' . curl_error($ch) . PHP_EOL;
} elseif ($status === 200 && ($res['success'] ?? false)) {
echo 'Queued. message_id: ' . $res['data']['message_id'] . PHP_EOL;
} else {
$code = $res['error_code'] ?? $res['error'] ?? 'Error';
echo "Failed (HTTP $status) $code: " . ($res['message'] ?? $body) . PHP_EOL;
}Run it from the command line:
SMS_API_KEY=your_api_key php send-sms.phpA successful call returns this JSON, and the script prints Queued. message_id: …:
{
"success": true,
"message": "SMS queued successfully",
"data": {
"message_id": 4821,
"queue_id": 4821,
"status": "queued",
"estimated_delivery": "2026-11-07T10:17:02.000000Z"
}
}With a wrong key the live API answers {"success":false,"error":"Unauthorized","message":"Invalid API key"} and the script prints Failed (HTTP 401) Unauthorized: Invalid API key. A few rules worth knowing from the start:
recipientcan be9876543210or+919876543210.messagecan be up to 1,600 characters and must match your approved template word for word, including the brand name at the end.- "queued" means the API accepted the SMS. It does not mean it was delivered — see delivery status.
Keep the API key out of your code
Read the key with getenv('SMS_API_KEY') and set it where your PHP runs, not in a file that goes into Git:
| Where PHP runs | Where to set SMS_API_KEY |
|---|---|
| PHP-FPM | In the pool file: env[SMS_API_KEY] = your_api_key, then reload PHP-FPM |
| Apache with mod_php | In the virtual host: SetEnv SMS_API_KEY your_api_key |
| Cron or the command line | In the crontab line or the systemd unit (Environment=SMS_API_KEY=…) |
| Shared hosting | A PHP file outside the web root that returns the key, loaded with require |
Never put the key in JavaScript or a mobile app. Anyone could read it there and send SMS on your account. Call the API from your server, give each server or integration its own key, and replace a key if it may have leaked.
A reusable PHP SMS class (no Composer)
For anything beyond a one-off script, keep the API calls in one class. This one has no dependencies. It sets timeouts, turns every error into an exception that carries the API's own error text, and retries only when retrying can help. It has four methods: send(), sendBulk(), status() and balance().
<?php
declare(strict_types=1);
/**
* SmsGateway: a small client for the OnlineSMSService SMS API (v2).
* No Composer packages. Needs PHP 8.1+ with the curl and json extensions.
*/
final class SmsApiException extends RuntimeException
{
public function __construct(
string $message,
public readonly int $httpStatus = 0, // 0 = no HTTP response (network error)
public readonly ?string $errorCode = null, // error_code, else error: "TEMPLATE_MISMATCH", "Unauthorized" …
public readonly array $errors = [], // details from the API's "errors" field
public readonly ?int $retryAfter = null, // seconds, sent with HTTP 429
) {
parent::__construct($message, $httpStatus);
}
public function isTemplateMismatch(): bool
{
return $this->errorCode === 'TEMPLATE_MISMATCH'
|| str_contains($this->getMessage(), 'Template verification failed');
}
}
final class SmsGateway
{
private const BASE_URL = 'https://whitelabled.securesmsc.com/api/v2';
public function __construct(
#[\SensitiveParameter] private readonly string $apiKey,
private readonly string $senderId, // your approved DLT header, e.g. "ACMEIN"
private readonly int $timeout = 30, // seconds for the whole request
private readonly int $maxRetries = 2, // extra attempts after the first
private readonly int $maxWait = 60, // longest Retry-After (seconds) worth waiting for
) {
if (trim($apiKey) === '') {
throw new InvalidArgumentException('SMS API key is empty. Set SMS_API_KEY.');
}
}
public static function fromEnv(): self
{
return new self((string) getenv('SMS_API_KEY'), (string) getenv('SMS_SENDER_ID'));
}
/** One SMS. $options: route, dlt_entity_id, dlt_template_id, unicode, flash, schedule_at, timezone, sender_id. */
public function send(string $to, string $message, array $options = []): array
{
return $this->request('POST', '/sms/send',
$options + ['sender_id' => $this->senderId, '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
{
if ($to === [] || count($to) > 1000) {
throw new InvalidArgumentException('sendBulk() takes 1 to 1,000 numbers per call.');
}
return $this->request('POST', '/sms/send-bulk',
$options + ['sender_id' => $this->senderId, 'recipients' => array_values($to), 'message' => $message]);
}
/** GET call: tick "Allow GET Method" for the key first, or the API answers 403. */
public function status(int|string $messageId): array
{
return $this->request('GET', '/sms/status/' . rawurlencode((string) $messageId));
}
/** GET call: tick "Allow GET Method" for the key first, or the API answers 403. */
public function balance(): array
{
return $this->request('GET', '/balance');
}
private function request(string $method, string $path, ?array $body = null): array
{
for ($attempt = 0; ; $attempt++) {
try {
return $this->once($method, $path, $body);
} catch (SmsApiException $e) {
$wait = $attempt < $this->maxRetries ? $this->retryDelay($e, $method, $attempt) : null;
if ($wait === null) {
throw $e;
}
usleep((int) ($wait * 1_000_000));
}
}
}
/** Seconds to wait before the next attempt, or null when retrying cannot help. */
private function retryDelay(SmsApiException $e, string $method, int $attempt): ?float
{
$backoff = 0.5 * 2 ** $attempt + random_int(0, 250) / 1000; // 0.5 s, 1 s … plus jitter
return match (true) {
// 429: wait as long as the API asks, if that is not too long
$e->httpStatus === 429 => ($e->retryAfter ?? 60) <= $this->maxWait ? (float) ($e->retryAfter ?? 60) : null,
// 5xx: retry, except a 504 on a POST (the SMS may still be queued)
$e->httpStatus >= 500 => ($method === 'POST' && $e->httpStatus === 504) ? null : $backoff,
// network error: retry a GET; retry a POST only if the request never left this server
$e->httpStatus === 0 => ($method === 'GET' || $e->errorCode === 'CONNECT_FAILED') ? $backoff : null,
// any other 4xx: the request itself is wrong (key, IP, sender ID, template, balance)
default => null,
};
}
private function once(string $method, string $path, ?array $body): array
{
$headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json'];
$retryAfter = null;
$ch = curl_init(self::BASE_URL . $path);
$opts = [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$retryAfter): int {
if (stripos($line, 'Retry-After:') === 0) {
$retryAfter = (int) trim(substr($line, 12));
}
return strlen($line);
},
];
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
$opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
}
curl_setopt_array($ch, $opts + [CURLOPT_HTTPHEADER => $headers]);
$raw = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($raw === false) {
// No pre-transfer time = DNS, connect or TLS failed, so the request never left.
$neverSent = curl_getinfo($ch, CURLINFO_PRETRANSFER_TIME_T) === 0;
throw new SmsApiException('Network error: ' . curl_error($ch), 0,
$neverSent ? 'CONNECT_FAILED' : 'NETWORK_ERROR');
}
$json = json_decode($raw, true);
if (!is_array($json)) {
throw new SmsApiException("Unexpected non-JSON response (HTTP $status)", $status, 'BAD_RESPONSE');
}
if ($status >= 200 && $status < 300 && ($json['success'] ?? false) === true) {
return $json['data'];
}
// Read error_code, then error, then message; add the details from "errors".
$errors = (array) ($json['errors'] ?? []);
$details = [];
array_walk_recursive($errors, function ($v) use (&$details) { $details[] = (string) $v; });
$message = ($json['message'] ?? $json['error'] ?? "HTTP $status")
. ($details ? ': ' . implode('; ', $details) : '');
throw new SmsApiException($message, $status, $json['error_code'] ?? $json['error'] ?? null, $errors,
$retryAfter ?? (isset($json['retry_after']) ? (int) $json['retry_after'] : null));
}
}Use it like this. Set SMS_API_KEY and SMS_SENDER_ID (your approved header) in the environment first.
<?php
require __DIR__ . '/SmsGateway.php';
$sms = SmsGateway::fromEnv(); // reads SMS_API_KEY and SMS_SENDER_ID
try {
$r = $sms->send('9876543210', '482910 is your OTP to log in to Acme. Valid for 10 minutes. Do not share it. -Acme');
echo "Queued. message_id: {$r['message_id']}\n"; // save it to check delivery later
} catch (SmsApiException $e) {
error_log("SMS not sent: HTTP {$e->httpStatus} {$e->errorCode}: {$e->getMessage()}");
echo match (true) {
$e->httpStatus === 401 => "Check SMS_API_KEY: {$e->getMessage()}\n",
$e->httpStatus === 403 => "Key refused for this server: {$e->getMessage()}\n",
$e->isTemplateMismatch() => "Text doesn't match an approved DLT template: {$e->getMessage()}\n",
$e->httpStatus === 429 => "Rate limited. Try again in {$e->retryAfter} seconds.\n",
default => "Not sent: {$e->getMessage()}\n",
};
}When the class retries, and when it doesn't
- HTTP 429 (rate limit): it waits for the number of seconds in the
Retry-Afterheader, if that is no more thanmaxWait(60 seconds by default), then tries again. When you hit the daily limit,Retry-Afteris a whole day, so it stops at once and you can read$e->retryAfter. In a web request — an OTP on a login page — create the client withmaxWait: 0so the visitor isn't kept waiting. - HTTP 500, 502 and 503: up to two more tries, about 0.5 and 1 second apart.
- Network errors: a GET is retried. A POST is retried only if the connection never opened (DNS, connect or TLS failure), because then the SMS cannot have been sent.
- Not retried: a POST that timed out after it was sent, or got HTTP 504. The SMS may already be queued, so check its status or your dashboard before you send it again.
- Never retried: any other 4xx — 400, 401, 403, 404, 422. The key, IP, sender ID, template or balance needs fixing first.
By default each key allows 60 requests a minute and 10,000 a day. A bulk call counts as one request however many numbers it carries.
Send bulk SMS in PHP
The /sms/send-bulk endpoint sends the same text to up to 1,000 numbers in one call. Split longer lists with array_chunk() and check the result for every number.
<?php
require __DIR__ . '/SmsGateway.php';
$sms = SmsGateway::fromEnv();
$numbers = ['9876543210', '9876543211', '9123456789']; // e.g. loaded from your database
$text = 'Your Acme order is ready for pickup. Show this SMS at the counter. -Acme';
$failed = [];
foreach (array_chunk($numbers, 1000) as $batch) { // up to 1,000 numbers per call
$r = $sms->sendBulk($batch, $text);
echo "{$r['successful']} queued, {$r['failed']} failed\n";
foreach ($r['results'] as $row) {
if ($row['status'] === 'failed') {
$failed[$row['recipient']] = $row['error'];
}
}
}
print_r($failed); // fix the cause, then resend to these numbers onlyHTTP 200 does not mean every number was queued. Each entry in results has the status queued, held (accepted but waiting for review) or failed with an error. A bulk call is all-or-nothing on balance: if your credit can't cover the whole batch, the call still returns 200, but every number is failed with "Insufficient credits. Required: X, Available: Y".
Use bulk when everyone gets the same text. For personalised text — a name, an order number — call send() once per person and stay within 60 requests a minute. Talk to us if you need more.
Check delivery status and balance
GET calls are off for new API keys. Status, balance, sender IDs and templates are GET requests. Until you tick "Allow GET Method" for the key under API & Integrations → API Management, they return HTTP 403 "GET method is not allowed for this API key".
<?php
// GET calls: tick "Allow GET Method" for this key under
// API & Integrations → API Management, or they return HTTP 403.
require __DIR__ . '/SmsGateway.php';
$sms = SmsGateway::fromEnv();
try {
$s = $sms->status($argv[1] ?? '4821'); // the message_id you saved when sending
echo "Message {$s['message_id']} to {$s['recipient']}: {$s['status']}\n";
$b = $sms->balance();
echo "Balance: {$b['balance']} {$b['currency']}\n";
} catch (SmsApiException $e) {
echo "HTTP {$e->httpStatus}: {$e->getMessage()}\n";
}While a message waits, its status is the queue status (for example queued). After the operator's delivery report arrives, it is that report's status text (for example DELIVRD). Operators don't all spell statuses the same way, so compare without case and log values you don't recognise. An unknown ID returns HTTP 404 "Message not found".
Instead of polling, the Business and Enterprise plans can push delivery reports to a URL on your server. The platform sends an HTTP GET with messageid, status, number and date (India time) when a message reaches its final status. Reply within 10 seconds; a failed push is retried once after 60 seconds. See delivery report webhooks in the API reference.
Send Hindi, Tamil and other Unicode SMS
<?php
require __DIR__ . '/SmsGateway.php';
$sms = SmsGateway::fromEnv();
// Save this file as UTF-8. The text must match a template approved in Tamil (or Hindi).
$text = 'உங்கள் OTP 482910. இதை யாருடனும் பகிர வேண்டாம். -Acme';
// $text = 'आपका OTP 482910 है। इसे किसी के साथ साझा न करें। -Acme';
$r = $sms->send('9876543210', $text); // Unicode is detected automatically
$chars = mb_strlen($text, 'UTF-8'); // not strlen(): that counts bytes
$parts = $chars <= 70 ? 1 : (int) ceil($chars / 67);
echo "Queued {$r['message_id']}: $chars characters, $parts SMS part(s)\n";You don't need to set a flag: the platform switches to Unicode as soon as the text has any non-ASCII character. (The unicode option exists, but it is optional.) A Unicode SMS holds 70 characters, or 67 per part when the message is longer, against 160 and 153 for plain English text. Each part is billed as one SMS.
Watch for hidden Unicode in English messages. One curly quote (’) or ₹ sign pasted from a document makes the whole message Unicode, and a 150-character message goes from one part to three. Use straight quotes and "Rs" in English templates, and check the final text with the SMS character counter.
DLT fields: route, entity ID and template ID
<?php
require __DIR__ . '/SmsGateway.php';
$sms = SmsGateway::fromEnv();
$r = $sms->send('9876543210',
'482910 is your OTP to log in to Acme. Valid for 10 minutes. Do not share it. -Acme', [
'route' => 'transactional',
'dlt_entity_id' => '1201160000000000000', // your Principal Entity ID, as a string
'dlt_template_id' => '1207160000000000000', // the approved template's ID, as a string
]);
echo "Queued {$r['message_id']}\n";routeistransactional(the default) orpromotional. Promotional SMS are sent only between 9 AM and 9 PM.dlt_entity_idanddlt_template_idare strings of up to 20 characters. Quote them: a PHP integer becomes a JSON number, and the API rejects it with HTTP 422 "must be a string".- If you leave out
dlt_entity_id, the platform uses the one saved with your sender ID or account. - Sending both IDs skips the platform's own template matching. The operators still check the text against DLT, so it must still match the approved template.
Templates use typed variables such as {#numeric#} and {#url#}; see DLT template variables. Before you go live, paste your final text into the DLT template checker.
Optional: the same call with Guzzle
If your project already uses Guzzle (guzzlehttp/guzzle), you can use it instead of cURL. Set http_errors to false so 4xx and 5xx replies come back as responses you can read. Network failures still throw GuzzleHttp\Exception\ConnectException.
<?php
// composer require guzzlehttp/guzzle
require __DIR__ . '/vendor/autoload.php';
$client = new GuzzleHttp\Client([
'base_uri' => 'https://whitelabled.securesmsc.com/api/v2/',
'connect_timeout' => 5,
'timeout' => 30,
'http_errors' => false, // read 4xx/5xx bodies yourself
'headers' => [
'Authorization' => 'Bearer ' . getenv('SMS_API_KEY'),
'Accept' => 'application/json',
],
]);
$res = $client->post('sms/send', ['json' => [
'sender_id' => 'ACMEIN',
'recipient' => '9876543210',
'message' => '482910 is your OTP to log in to Acme. Valid for 10 minutes. Do not share it. -Acme',
]]);
$data = json_decode((string) $res->getBody(), true);
echo $res->getStatusCode() === 200 && ($data['success'] ?? false)
? "Queued. message_id: {$data['data']['message_id']}\n"
: "Failed (HTTP {$res->getStatusCode()}): " . ($data['error_code'] ?? $data['error'] ?? '') . ' ' . ($data['message'] ?? 'no JSON body') . "\n";Error codes and what to do
Every error is JSON with "success": false. Read error_code first (only some errors have it), then error, then message, and look in errors for details.
| HTTP | error | What you'll see in message / errors | What to do | Retry? |
|---|---|---|---|---|
| 401 | Unauthorized | API key is required · Invalid API key · API key is disabled · API key has expired · Account is not active | Check SMS_API_KEY and that the key is active in API Management. | No |
| 403 | Forbidden | IP address not allowed. Please whitelist your IP address to access the API. | Add this server's IP or CIDR range to the key's IP whitelist, or use a separate key for this server. | No |
| 403 | Forbidden | GET method is not allowed for this API key | Tick "Allow GET Method" for the key. | No |
| 400 | Invalid sender ID | The provided sender ID is not authorized for your account | Use a sender ID that is approved on your account. | No |
| 400 | SMS dispatch failed | errors says why, for example "Insufficient credits. Required: X, Available: Y" or "Template verification failed: …" | Top up, or change the text to match an approved template. | No |
| 422 | Validation failed | Invalid request parameters, with a list per field in errors | Fix the field named — number format, missing sender_id, a DLT ID sent as a number. | No |
| 422 | error_code TEMPLATE_MISMATCH | Template verification failed: … | Make the text match the approved template word for word. | No |
| 404 | Message not found | The specified message ID does not exist or does not belong to your account | Use the message_id from the send reply. | No |
| 429 | Rate limit exceeded | Too many requests, with retry_after and a Retry-After header | Wait that many seconds. Defaults: 60 requests a minute, 10,000 a day per key. | Yes, after the wait |
| 500, 502, 503 | Internal server error | An unexpected error occurred… | Retry with a short back-off. | Yes |
| 504 or timeout | — | No JSON, or no reply at all | Check the message status before sending again. | Check first |
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.
Using Laravel?
In Laravel, use the built-in HTTP client instead of raw cURL. Our Laravel SMS integration guide builds a small SmsClient service on the Http facade with timeouts and retries, a custom notification channel with toSms(), queued notifications that retry and end up in failed_jobs, bulk sends in chunks of 1,000, and tests with Http::fake(). There is no Laravel package to install. We tested the code on Laravel 11, 12 and 13.
WordPress and WooCommerce
There is no WordPress or WooCommerce plugin. You can send order SMS from a small plugin of your own that calls the same API with WordPress's wp_remote_post() when an order changes status. The WooCommerce SMS notifications guide walks through it.
Production checklist
Security
Key in an environment variable, never in Git or browser code. One key per server or integration, with its IPs whitelisted. Replace a key that may have leaked.
Reliability
Send from a queue or cron job so web pages stay fast. Keep timeouts (5 s to connect, 30 s in total). Save every message_id, and check every bulk result.
Compliance
Send only approved templates from an approved header. Promotional SMS only from 9 AM to 9 PM, with opt-out instructions. Respect DND preferences.
Testing
No sandbox: test with your own number. Test the error paths with a wrong key, which sends nothing. Try requests in the API playground.
Prices are the same for API and panel sends: ₹0.20 per SMS on Starter and ₹0.15 on Business, plus GST, billed per delivered message. See pricing. For other languages, see the Node.js and Python guides, or the full API reference.