BestSMS.lk

SMS SDKs for your app

Send bulk SMS and OTP codes to any Sri Lankan mobile from PHP, Node.js, Python, Java or C#. Each SDK is free, has no extra dependencies and covers every endpoint of the BestSMS API.

  • Automatic retries
  • Webhook signature check
  • MIT licence
<?php
require 'vendor/autoload.php';

use BestSMS\Client;

$sms = new Client(getenv('BESTSMS_KEY'));

$res = $sms->send('0771234567', 'Your order #2041 is ready for pickup.', [
    'sender_id'  => 'MYSHOP',
    'client_ref' => 'order-2041',
]);

echo $res['campaign_id'] . ' ' . $res['status'];   // 18342 done

Install

Install from your package manager, or download the zip and add it to your project. The PHP, Python and Node.js SDKs use only what ships with the language. Java needs nothing extra either, and the .NET SDK uses System.Text.Json.

Then create an API key on the API and webhooks page of your dashboard and keep it in an environment variable such as BESTSMS_KEY. Keys start with bsk_live_.

The tabs on this page stay in sync. Pick your language once and every example follows.

# With Composer
composer require bestsms/bestsms-php

# Or unzip bestsms-php.zip and load the client yourself
require __DIR__ . '/bestsms-php/src/Client.php';

Send an SMS

Pass one number or many, the text and your approved sender ID. If you leave out the sender ID we use your default one.

Up to 100 numbers are sent before the call returns, so the result already has each message id and status. Bigger lists are queued and sent in the background.

Returns
campaign_id, status, recipients, credits_reserved, invalid, opted_out, messages
Text
Up to 1,530 characters. Sinhala, Tamil and emoji work.
<?php
require 'vendor/autoload.php';

use BestSMS\Client;

$sms = new Client(getenv('BESTSMS_KEY'));

$res = $sms->send('0771234567', 'Your order #2041 is ready for pickup.', [
    'sender_id'  => 'MYSHOP',
    'client_ref' => 'order-2041',
]);

echo $res['campaign_id'] . ' ' . $res['status'];   // 18342 done

Bulk and personal messages

Send one text to a whole list in a single call instead of calling once per number. One request can hold up to 100,000 numbers.

For personal messages, give each number a name, field1 and field2 and use {name}, {field1} and {field2} in the text. Each recipient can also carry its own client_ref, which comes back in delivery webhooks.

Add a schedule time in Sri Lanka time to send later. You can cancel a scheduled campaign and get every credit back.

// One message to many numbers
$sms->send(['0771234567', '0762289014'], 'Our shop opens at 9 am tomorrow.', ['sender_id' => 'MYSHOP']);

// A personal message for each number
$sms->sendBulk([
    ['phone' => '0771234567', 'name' => 'Nimal',  'field1' => '1,250'],
    ['phone' => '0762289014', 'name' => 'Kamala', 'field1' => '830'],
], 'Hi {name}, you have {field1} points.', ['sender_id' => 'MYSHOP']);

// Send later (Sri Lanka time)
$sms->send('0771234567', 'Reminder: your appointment is at 10:30 am.', [
    'sender_id'   => 'MYSHOP',
    'schedule_at' => '2026-12-24 09:00',
]);

Balance and delivery

Check your credits before a big send, and look up any message by the id from the send result. A message moves from queued to sent, then to delivered or failed when the network reports back.

To hear about deliveries without polling, add a webhook.

$bal = $sms->getBalance();
echo $bal['credits'];         // 9480
echo $bal['price_per_sms'];   // 1.35

// Delivery status of one message from a send response
$msg = $sms->getMessage($res['messages'][0]['id']);
echo $msg['message']['status'];   // queued, sent, delivered, failed or cancelled

OTP codes

We make a random code, text it and keep only a hash of it. Store the otp_id in your session and send it back with what the person typed.

  • Codes are 4 to 8 digits, 6 by default.
  • They stay valid for 60 to 1,800 seconds, 300 by default.
  • A code works once. After 5 wrong tries it locks.
  • Up to 5 codes per number every 10 minutes.
// 1. Text a code
$otp = $sms->sendOtp('0771234567', [
    'sender_id' => 'MYSHOP',
    'length'    => 6,
    'expiry'    => 300,
    'message'   => 'Your MyShop login code is {code}',
]);
$_SESSION['otp_id'] = $otp['otp_id'];

