Adding SMS to a website or app is one of the quickest wins in software: order confirmations, OTP codes, payment reminders and alerts all become automatic. This guide walks through integrating an SMS API from start to finish, using the SageSMS SMS API as the example, with working code in 15 languages and frameworks — from PHP, Node.js and Python to Java, C#, Go, Android and Flutter.
1. What you need before you start
- An SMS gateway account. Your messages are charged from a prepaid balance, so make sure the account has credit.
- An approved Sender ID. This is the name your recipients see instead of a number. For alerts and OTPs you need a Transactional Sender ID; for marketing, a Promotional one. See how Sender ID registration works.
- API credentials. In the SageSMS dashboard, open Settings → Integrations to find your
user_idandapi_key.
Treat the API key like a password. Store it in an environment variable or secrets manager, never in front-end JavaScript or a public Git repository. If it leaks, generate a new key from the same Integrations page and update your application.
2. Understand the endpoints
The SageSMS API has three endpoints. All of them accept a standard form-encoded HTTP POST and return JSON.
| Endpoint | Use it for | Notes |
|---|---|---|
/api/sms/send | Transactional SMS — OTPs, alerts, order updates | Requires a Transactional Sender ID. Works 24/7. |
/api/sms/sendpromo | Promotional SMS — offers and campaigns | Requires a Promotional Sender ID. Accepted 8:00 AM–8:00 PM Sri Lanka time. |
/api/sms/balance | Checking balance and account status | Only needs api_key and user_id. |
The base URL is https://api.sagesms.com. The two send endpoints take the same five parameters:
api_keyanduser_id— your credentialssender_id— an approved Sender ID on your account, e.g.YOURBRANDto— the recipient’s mobile number, e.g.0771234567message— the text, in English, Sinhala or Tamil (send it as UTF-8)
Each request sends to one number. To reach a list, loop over your recipients in your code — or for one-off campaigns, use bulk SMS from the dashboard, which handles contact groups and scheduling for you.
3. Send your first SMS
Pick an endpoint and your language. Every example makes the same form-encoded POST, sets a timeout, checks status and prints the serverRef (or your balance) — or the error message.
Any terminal — handy for a quick test.
curl -X POST https://api.sagesms.com/api/sms/send \
-H "Accept: application/json" \
--data-urlencode "api_key=YOUR_API_KEY" \
--data-urlencode "user_id=YOUR_USER_ID" \
--data-urlencode "sender_id=YOUR_SENDER_ID" \
--data-urlencode "to=0771234567" \
--data-urlencode "message=Your order #1024 has been shipped."PHP 7.4+ with the cURL extension.
<?php
// Tip: in production, load the API key from an environment variable or secrets manager.
$ch = curl_init('https://api.sagesms.com/api/sms/send');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
CURLOPT_TIMEOUT => 15,
CURLOPT_POSTFIELDS => http_build_query([
'api_key' => 'YOUR_API_KEY',
'user_id' => 'YOUR_USER_ID',
'sender_id' => 'YOUR_SENDER_ID',
'to' => '0771234567',
'message' => 'Your order #1024 has been shipped.',
]),
]);
$body = curl_exec($ch);
if ($body === false) {
error_log('SageSMS cURL error: ' . curl_error($ch));
}
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode((string) $body, true);
if ($http === 200 && ($result['status'] ?? '') === 'success') {
$serverRef = $result['serverRef']; // store with your own record
} else {
error_log("SageSMS error ($http): " . ($result['message'] ?? 'unknown'));
}Laravel 8+ HTTP client.
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
// Tip: in production, load the API key from an environment variable or secrets manager.
$response = Http::asForm()
->acceptJson()
->timeout(15)
->post('https://api.sagesms.com/api/sms/send', [
'api_key' => 'YOUR_API_KEY',
'user_id' => 'YOUR_USER_ID',
'sender_id' => 'YOUR_SENDER_ID',
'to' => '0771234567',
'message' => 'Your order #1024 has been shipped.',
]);
if ($response->successful() && $response->json('status') === 'success') {
$serverRef = $response->json('serverRef');
} else {
Log::error('SageSMS error', [
'http' => $response->status(),
'message' => $response->json('message'),
]);
}Any plugin or theme — uses the WordPress HTTP API. (For WooCommerce, use the plugin above.)
<?php
// Tip: in production, load the API key from an environment variable or secrets manager.
$response = wp_remote_post('https://api.sagesms.com/api/sms/send', [
'timeout' => 15,
'headers' => ['Accept' => 'application/json'],
'body' => [
'api_key' => 'YOUR_API_KEY',
'user_id' => 'YOUR_USER_ID',
'sender_id' => 'YOUR_SENDER_ID',
'to' => '0771234567',
'message' => 'Your order #1024 has been shipped.',
],
]);
if (is_wp_error($response)) {
error_log('SageSMS: ' . $response->get_error_message());
} else {
$http = wp_remote_retrieve_response_code($response);
$result = json_decode(wp_remote_retrieve_body($response), true);
if ($http === 200 && ($result['status'] ?? '') === 'success') {
$server_ref = $result['serverRef'];
} else {
error_log("SageSMS error ($http): " . ($result['message'] ?? 'unknown'));
}
}Node.js 18+ — no packages needed.
// Node.js 18+ (built-in fetch) — run on your server, never in a browser.
// Tip: in production, load the API key from an environment variable or secrets manager.
const res = await fetch("https://api.sagesms.com/api/sms/send", {
method: "POST",
headers: { Accept: "application/json" },
body: new URLSearchParams({
api_key: "YOUR_API_KEY",
user_id: "YOUR_USER_ID",
sender_id: "YOUR_SENDER_ID",
to: "0771234567",
message: "Your order #1024 has been shipped.",
}),
signal: AbortSignal.timeout(15000),
});
const data = await res.json();
if (!res.ok || data.status !== "success") {
throw new Error(`SageSMS error (${res.status}): ${data.message}`);
}
console.log("Sent, serverRef:", data.serverRef);Python 3.8+ with requests.
# pip install requests
# Tip: in production, load the API key from an environment variable or secrets manager.
import requests
res = requests.post(
"https://api.sagesms.com/api/sms/send",
headers={"Accept": "application/json"},
data={
"api_key": "YOUR_API_KEY",
"user_id": "YOUR_USER_ID",
"sender_id": "YOUR_SENDER_ID",
"to": "0771234567",
"message": "Your order #1024 has been shipped.",
},
timeout=15,
)
data = res.json()
if res.status_code != 200 or data.get("status") != "success":
raise RuntimeError(f"SageSMS error ({res.status_code}): {data.get('message')}")
print("Sent, serverRef:", data["serverRef"])Java 11+ — no extra libraries needed.
// Java 11+ (built-in HttpClient)
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class SageSms {
public static void main(String[] args) throws Exception {
// Tip: in production, load the API key from an environment variable or secrets manager.
Map<String, String> params = new LinkedHashMap<>();
params.put("api_key", "YOUR_API_KEY");
params.put("user_id", "YOUR_USER_ID");
params.put("sender_id", "YOUR_SENDER_ID");
params.put("to", "0771234567");
params.put("message", "Your order #1024 has been shipped.");
String form = params.entrySet().stream()
.map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "="
+ URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.sagesms.com/api/sms/send"))
.header("Accept", "application/json")
.header("Content-Type", "application/x-www-form-urlencoded")
.timeout(Duration.ofSeconds(15))
.POST(HttpRequest.BodyPublishers.ofString(form))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
// Parse the JSON with Jackson or Gson and check "status" == "success".
System.out.println(response.statusCode() + " " + response.body());
}
}.NET 6+ — HttpClient and System.Text.Json.
// .NET 6+ (top-level program)
using System.Net.Http.Headers;
using System.Text.Json;
// Tip: in production, load the API key from an environment variable or secrets manager.
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var form = new FormUrlEncodedContent(new Dictionary<string, string>
{
["api_key"] = "YOUR_API_KEY",
["user_id"] = "YOUR_USER_ID",
["sender_id"] = "YOUR_SENDER_ID",
["to"] = "0771234567",
["message"] = "Your order #1024 has been shipped.",
});
var response = await http.PostAsync("https://api.sagesms.com/api/sms/send", form);
var body = await response.Content.ReadAsStringAsync();
using var json = JsonDocument.Parse(body);
var root = json.RootElement;
if (response.IsSuccessStatusCode && root.GetProperty("status").GetString() == "success")
{
Console.WriteLine($"Sent, serverRef: {root.GetProperty("serverRef")}");
}
else
{
Console.WriteLine($"SageSMS error ({(int)response.StatusCode}): {body}");
}Go 1.18+ standard library.
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
)
func main() {
// Tip: in production, load the API key from an environment variable or secrets manager.
form := url.Values{}
form.Set("api_key", "YOUR_API_KEY")
form.Set("user_id", "YOUR_USER_ID")
form.Set("sender_id", "YOUR_SENDER_ID")
form.Set("to", "0771234567")
form.Set("message", "Your order #1024 has been shipped.")
req, err := http.NewRequest(http.MethodPost, "https://api.sagesms.com/api/sms/send", strings.NewReader(form.Encode()))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
client := &http.Client{Timeout: 15 * time.Second}
res, err := client.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
var data map[string]any
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
panic(err)
}
if res.StatusCode != http.StatusOK || data["status"] != "success" {
fmt.Printf("SageSMS error (%d): %v\n", res.StatusCode, data["message"])
return
}
fmt.Println("Sent, serverRef:", data["serverRef"])
}Ruby 2.7+ standard library (works in Rails too).
require "net/http"
require "json"
require "uri"
# Tip: in production, load the API key from an environment variable or secrets manager.
uri = URI("https://api.sagesms.com/api/sms/send")
req = Net::HTTP::Post.new(uri, "Accept" => "application/json")
req.set_form_data(
"api_key" => "YOUR_API_KEY",
"user_id" => "YOUR_USER_ID",
"sender_id" => "YOUR_SENDER_ID",
"to" => "0771234567",
"message" => "Your order #1024 has been shipped."
)
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 15) do |http|
http.request(req)
end
data = JSON.parse(res.body)
if res.code == "200" && data["status"] == "success"
puts "Sent, serverRef: #{data["serverRef"]}"
else
warn "SageSMS error (#{res.code}): #{data["message"]}"
endKotlin/JVM on Java 11+ — for your backend (Ktor, Spring).
// Kotlin/JVM (Java 11+ HttpClient) — run on your server, not in an Android app.
import java.net.URI
import java.net.URLEncoder
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
fun main() {
// Tip: in production, load the API key from an environment variable or secrets manager.
val params = mapOf(
"api_key" to "YOUR_API_KEY",
"user_id" to "YOUR_USER_ID",
"sender_id" to "YOUR_SENDER_ID",
"to" to "0771234567",
"message" to "Your order #1024 has been shipped.",
)
val form = params.entries.joinToString("&") { (k, v) ->
URLEncoder.encode(k, Charsets.UTF_8) + "=" + URLEncoder.encode(v, Charsets.UTF_8)
}
val request = HttpRequest.newBuilder(URI.create("https://api.sagesms.com/api/sms/send"))
.header("Accept", "application/json")
.header("Content-Type", "application/x-www-form-urlencoded")
.timeout(Duration.ofSeconds(15))
.POST(HttpRequest.BodyPublishers.ofString(form))
.build()
val response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString())
// Parse with kotlinx.serialization / Moshi and check "status" == "success".
println("${response.statusCode()} ${response.body()}")
}Android (Kotlin) with OkHttp — see the security note in the code before shipping.
// Android (Kotlin) — OkHttp + coroutines
// build.gradle.kts:
// implementation("com.squareup.okhttp3:okhttp:4.12.0")
// implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
// AndroidManifest.xml: <uses-permission android:name="android.permission.INTERNET" />
// ⚠ Security: an API key inside a mobile app can be extracted from the app file.
// Use this for testing or internal apps only. In production, call your own
// backend from the app and let the backend call SageSMS with the key.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.util.concurrent.TimeUnit
private val client = OkHttpClient.Builder()
.callTimeout(15, TimeUnit.SECONDS)
.build()
/** Call from a coroutine, e.g. lifecycleScope.launch { sendSms() } */
suspend fun sendSms(): String = withContext(Dispatchers.IO) {
val form = FormBody.Builder()
.add("api_key", "YOUR_API_KEY")
.add("user_id", "YOUR_USER_ID")
.add("sender_id", "YOUR_SENDER_ID")
.add("to", "0771234567")
.add("message", "Your order #1024 has been shipped.")
.build()
val request = Request.Builder()
.url("https://api.sagesms.com/api/sms/send")
.header("Accept", "application/json")
.post(form)
.build()
client.newCall(request).execute().use { response ->
val json = JSONObject(response.body?.string().orEmpty())
if (!response.isSuccessful || json.optString("status") != "success") {
throw IllegalStateException("SageSMS error (${response.code}): ${json.optString("message")}")
}
json.getString("serverRef")
}
}Flutter / Dart with the http package — see the security note in the code before shipping.
// Flutter / Dart — pubspec.yaml: http: ^1.2.0
// Android also needs <uses-permission android:name="android.permission.INTERNET" />
// ⚠ Security: an API key inside a mobile app can be extracted from the app file.
// Use this for testing or internal apps only. In production, call your own
// backend from the app and let the backend call SageSMS with the key.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<String> sendSms() async {
final res = await http
.post(
Uri.parse('https://api.sagesms.com/api/sms/send'),
headers: {'Accept': 'application/json'},
body: {
'api_key': 'YOUR_API_KEY',
'user_id': 'YOUR_USER_ID',
'sender_id': 'YOUR_SENDER_ID',
'to': '0771234567',
'message': 'Your order #1024 has been shipped.',
},
)
.timeout(const Duration(seconds: 15));
final data = jsonDecode(res.body) as Map<String, dynamic>;
if (res.statusCode != 200 || data['status'] != 'success') {
throw Exception('SageSMS error (${res.statusCode}): ${data['message']}');
}
return data['serverRef'].toString();
}reqwest + tokio.
// Cargo.toml:
// reqwest = { version = "0.12", features = ["json"] }
// tokio = { version = "1", features = ["full"] }
// serde_json = "1"
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Tip: in production, load the API key from an environment variable or secrets manager.
let params = [
("api_key", "YOUR_API_KEY"),
("user_id", "YOUR_USER_ID"),
("sender_id", "YOUR_SENDER_ID"),
("to", "0771234567"),
("message", "Your order #1024 has been shipped."),
];
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.build()?;
let res = client
.post("https://api.sagesms.com/api/sms/send")
.header("Accept", "application/json")
.form(¶ms)
.send()
.await?;
let status = res.status();
let data: serde_json::Value = res.json().await?;
if status.is_success() && data["status"] == "success" {
println!("Sent, serverRef: {}", data["serverRef"]);
} else {
eprintln!("SageSMS error ({}): {}", status, data["message"]);
}
Ok(())
}Windows PowerShell 5.1 or PowerShell 7+.
# PowerShell 5.1+ / 7+
# Tip: in production, load the API key from an environment variable or secrets manager.
$body = @{
api_key = "YOUR_API_KEY"
user_id = "YOUR_USER_ID"
sender_id = "YOUR_SENDER_ID"
to = "0771234567"
message = "Your order #1024 has been shipped."
}
try {
$data = Invoke-RestMethod -Method Post -Uri "https://api.sagesms.com/api/sms/send" `
-Headers @{ Accept = "application/json" } `
-Body $body -TimeoutSec 15
Write-Host "Sent, serverRef: $($data.serverRef)"
} catch {
# 4xx/5xx responses land here — the JSON error is in ErrorDetails.
Write-Error "SageSMS error: $($_.ErrorDetails.Message)"
}Replace YOUR_API_KEY, YOUR_USER_ID and YOUR_SENDER_ID with the values from Settings → Integrations in your SageSMS dashboard — the same examples there come pre-filled with your own credentials.
Building a mobile app? The Android and Flutter examples work, but an API key inside an app can be extracted from the installed app. Use them for testing or internal tools, and in production send SMS from your own backend, which your app calls.
Notice the Accept: application/json header in every example. It makes sure that if a parameter is missing, the API answers with a JSON validation error you can read, rather than an HTML redirect.
4. Read the response and handle errors
A successful send returns HTTP 200 with a server reference you should store alongside your own record:
{"status":"success","result":"sent","serverRef":"1432616715"}When something goes wrong, status is "error" and message explains why. The most common cases:
| HTTP | Meaning | What to do |
|---|---|---|
| 401 | Invalid API key or User ID | Check your credentials — the key may have been regenerated. |
| 403 | Account not active, Sender ID invalid or inactive, wrong Sender ID type, or a promotional send outside 8 AM–8 PM | Read the message: use the right Sender ID type, or retry promotional sends in the allowed window. |
| 422 | Missing parameters, insufficient balance, or a delivery error | Fix the request, or recharge the account. The message tells you the cost and page count needed. |
Log every failure with the phone number, the error message and the time. For critical messages such as OTPs, show the user a friendly “couldn’t send the code, please try again” and alert your team if failures repeat.
5. Building an OTP flow
OTP verification is the most common reason developers integrate SMS. The gateway only delivers the message — your application owns the code. A secure flow looks like this:
- Generate a random 6-digit code on the server (use a cryptographically secure random function).
- Store a hash of the code with the user ID and an expiry 5–10 minutes ahead.
- Send it through
/api/sms/send: “Your YourBrand verification code is 482913. It expires in 5 minutes.” - When the user submits a code, compare it to the stored hash and check it hasn’t expired.
- Delete the code after a successful check, and limit attempts and resends per number.
Rate-limiting resends matters for cost as well as security: without it, a bot can trigger thousands of paid messages. Read more on the OTP SMS page.
6. Monitor your balance
An integration that silently stops when credit runs out is a common cause of missed OTPs. Call the balance endpoint from a scheduled job and alert your team below a threshold:
curl -X POST https://api.sagesms.com/api/sms/balance \
-H "Accept: application/json" \
-d api_key=YOUR_API_KEY -d user_id=YOUR_USER_ID
{"status":"success","result":{"account_status":"active","account_balance":"993.52"}}Top-ups can be made instantly online from the recharge page.
7. Production checklist
- API key stored in an environment variable or secrets manager, never in client-side code.
- All SMS sends made from your server, never directly from a browser or mobile app.
- Timeouts set on HTTP calls, and failures logged with the API’s error message.
- Transactional and promotional traffic sent through the correct endpoint and Sender ID.
- Promotional sends scheduled inside 8:00 AM–8:00 PM Sri Lanka time.
- OTP attempts and resends rate-limited per user and per phone number.
- Balance monitored with an alert before it runs out.
Running WordPress? You can skip the code entirely with the SageSMS WooCommerce plugin, which sends order-status SMS automatically.