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 doneconst BestSMS = require('bestsms');
// ESM or TypeScript: import BestSMS from 'bestsms';
const sms = new BestSMS(process.env.BESTSMS_KEY);
const res = await sms.send('0771234567', 'Your order #2041 is ready for pickup.', {
senderId: 'MYSHOP',
clientRef: 'order-2041',
});
console.log(res.campaign_id, res.status); // 18342 'done'import os
from bestsms import BestSMS
sms = BestSMS(os.environ["BESTSMS_KEY"])
res = sms.send("0771234567", "Your order #2041 is ready for pickup.",
sender_id="MYSHOP", client_ref="order-2041")
print(res["campaign_id"], res["status"]) # 18342 doneimport lk.bestsms.BestSMS;
import lk.bestsms.BestSMS.JsonObject;
BestSMS sms = new BestSMS(System.getenv("BESTSMS_KEY"));
JsonObject res = sms.send("0771234567", "Your order #2041 is ready for pickup.",
new BestSMS.SendOptions().senderId("MYSHOP").clientRef("order-2041"));
System.out.println(res.getLong("campaign_id") + " " + res.getString("status"));using BestSms;
using var sms = new BestSmsClient(Environment.GetEnvironmentVariable("BESTSMS_KEY"));
var res = await sms.SendAsync("0771234567", "Your order #2041 is ready for pickup.",
new SendOptions { SenderId = "MYSHOP", ClientRef = "order-2041" });
Console.WriteLine($"{res.CampaignId} {res.Status}"); // 18342 donePick your language
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';# Node.js 18 or newer
npm install bestsms
# Or unzip bestsms-node.zip and install the folder
npm install ./bestsms-node# Python 3.8 or newer
pip install bestsms
# Or unzip bestsms-python.zip and install the folder
pip install ./bestsms-python# Java 8+ and Android (minSdk 21). One file, no dependencies.
# Unzip bestsms-java.zip and copy this file into your project:
src/main/java/lk/bestsms/BestSMS.java
# Or build a jar
cd bestsms-java && mvn package# .NET 6+ or .NET Framework 4.6.1+ (netstandard2.0)
# Unzip bestsms-dotnet.zip, then reference the project
dotnet add reference ./bestsms-dotnet/BestSms.csproj
# or copy BestSms.cs into your projectSend 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 doneconst BestSMS = require('bestsms');
// ESM or TypeScript: import BestSMS from 'bestsms';
const sms = new BestSMS(process.env.BESTSMS_KEY);
const res = await sms.send('0771234567', 'Your order #2041 is ready for pickup.', {
senderId: 'MYSHOP',
clientRef: 'order-2041',
});
console.log(res.campaign_id, res.status); // 18342 'done'import os
from bestsms import BestSMS
sms = BestSMS(os.environ["BESTSMS_KEY"])
res = sms.send("0771234567", "Your order #2041 is ready for pickup.",
sender_id="MYSHOP", client_ref="order-2041")
print(res["campaign_id"], res["status"]) # 18342 doneimport lk.bestsms.BestSMS;
import lk.bestsms.BestSMS.JsonObject;
BestSMS sms = new BestSMS(System.getenv("BESTSMS_KEY"));
JsonObject res = sms.send("0771234567", "Your order #2041 is ready for pickup.",
new BestSMS.SendOptions().senderId("MYSHOP").clientRef("order-2041"));
System.out.println(res.getLong("campaign_id") + " " + res.getString("status"));using BestSms;
using var sms = new BestSmsClient(Environment.GetEnvironmentVariable("BESTSMS_KEY"));
var res = await sms.SendAsync("0771234567", "Your order #2041 is ready for pickup.",
new SendOptions { SenderId = "MYSHOP", ClientRef = "order-2041" });
Console.WriteLine($"{res.CampaignId} {res.Status}"); // 18342 doneBulk 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',
]);// One message to many numbers
await sms.send(['0771234567', '0762289014'], 'Our shop opens at 9 am tomorrow.', { senderId: 'MYSHOP' });
// A personal message for each number
await sms.sendBulk([
{ phone: '0771234567', name: 'Nimal', field1: '1,250' },
{ phone: '0762289014', name: 'Kamala', field1: '830' },
], 'Hi {name}, you have {field1} points.', { senderId: 'MYSHOP' });
// Send later (Sri Lanka time)
await sms.send('0771234567', 'Reminder: your appointment is at 10:30 am.', {
senderId: 'MYSHOP',
scheduleAt: '2026-12-24 09:00',
});# 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.send_bulk([
{"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")BestSMS.SendOptions opts = new BestSMS.SendOptions().senderId("MYSHOP");
// One message to many numbers
sms.sendBulk(Arrays.asList("0771234567", "0762289014"), "Our shop opens at 9 am tomorrow.", opts);
// A personal message for each number
sms.sendPersonalized(Arrays.asList(
new BestSMS.Recipient("0771234567").name("Nimal").field1("1,250"),
new BestSMS.Recipient("0762289014").name("Kamala").field1("830")),
"Hi {name}, you have {field1} points.", opts);
// Send later (Sri Lanka time)
sms.send("0771234567", "Reminder: your appointment is at 10:30 am.",
new BestSMS.SendOptions().senderId("MYSHOP").scheduleAt("2026-12-24 09:00"));var opts = new SendOptions { SenderId = "MYSHOP" };
// One message to many numbers
await sms.SendBulkAsync(new[] { "0771234567", "0762289014" }, "Our shop opens at 9 am tomorrow.", opts);
// A personal message for each number
await sms.SendPersonalizedAsync(new[]
{
new Recipient("0771234567") { Name = "Nimal", Field1 = "1,250" },
new Recipient("0762289014") { Name = "Kamala", Field1 = "830" },
}, "Hi {name}, you have {field1} points.", opts);
// Send later (Sri Lanka time)
await sms.SendAsync("0771234567", "Reminder: your appointment is at 10:30 am.",
new SendOptions { SenderId = "MYSHOP", ScheduleAt = "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 cancelledconst { credits, price_per_sms } = await sms.getBalance();
console.log(credits, price_per_sms); // 9480 1.35
// Delivery status of one message from a send response
const { message } = await sms.getMessage(res.messages[0].id);
console.log(message.status); // queued, sent, delivered, failed or cancelledbal = sms.get_balance()
print(bal["credits"], bal["price_per_sms"]) # 9480 1.35
# Delivery status of one message from a send response
msg = sms.get_message(res["messages"][0]["id"])
print(msg["message"]["status"]) # queued, sent, delivered, failed or cancelledJsonObject bal = sms.getBalance();
double credits = bal.getDouble("credits"); // 9480.0
double price = bal.getDouble("price_per_sms"); // 1.35
// Delivery status of one message from a send response
long id = res.getArray("messages").getObject(0).getLong("id");
String status = sms.getMessage(id).getObject("message").getString("status");var bal = await sms.GetBalanceAsync();
Console.WriteLine($"{bal.Credits} credits at Rs {bal.PricePerSms}");
// Delivery status of one message from a send response
var msg = await sms.GetMessageAsync(res.Messages![0].Id);
Console.WriteLine(msg.Message.Status); // queued, sent, delivered, failed or cancelledOTP 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.';
}
}// 1. Text a code
const otp = await sms.sendOtp('0771234567', {
senderId: 'MYSHOP',
length: 6,
expiry: 300,
message: 'Your MyShop login code is {code}',
});
req.session.otpId = otp.otp_id;
// 2. Check what the person typed
try {
await sms.verifyOtp({ otpId: req.session.otpId, code: req.body.code });
// verified: log them in
} catch (e) {
if (e.code === 'otp_invalid') console.log(`Wrong code. ${e.attemptsLeft} tries left.`);
else if (e.code === 'otp_expired') console.log('That code has expired.');
else throw e;
}from bestsms import BestSMSError
# 1. Text a code
otp = sms.send_otp("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.verify_otp(request.form["code"], otp_id=session["otp_id"])
# verified: log them in
except BestSMSError as e:
if e.code == "otp_invalid":
print(f"Wrong code. {e.attempts_left} tries left.")
elif e.code == "otp_expired":
print("That code has expired.")
else:
raise// 1. Text a code
JsonObject otp = sms.sendOtp("0771234567", new BestSMS.OtpOptions()
.senderId("MYSHOP").length(6).expiry(300)
.message("Your MyShop login code is {code}"));
long otpId = otp.getLong("otp_id");
// 2. Check what the person typed
try {
sms.verifyOtpById(otpId, typedCode);
// verified: log them in
} catch (BestSMS.BestSMSException e) {
if ("otp_invalid".equals(e.getCode())) {
System.out.println("Wrong code. " + e.getAttemptsLeft() + " tries left.");
} else if ("otp_expired".equals(e.getCode())) {
System.out.println("That code has expired.");
}
}// 1. Text a code
var otp = await sms.SendOtpAsync("0771234567", new OtpOptions
{
SenderId = "MYSHOP", Length = 6, Expiry = 300,
Message = "Your MyShop login code is {code}",
});
// 2. Check what the person typed
try
{
await sms.VerifyOtpAsync(typedCode, otpId: otp.OtpId);
// verified: log them in
}
catch (BestSmsException e) when (e.Code == "otp_invalid")
{
Console.WriteLine($"Wrong code. {e.AttemptsLeft} tries left.");
}
catch (BestSmsException e) when (e.Code == "otp_expired")
{
Console.WriteLine("That code has expired.");
}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.
| Code | HTTP | Meaning |
|---|---|---|
unauthorized | 401, 403 | The key is missing, wrong or revoked, or the account is suspended. |
forbidden_ip | 403 | The key has an IP allow-list and the request came from another address. |
rate_limited | 429 | Too many requests this minute, or too many codes to one number. Retried for you. |
invalid_request | 422 | A field is missing or not valid. The message says which one. |
sender_not_approved | 422 | The sender ID is not approved on your account. |
insufficient_credits | 402 | Not enough credits for this send. Nothing was sent. |
not_found | 404 | No such message, campaign, giveaway or endpoint on your account. |
otp_invalid | 422, 404 | Wrong code, already used, or no code was sent to that number. |
otp_expired | 422 | The code is older than its expiry time. |
otp_too_many_attempts | 429 | Five wrong tries. Send a new code. |
server_error | 500, 502 | Something failed on our side. GET requests are retried for you. |
network_error | none | Added 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()
}const { BestSMSError } = require('bestsms');
try {
await sms.send(numbers, text, { senderId: 'MYSHOP' });
} catch (e) {
if (!(e instanceof BestSMSError)) throw e;
switch (e.code) {
case 'insufficient_credits': notifyAdmin('Top up BestSMS'); break;
case 'sender_not_approved': /* use another sender ID */ break;
case 'invalid_request': console.warn(e.message); break;
default: throw e;
}
// also: e.status, e.body, e.retryAfter
}from bestsms import BestSMSError
try:
sms.send(numbers, text, sender_id="MYSHOP")
except BestSMSError as e:
if e.code == "insufficient_credits":
notify_admin("Top up BestSMS")
elif e.code == "sender_not_approved":
pass # use another sender ID
elif e.code == "invalid_request":
log.warning(e.message)
else:
raise
# also: e.status, e.body, e.retry_aftertry {
sms.send(numbers, text, new BestSMS.SendOptions().senderId("MYSHOP"));
} catch (BestSMS.BestSMSException e) {
switch (e.getCode()) {
case "insufficient_credits": notifyAdmin("Top up BestSMS"); break;
case "sender_not_approved": /* use another sender ID */ break;
case "invalid_request": log.warn(e.getMessage()); break;
default: throw e;
}
// also: e.getHttpStatus(), e.getBody(), e.getRetryAfter()
}try
{
await sms.SendAsync(numbers, text, new SendOptions { SenderId = "MYSHOP" });
}
catch (BestSmsException e) when (e.Code == "insufficient_credits")
{
NotifyAdmin("Top up BestSMS");
}
catch (BestSmsException e) when (e.Code == "invalid_request")
{
logger.LogWarning(e.Message);
}
// also: e.HttpStatus, e.Body, e.RetryAfterVerify 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.
| Event | When |
|---|---|
message.delivered | The network confirms a message reached the phone. |
message.failed | The network reports a message could not be delivered. |
campaign.finished | Every number in a campaign was sent or failed. |
balance.low | Your credits drop below your alert level. |
giveaway.entry | Someone enters one of your giveaways. |
webhook.test | You 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);const express = require('express');
const BestSMS = require('bestsms');
const app = express();
// keep the raw bytes: the signature is over the exact body we send
app.post('/bestsms', express.raw({ type: 'application/json' }), (req, res) => {
const sig = req.get('X-BestSMS-Signature');
if (!BestSMS.verifyWebhookSignature(req.body, sig, process.env.BESTSMS_WEBHOOK_SECRET)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body);
if (event.event === 'message.delivered') markDelivered(event.data.client_ref);
res.sendStatus(200);
});from flask import Flask, abort, request
from bestsms import verify_webhook_signature
app = Flask(__name__)
@app.post("/bestsms")
def bestsms_webhook():
raw = request.get_data() # raw bytes, before parsing
sig = request.headers.get("X-BestSMS-Signature")
if not verify_webhook_signature(raw, sig, os.environ["BESTSMS_WEBHOOK_SECRET"]):
abort(401)
event = request.get_json()
if event["event"] == "message.delivered":
mark_delivered(event["data"]["client_ref"])
return "", 200// Servlet, Spring or any framework: read the raw body bytes first
byte[] raw = request.getInputStream().readAllBytes();
String sig = request.getHeader("X-BestSMS-Signature");
if (!BestSMS.verifyWebhookSignature(raw, sig, System.getenv("BESTSMS_WEBHOOK_SECRET"))) {
response.setStatus(401);
return;
}
JsonObject event = (JsonObject) BestSMS.Json.parse(new String(raw, StandardCharsets.UTF_8));
if ("message.delivered".equals(event.getString("event"))) {
markDelivered(event.getObject("data").getString("client_ref"));
}
response.setStatus(200);app.MapPost("/bestsms", async (HttpRequest req) =>
{
using var ms = new MemoryStream();
await req.Body.CopyToAsync(ms);
var raw = ms.ToArray(); // the exact bytes received
var secret = Environment.GetEnvironmentVariable("BESTSMS_WEBHOOK_SECRET")!;
if (!BestSmsClient.VerifyWebhookSignature(raw, req.Headers["X-BestSMS-Signature"], secret))
return Results.Unauthorized();
var evt = JsonDocument.Parse(raw).RootElement;
if (evt.GetProperty("event").GetString() == "message.delivered") { /* update your records */ }
return Results.Ok();
});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.
| Method | Endpoint | Parameters | Returns |
|---|---|---|---|
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 |
| Method | Endpoint | Parameters | Returns |
|---|---|---|---|
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: senderId, scheduleAt, name, clientRef | 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: senderId, scheduleAt, name, clientRef | 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: senderId, 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: groupId, 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 |
BestSMS.verifyWebhookSignature(raw, header, secret)Checks the X-BestSMS-Signature header with a constant-time compare. |
Webhook helper | rawBody, header, secret | true or false |
| Method | Endpoint | Parameters | Returns |
|---|---|---|---|
ping()API name and version. Needs no key. |
GET / |
none | name, version |
get_balance()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 |
send_bulk(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 |
send_via_link(to, message, sender_id)The simple link endpoint, called with your key in the header. |
GET /send |
to, message, sender_id? | same as send |
build_simple_link(to, message, sender_id)Builds the link for POS systems. No request is made. |
GET /send link | to, message, sender_id? | URL string |
get_message(id)Status of one message. |
GET /sms/{id} |
id | message: id, status, segments, encoding, error, client_ref, sent_at, delivered_at |
list_campaigns(page=1)Your campaigns, newest first, 50 per page. |
GET /campaigns |
page? | campaigns, page, pages |
get_campaign(id)One campaign with its counters. |
GET /campaigns/{id} |
id | campaign |
cancel_campaign(id)Stops a scheduled or sending campaign and refunds unsent credits. |
POST /campaigns/{id}/cancel |
id | refunded |
list_sender_ids()Your sender IDs and their status. |
GET /sender-ids |
none | sender_ids |
request_sender_id(sender_id, business_name, purpose, sample_message)Asks us to approve a new sender ID. |
POST /sender-ids |
sender_id, business_name, purpose, sample_message? | id, sender_id, status |
send_otp(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 |
verify_otp(code, to=None, otp_id=None)Checks a code by phone number or otp_id. |
POST /otp/verify |
code, to?, otp_id? (to or otpId) | verified, phone |
list_groups()Contact groups with a count of contacts in each. |
GET /groups |
none | groups |
add_contact(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 |
add_opt_out(phone, reason)Adds a number to your opt-out list. OTP still goes through. |
POST /optouts |
phone, reason? | ok |
list_giveaways()Your giveaways with their public link and entry count. |
GET /giveaways |
none | giveaways: slug, title, type, status, entries, link |
list_giveaway_entries(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 |
verify_webhook_signature(raw, header, secret)Checks the X-BestSMS-Signature header with a constant-time compare. |
Webhook helper | raw_body, header, secret | true or false |
| Method | Endpoint | Parameters | Returns |
|---|---|---|---|
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, SendOptions)One message to one number or a list. |
POST /sms/send |
to, message; options: senderId, scheduleAt, name, clientRef | campaign_id, status, recipients, credits_reserved, invalid, opted_out, messages, scheduled_at |
sendBulk(numbers, message, SendOptions)sendPersonalized(recipients, message, SendOptions)A list of numbers, or a personal message per number with {name}, {field1}, {field2}. |
POST /sms/send |
recipients, message; options: senderId, scheduleAt, name, clientRef | 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)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, OtpOptions)Texts a one-time code and keeps only its hash. |
POST /otp/send |
to; options: senderId, length, expiry, message | otp_id, message_id, expires_at |
verifyOtp(to, code)verifyOtpById(otpId, code)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, ContactOptions)Adds or updates a contact. A group name you pass is created if missing. |
POST /contacts |
phone; options: groupId, 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)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 |
BestSMS.verifyWebhookSignature(raw, header, secret)Checks the X-BestSMS-Signature header with a constant-time compare. |
Webhook helper | rawBody, header, secret | true or false |
| Method | Endpoint | Parameters | Returns |
|---|---|---|---|
PingAsync()API name and version. Needs no key. |
GET / |
none | PingResult |
GetBalanceAsync()Credits left and your price per SMS. |
GET /balance |
none | BalanceResult |
SendAsync(to, message, SendOptions)One message to one number or a list. |
POST /sms/send |
to, message; options: SenderId, ScheduleAt, Name, ClientRef | SendResult |
SendBulkAsync(numbers, message, SendOptions)SendPersonalizedAsync(recipients, message, SendOptions)A list of numbers, or a personal message per number with {name}, {field1}, {field2}. |
POST /sms/send |
recipients, message; options: SenderId, ScheduleAt, Name, ClientRef | SendResult |
SendViaLinkAsync(to, message, senderId)The simple link endpoint, called with your key in the header. |
GET /send |
to, message, senderId? | SendResult |
BuildSimpleLink(to, message, senderId)Builds the link for POS systems. No request is made. |
GET /send link | to, message, senderId? | string |
GetMessageAsync(id)Status of one message. |
GET /sms/{id} |
id | MessageResult |
ListCampaignsAsync(page = 1)Your campaigns, newest first, 50 per page. |
GET /campaigns |
page? | CampaignListResult |
GetCampaignAsync(id)One campaign with its counters. |
GET /campaigns/{id} |
id | CampaignResult |
CancelCampaignAsync(id)Stops a scheduled or sending campaign and refunds unsent credits. |
POST /campaigns/{id}/cancel |
id | CancelResult |
ListSenderIdsAsync()Your sender IDs and their status. |
GET /sender-ids |
none | SenderIdListResult |
RequestSenderIdAsync(senderId, businessName, purpose, sampleMessage)Asks us to approve a new sender ID. |
POST /sender-ids |
senderId, businessName, purpose, sampleMessage? | SenderIdRequestResult |
SendOtpAsync(to, OtpOptions)Texts a one-time code and keeps only its hash. |
POST /otp/send |
to; options: SenderId, Length, Expiry, Message | OtpSendResult |
VerifyOtpAsync(code, to, otpId)Checks a code by phone number or otp_id. |
POST /otp/verify |
code, to?, otpId? (to or otpId) | OtpVerifyResult |
ListGroupsAsync()Contact groups with a count of contacts in each. |
GET /groups |
none | GroupListResult |
AddContactAsync(phone, ContactOptions)Adds or updates a contact. A group name you pass is created if missing. |
POST /contacts |
phone; options: GroupId, Group, Name, Field1, Field2 | ContactResult |
AddOptOutAsync(phone, reason)Adds a number to your opt-out list. OTP still goes through. |
POST /optouts |
phone, reason? | OkResult |
ListGiveawaysAsync()Your giveaways with their public link and entry count. |
GET /giveaways |
none | GiveawayListResult |
ListGiveawayEntriesAsync(slug, page = 1)Entries for one giveaway, oldest first, 100 per page. |
GET /giveaways/{slug}/entries |
slug, page? | GiveawayEntriesResult |
BestSmsClient.VerifyWebhookSignature(raw, header, secret)Checks the X-BestSMS-Signature header with a constant-time compare. |
Webhook helper | rawBody, header, secret | bool |
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]const sms = new BestSMS(key, {
baseUrl: 'https://bestsms.lk/api/v1',
timeout: 30000, // milliseconds
maxRetries: 3,
});
console.log(sms.rateLimit); // { limit: 120, remaining: 119 }sms = BestSMS(key,
base_url="https://bestsms.lk/api/v1",
timeout=30, # seconds
max_retries=3)
print(sms.rate_limit) # {'limit': 120, 'remaining': 119}BestSMS sms = new BestSMS(key, "https://bestsms.lk/api/v1",
30000, // timeout in milliseconds
3); // max retries
Integer remaining = sms.getRateLimitRemaining();var sms = new BestSmsClient(new BestSmsOptions
{
ApiKey = key,
BaseUrl = "https://bestsms.lk/api/v1",
Timeout = TimeSpan.FromSeconds(30),
MaxRetries = 3,
});
int? remaining = sms.RateLimitRemaining;Simple link for POS systems
Some billing machines and POS systems can only open a web address. For them there is a plain GET link with the key, number, sender ID and text in the URL. It gives the same answer as a normal send.
The SDKs build this link for you with the text safely encoded. Because the key is inside the link, use it only on machines you trust, and prefer the normal send call anywhere else.
https://bestsms.lk/api/v1/send?api_key=bsk_live_xxxx&to=0771234567&sender_id=MYSHOP&message=Your%20bill%20is%20Rs%202%2C450.%20Thank%20you!$url = $sms->buildSimpleLink('0771234567', 'Your bill is Rs 2,450. Thank you!', 'MYSHOP');
// https://bestsms.lk/api/v1/send?api_key=bsk_live_...&to=0771234567&sender_id=MYSHOP&message=Your%20bill...const url = sms.buildSimpleLink('0771234567', 'Your bill is Rs 2,450. Thank you!', 'MYSHOP');
// https://bestsms.lk/api/v1/send?api_key=bsk_live_...&to=0771234567&sender_id=MYSHOP&message=Your%20bill...url = sms.build_simple_link("0771234567", "Your bill is Rs 2,450. Thank you!", "MYSHOP")
# https://bestsms.lk/api/v1/send?api_key=bsk_live_...&to=0771234567&sender_id=MYSHOP&message=Your%20bill...String url = sms.buildSimpleLink("0771234567", "Your bill is Rs 2,450. Thank you!", "MYSHOP");
// https://bestsms.lk/api/v1/send?api_key=bsk_live_...&to=0771234567&sender_id=MYSHOP&message=Your%20bill...var url = sms.BuildSimpleLink("0771234567", "Your bill is Rs 2,450. Thank you!", "MYSHOP");
// https://bestsms.lk/api/v1/send?api_key=bsk_live_...&to=0771234567&sender_id=MYSHOP&message=Your%20bill...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.
BestSMS.postman_collection.json
OpenAPI 3.0Every path, field and error. Works with Swagger UI, Insomnia and code generators such as openapi-generator.
openapi.json
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.