// 2. Check what the person typed
try {
    $sms->verifyOtp($_POST['code'], otpId: $_SESSION['otp_id']);
    // verified: log them in
} catch (BestSMS\BestSMSException $e) {
    if ($e->getErrorCode() === 'otp_invalid') {
        echo 'Wrong code. ' . $e->getAttemptsLeft() . ' tries left.';
    } elseif ($e->getErrorCode() === 'otp_expired') {
        echo 'That code has expired. We sent you a new one.';
    }
}

Handle errors

Every SDK throws one error type with the same three things: a stable code to branch on, a message written for people, and the HTTP status.

CodeHTTPMeaning
unauthorized401, 403The key is missing, wrong or revoked, or the account is suspended.
forbidden_ip403The key has an IP allow-list and the request came from another address.
rate_limited429Too many requests this minute, or too many codes to one number. Retried for you.
invalid_request422A field is missing or not valid. The message says which one.
sender_not_approved422The sender ID is not approved on your account.
insufficient_credits402Not enough credits for this send. Nothing was sent.
not_found404No such message, campaign, giveaway or endpoint on your account.
otp_invalid422, 404Wrong code, already used, or no code was sent to that number.
otp_expired422The code is older than its expiry time.
otp_too_many_attempts429Five wrong tries. Send a new code.
server_error500, 502Something failed on our side. GET requests are retried for you.
network_errornoneAdded by the SDK: no response, for example a timeout or no internet.
use BestSMS\BestSMSException;

try {
    $sms->send($numbers, $text, ['sender_id' => 'MYSHOP']);
} catch (BestSMSException $e) {
    switch ($e->getErrorCode()) {
        case 'insufficient_credits': notifyAdmin('Top up BestSMS'); break;
        case 'sender_not_approved':  /* use another sender ID */ break;
        case 'invalid_request':      log($e->getMessage()); break;
        default: throw $e;
    }
    // also: $e->getHttpStatus(), $e->getBody(), $e->getRetryAfter()
}

Verify a webhook

Add your URL on the API and webhooks page of your dashboard and copy the signing secret. We POST JSON with event, time and data. Reply with any 2xx status within 6 seconds.

The X-BestSMS-Signature header is sha256= followed by the hex HMAC-SHA256 of the raw request body, keyed with your secret. Check it on the raw bytes before you parse the JSON. The helper compares in constant time.

EventWhen
message.deliveredThe network confirms a message reached the phone.
message.failedThe network reports a message could not be delivered.
campaign.finishedEvery number in a campaign was sent or failed.
balance.lowYour credits drop below your alert level.
giveaway.entrySomeone enters one of your giveaways.
webhook.testYou press Send test event in the dashboard.
use BestSMS\Client;

$raw = file_get_contents('php://input');
$sig = $_SERVER['HTTP_X_BESTSMS_SIGNATURE'] ?? '';

if (!Client::verifyWebhookSignature($raw, $sig, getenv('BESTSMS_WEBHOOK_SECRET'))) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw, true);
if ($event['event'] === 'message.delivered') {
    markDelivered($event['data']['client_ref']);
}
http_response_code(200);

Method reference

Every SDK has the same methods, named the way your language likes. Each call returns the JSON from the API: arrays in PHP, objects in Node.js, dicts in Python, a JsonObject in Java and typed classes in C#. Optional parameters end in a question mark.

