Guide

How to Integrate an SMS API: Code Examples in 15 Languages

19 November 2026 · 9 min read · SageSMS team

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_id and api_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.

EndpointUse it forNotes
/api/sms/sendTransactional SMS — OTPs, alerts, order updatesRequires a Transactional Sender ID. Works 24/7.
/api/sms/sendpromoPromotional SMS — offers and campaignsRequires a Promotional Sender ID. Accepted 8:00 AM–8:00 PM Sri Lanka time.
/api/sms/balanceChecking balance and account statusOnly needs api_key and user_id.

The base URL is https://api.sagesms.com. The two send endpoints take the same five parameters:

  • api_key and user_id — your credentials
  • sender_id — an approved Sender ID on your account, e.g. YOURBRAND
  • to — the recipient’s mobile number, e.g. 0771234567
  • message — 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.

PHP 7.4+ with the cURL extension.

PHP · Transactional
<?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'));
}

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:

HTTPMeaningWhat to do
401Invalid API key or User IDCheck your credentials — the key may have been regenerated.
403Account not active, Sender ID invalid or inactive, wrong Sender ID type, or a promotional send outside 8 AM–8 PMRead the message: use the right Sender ID type, or retry promotional sends in the allowed window.
422Missing parameters, insufficient balance, or a delivery errorFix 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:

  1. Generate a random 6-digit code on the server (use a cryptographically secure random function).
  2. Store a hash of the code with the user ID and an expiry 5–10 minutes ahead.
  3. Send it through /api/sms/send: “Your YourBrand verification code is 482913. It expires in 5 minutes.”
  4. When the user submits a code, compare it to the stored hash and check it hasn’t expired.
  5. 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.

Ready to start sending?

Create a SageSMS account — no monthly fees, free API access, and SMS credits that never expire.