MethodEndpointParametersReturns
ping()API name and version. Needs no key. GET / none name, version
getBalance()Credits left and your price per SMS. GET /balance none credits, price_per_sms, currency
send($to, $message, $options)One message to one number or a list. POST /sms/send to, message; options: sender_id, schedule_at, name, client_ref campaign_id, status, recipients, credits_reserved, invalid, opted_out, messages, scheduled_at
sendBulk($recipients, $message, $options)A list of numbers, or a personal message per number with {name}, {field1}, {field2}. POST /sms/send recipients, message; options: sender_id, schedule_at, name, client_ref same as send
sendViaLink($to, $message, $senderId)The simple link endpoint, called with your key in the header. GET /send to, message, senderId? same as send
buildSimpleLink($to, $message, $senderId)Builds the link for POS systems. No request is made. GET /send link to, message, senderId? URL string
getMessage($id)Status of one message. GET /sms/{id} id message: id, status, segments, encoding, error, client_ref, sent_at, delivered_at
listCampaigns($page = 1)Your campaigns, newest first, 50 per page. GET /campaigns page? campaigns, page, pages
getCampaign($id)One campaign with its counters. GET /campaigns/{id} id campaign
cancelCampaign($id)Stops a scheduled or sending campaign and refunds unsent credits. POST /campaigns/{id}/cancel id refunded
listSenderIds()Your sender IDs and their status. GET /sender-ids none sender_ids
requestSenderId($senderId, $businessName, $purpose, $sampleMessage)Asks us to approve a new sender ID. POST /sender-ids senderId, businessName, purpose, sampleMessage? id, sender_id, status
sendOtp($to, $options)Texts a one-time code and keeps only its hash. POST /otp/send to; options: sender_id, length, expiry, message otp_id, message_id, expires_at
verifyOtp($code, $to, $otpId)Checks a code by phone number or otp_id. POST /otp/verify code, to?, otpId? (to or otpId) verified, phone
listGroups()Contact groups with a count of contacts in each. GET /groups none groups
addContact($phone, $options)Adds or updates a contact. A group name you pass is created if missing. POST /contacts phone; options: group_id, group, name, field1, field2 contact_id, group_id
addOptOut($phone, $reason)Adds a number to your opt-out list. OTP still goes through. POST /optouts phone, reason? ok
listGiveaways()Your giveaways with their public link and entry count. GET /giveaways none giveaways: slug, title, type, status, entries, link
listGiveawayEntries($slug, $page = 1)Entries for one giveaway, oldest first, 100 per page. GET /giveaways/{slug}/entries slug, page? entries (name, phone, verified, referrals, bonus_entries, entries, answers), page, pages, total
Client::verifyWebhookSignature($raw, $header, $secret)Checks the X-BestSMS-Signature header with a constant-time compare. Webhook helper rawBody, header, secret true or false

Rate limits and retries

Each API key can make 120 requests a minute unless we have raised it for you. Every response carries X-RateLimit-Limit and X-RateLimit-Remaining, and the SDKs keep the latest values for you.

When a request is refused with 429 rate_limited, the SDK waits and tries again, up to 3 times. It waits for the Retry-After header when we send one, and otherwise backs off for about half a second, then 1 and 2 seconds.

Server errors and timeouts are retried only for GET requests. A send, OTP or cancel call is never repeated after a server error, so one call can never text a customer twice.

You can change the base URL, the timeout and the number of retries when you create the client.

$sms = new BestSMS\Client($key, [
    'base_url'    => 'https://bestsms.lk/api/v1',
    'timeout'     => 30,   // seconds
    'max_retries' => 3,
]);
print_r($sms->getRateLimit());   // ['limit' => 120, 'remaining' => 119]

Downloads

Each zip has the source, a README with every method, runnable examples and the MIT licence.

Postman and OpenAPI

Try every endpoint without writing code, or generate a client for a language we do not cover yet.

Questions

Do the SDKs cost anything?

No. They are free and open source under the MIT licence. You only pay for the SMS credits you use.

Can I put my API key inside a mobile app or website?

No. Anyone can read a key from an app or a web page and send SMS from your balance. Keep the key on your server, let your app call your server, and use an IP allow-list on the key for extra safety.

Will a retry ever send the same SMS twice?

No. Requests that send or change something are only retried when we answer 429 rate_limited, which means nothing was done yet. Server errors and timeouts are retried for read-only GET requests only.

Which phone number formats work?

Any Sri Lankan mobile number: 0771234567, 771234567, +94771234567 or 94771234567. Numbers are cleaned to 947XXXXXXXX and duplicates in one request are sent once.

How do I test without spending credits?

Send to your own number first: one SMS part costs one credit. Failed numbers are refunded when the campaign finishes, and scheduled campaigns can be cancelled for a full refund.

My language is not listed. Can I still use the API?

Yes. The API is plain JSON over HTTPS, so any language works. Import the OpenAPI file into a code generator, or follow the API reference with cURL samples.

Ready to send your first SMS?

Create an account, request a sender ID and make an API key. Every message your code sends shows up in your dashboard under Delivery reports.

Create free account Read the API reference