A complete guide to integrating our SMS Gateway API into any software, platform, or programming language. Send transactional OTPs, notifications, alerts, and bulk SMS with full DLT/TRAI compliance.
All API requests require an API Key for authentication. The API Key uniquely identifies your account and authorizes your requests. You can find your API Key in the SMS Gateway dashboard under your user profile.
sk_ followed by a 48-character hex string.
Example: sk_a1b2c3d4e5f6...
You can pass the API Key in any of these three ways:
| Method | How to Send | Example |
|---|---|---|
| Query Parameter | Append ?api_key=YOUR_KEY to the URL |
/api/send.php?api_key=sk_xxx |
| POST Body | Include api_key as a form field |
api_key=sk_xxx |
| HTTP Header | Send as X-Api-Key header |
X-Api-Key: sk_xxx |
All API endpoints are relative to your gateway's base URL:
https://yourdomain.com/sms-gateway
Replace yourdomain.com/sms-gateway with the actual domain where your SMS Gateway is hosted.
All API calls shown in this document use {BASE_URL} as a placeholder for this.
Send your first SMS in under 5 minutes:
curl -X POST "{BASE_URL}/api/send.php" \ -d "api_key=sk_your_api_key" \ -d "mobile=9876543210" \ -d "message=Your OTP is 123456. Valid for 5 minutes." \ -d "sender_id=MYSEND" \ -d "entity_id=YOUR_ENTITY_ID" \ -d "template_id=YOUR_TEMPLATE_ID" \ -d "sms_type=transactional"
{
"success": true,
"message": "SMS sent successfully",
"mobile": "919876543210",
"response": "1234567890-ABCDEF",
"balance": 49.80
}
This is the primary endpoint to send a single SMS message to a mobile number.
| Parameter | Type | Required | Description | Example |
|---|---|---|---|---|
api_key |
string | Required | Your account API key for authentication. | sk_a1b2c3... |
mobile |
string | Required | Recipient's mobile number. 10-digit Indian number (6–9 series). The system auto-prepends 91. |
9876543210 |
message |
string | Required | The SMS message content. Must match your DLT approved template exactly. | Your OTP is 123456. |
sender_id |
string | Required | TRAI DLT registered Sender ID. 6-character alphanumeric. | MYSEND |
entity_id |
string | Required | Your TRAI DLT registered Entity ID. | 1001XXXXXXXXX |
template_id |
string | Required | The DLT Template ID approved for this specific message. | 1007XXXXXXXXX |
sms_type |
string | Optional |
Type of SMS. See SMS Types section for details. Default: transactional
|
transactional |
{
"success": true,
"message": "SMS sent successfully",
"mobile": "919876543210", // Normalized number with country code
"response": "MSG-ID-12345", // Message ID from carrier
"balance": 49.80 // Remaining wallet balance (₹)
}
{
"success": false,
"error": "Invalid mobile number: 123456"
}
Retrieve your current wallet balance and SMS credit information.
| Parameter | Type | Required | Description |
|---|---|---|---|
api_key |
string | Required | Your account API key. |
{
"success": true,
"balance": 49.80, // Wallet balance in INR (₹)
"sms_rate": 0.20, // Cost per SMS in INR
"sms_count": 249 // Estimated SMS credits remaining
}
curl "{BASE_URL}/api/balance.php?api_key=sk_your_api_key"
India's TRAI mandates DLT (Distributed Ledger Technology) compliance. Choose the correct sms_type for your message:
| sms_type Value | Use Case | Time Restriction (IST) |
|---|---|---|
transactional ⭐ |
OTP, transaction alerts, login codes, password reset — sent to opted-in users | ✅ 24×7 allowed |
service_implicit |
Service messages to existing customers (bills, delivery updates) | ✅ 24×7 allowed |
promotional |
Marketing/offers to opted-in users | ⏰ 9:00 AM – 9:00 PM IST only |
service_explicit |
Service messages to users who have explicitly opted in | ⏰ 9:00 AM – 9:00 PM IST only |
sms_type=transactional. It works 24×7 and is not subject to time restrictions.
The API accepts Indian mobile numbers in multiple formats and normalizes them automatically:
| Input Format | Example | Stored As | Valid? |
|---|---|---|---|
| 10-digit | 9876543210 | 919876543210 | ✅ |
| With country code | 919876543210 | 919876543210 | ✅ |
| With leading zero | 09876543210 | 919876543210 | ✅ |
| Must start with 6–9 | 5876543210 | — | ❌ Invalid |
To ensure platform stability, API requests are rate-limited per account:
| Limit | Value | Error Code |
|---|---|---|
| Requests per minute | 60 requests / minute (configurable by admin) | 1009 — Rate limit exceeded |
function sendSmsWithRetry($params, $maxRetries = 3): array { $attempt = 0; while ($attempt < $maxRetries) { $response = sendSms($params); if ($response['success'] || http_response_code() !== 429) { return $response; } $delay = (2 ** $attempt) * 1000000; // exponential backoff (microseconds) usleep($delay); $attempt++; } return ['success' => false, 'error' => 'Max retries exceeded']; }
All API responses return Content-Type: application/json. The response always contains a success boolean field.
{
"success": true, // Always present
"message": "SMS sent successfully",
"mobile": "919876543210", // Normalized mobile
"response": "MSG-ID-XYZ", // Carrier message ID
"balance": 49.80 // Remaining balance
}
{
"success": false, // Always present
"error": "Error description", // Human-readable error
"balance": 0.00 // Sometimes included
}
{
"success": false,
"error": "Promotional SMS is only allowed between 9:00 AM – 9:00 PM IST.",
"sms_type": "promotional",
"ist_time": "10:35 PM IST" // Wallet NOT deducted
}
| Error Code | HTTP Status | Description | Solution |
|---|---|---|---|
| 1001 | 401 | API key missing or invalid / inactive account | Verify your API key from the dashboard. |
| 1002 | 402 | Insufficient wallet balance | Recharge your wallet from the dashboard. |
| 1003 | 400 | Invalid mobile number format | Ensure 10-digit Indian number starting with 6–9. |
| 1004 | 400 | Sender ID missing or not configured | Provide a valid DLT-registered Sender ID. |
| 1005 | 400 | Entity ID missing | Provide your TRAI DLT Entity ID. |
| 1006 | 400 | DLT Template ID missing or invalid | Provide the correct DLT Template ID for this message type. |
| 1008 | 400 | Number is on DND (Do Not Disturb) list | Cannot send to DND numbers for promotional SMS. |
| 1009 | 429 | Rate limit exceeded (60 req/min) | Slow down requests; implement retry with backoff. |
| 1016 | 400 | Time restriction violated (promotional SMS outside 9AM–9PM IST) | Send only between 9:00 AM – 9:00 PM IST. Wallet not deducted. |
| — | 500 | SMS delivery failed (carrier error) | Retry. Wallet is NOT deducted on failure. |
| HTTP Code | Meaning |
|---|---|
| 200 OK | Request successful. Check success field in JSON for delivery status. |
| 400 Bad Request | Missing or invalid parameters. |
| 401 Unauthorized | Invalid or missing API key. |
| 402 Payment Required | Insufficient wallet balance. |
| 429 Too Many Requests | Rate limit exceeded. |
| 500 Internal Error | Carrier-side delivery failure. |
If your application uses multiple message templates (e.g., License Management, ERP, CRM), each template must have its own DLT-registered template_id.
Always pass the matching template_id for each message type.
template_id.
// Define all your DLT templates in one config file define('SMS_TEMPLATES', [ // ── OTP & Authentication ── 'otp_login' => [ 'template_id' => '1007XXXXXXXXX001', 'message' => 'Your login OTP is {otp}. Valid for 5 minutes. Do not share. - MYSEND', ], 'otp_register' => [ 'template_id' => '1007XXXXXXXXX002', 'message' => 'Welcome! Your registration OTP is {otp}. Valid for 10 minutes. - MYSEND', ], // ── License Events ── 'license_generated' => [ 'template_id' => '1007XXXXXXXXX003', 'message' => 'Your license key is {license_key}. Product: {product}. - MYSEND', ], 'license_expiry_alert' => [ 'template_id' => '1007XXXXXXXXX004', 'message' => 'Alert: Your {product} license expires on {date}. Renew now. - MYSEND', ], 'license_expired' => [ 'template_id' => '1007XXXXXXXXX005', 'message' => 'Your {product} license has expired. Contact support. - MYSEND', ], 'license_renewed' => [ 'template_id' => '1007XXXXXXXXX006', 'message' => 'Your {product} license renewed successfully until {date}. - MYSEND', ], 'license_blocked' => [ 'template_id' => '1007XXXXXXXXX007', 'message' => 'Your {product} license has been blocked. Contact support: {phone}. - MYSEND', ], 'new_license_key' => [ 'template_id' => '1007XXXXXXXXX008', 'message' => 'New license key issued: {license_key}. Valid till {date}. - MYSEND', ], 'renewal_reminder' => [ 'template_id' => '1007XXXXXXXXX009', 'message' => 'Reminder: Renew your {product} license before {date} to avoid disruption. - MYSEND', ], // ── Payment ── 'payment_success' => [ 'template_id' => '1007XXXXXXXXX010', 'message' => 'Payment of Rs.{amount} received for {product}. Txn ID: {txn_id}. - MYSEND', ], 'payment_failed' => [ 'template_id' => '1007XXXXXXXXX011', 'message' => 'Payment of Rs.{amount} failed. Please retry or contact support. - MYSEND', ], 'invoice_generated' => [ 'template_id' => '1007XXXXXXXXX012', 'message' => 'Invoice #{invoice_no} of Rs.{amount} generated. Download: {link} - MYSEND', ], ]); /** * Send an SMS using a named template. * * @param string $templateKey Key from SMS_TEMPLATES (e.g., 'license_generated') * @param string $mobile 10-digit mobile number * @param array $vars Placeholder replacements (['license_key' => 'XXXX', ...]) */ function sendTemplateSms($templateKey, $mobile, array $vars): array { $config = SMS_TEMPLATES[$templateKey] ?? null; if (!$config) { throw new \InvalidArgumentException("Unknown SMS template: {$templateKey}"); } // Replace {placeholder} with actual values $message = $config['message']; foreach ($vars as $key => $value) { $message = str_replace("{{$key}}", $value, $message); } $postData = http_build_query([ 'api_key' => 'sk_your_api_key', 'mobile' => $mobile, 'message' => $message, 'sender_id' => 'MYSEND', 'entity_id' => 'YOUR_ENTITY_ID', 'template_id' => $config['template_id'], 'sms_type' => 'transactional', ]); $ch = curl_init('{BASE_URL}/api/send.php'); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postData, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $response = json_decode(curl_exec($ch), true); curl_close($ch); return $response; } // ── Usage Examples ────────────────────────────── // Send OTP sendTemplateSms('otp_login', '9876543210', ['otp' => '847291']); // Send license generated SMS sendTemplateSms('license_generated', '9876543210', [ 'license_key' => 'LIC-2024-ABCD-1234', 'product' => 'MyApp Pro', ]); // Send payment success sendTemplateSms('payment_success', '9876543210', [ 'amount' => '2999', 'product' => 'MyApp Pro Annual', 'txn_id' => 'TXN20240115001', ]); // Send renewal reminder sendTemplateSms('renewal_reminder', '9876543210', [ 'product' => 'MyApp Pro', 'date' => '31 Jan 2025', ]);
// Notify all users whose license expires in 7 days $expiringUsers = $db->query(" SELECT mobile, name, product_name, expiry_date FROM licenses WHERE expiry_date = DATE_ADD(CURDATE(), INTERVAL 7 DAY) AND status = 'active' "); foreach ($expiringUsers as $user) { sendTemplateSms('license_expiry_alert', $user['mobile'], [ 'product' => $user['product_name'], 'date' => date('d M Y', strtotime($user['expiry_date'])), ]); usleep(200000); // 200ms delay to respect rate limits }
Complete working examples in popular programming languages and frameworks.
function sendSms(array $params): array { $baseUrl = '{BASE_URL}'; $payload = array_merge([ 'api_key' => 'sk_your_api_key', 'sender_id' => 'MYSEND', 'entity_id' => 'YOUR_ENTITY_ID', 'sms_type' => 'transactional', ], $params); $ch = curl_init($baseUrl . '/api/send.php'); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($payload), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_SSL_VERIFYPEER => true, ]); $body = curl_exec($ch); $err = curl_error($ch); curl_close($ch); if ($err) return ['success' => false, 'error' => $err]; return json_decode($body, true) ?: ['success' => false, 'error' => 'Invalid response']; } // Send OTP $result = sendSms([ 'mobile' => '9876543210', 'message' => 'Your OTP is 123456. Valid for 5 minutes.', 'template_id' => '1007XXXXXXXXX001', ]); if ($result['success']) { echo "SMS sent! Balance: ₹" . $result['balance']; } else { echo "Error: " . $result['error']; }
import requests BASE_URL = "{BASE_URL}" API_KEY = "sk_your_api_key" def send_sms(mobile: str, message: str, template_id: str, sender_id: str = "MYSEND", sms_type: str = "transactional") -> dict: """Send a single SMS via the gateway.""" response = requests.post( f"{BASE_URL}/api/send.php", data={ "api_key": API_KEY, "mobile": mobile, "message": message, "sender_id": sender_id, "entity_id": "YOUR_ENTITY_ID", "template_id": template_id, "sms_type": sms_type, }, timeout=30 ) response.raise_for_status() return response.json() def check_balance() -> dict: """Check current wallet balance.""" response = requests.get( f"{BASE_URL}/api/balance.php", params={"api_key": API_KEY}, timeout=15 ) return response.json() # ── Usage ───────────────────────────────────────── # Send OTP result = send_sms( mobile="9876543210", message="Your OTP is 123456. Valid for 5 minutes.", template_id="1007XXXXXXXXX001" ) if result["success"]: print(f"Sent! Balance: ₹{result['balance']}") else: print(f"Failed: {result['error']}") # Send License Generated notification send_sms( mobile="9876543210", message="Your license key is LIC-2024-ABCD-1234. Product: MyApp Pro.", template_id="1007XXXXXXXXX003" ) # Check balance bal = check_balance() print(f"Balance: ₹{bal['balance']} | SMS credits: {bal['sms_count']}")
const axios = require('axios'); const qs = require('querystring'); const BASE_URL = '{BASE_URL}'; const API_KEY = 'sk_your_api_key'; async function sendSms({ mobile, message, templateId, smsType = 'transactional' }) { const { data } = await axios.post( `${BASE_URL}/api/send.php`, qs.stringify({ api_key: API_KEY, mobile, message, sender_id: 'MYSEND', entity_id: 'YOUR_ENTITY_ID', template_id: templateId, sms_type: smsType, }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 30000 } ); return data; } async function checkBalance() { const { data } = await axios.get(`${BASE_URL}/api/balance.php`, { params: { api_key: API_KEY } }); return data; } // ── Usage ───────────────────────────────────────── (async () => { // Send OTP const result = await sendSms({ mobile: '9876543210', message: 'Your OTP is 123456. Valid for 5 minutes.', templateId: '1007XXXXXXXXX001', }); console.log(result.success ? `Sent! Balance: ₹${result.balance}` : `Error: ${result.error}`); // Check balance const bal = await checkBalance(); console.log(`Balance: ₹${bal.balance} | Credits: ${bal.sms_count}`); })();
import java.net.*; import java.io.*; import org.json.*; public class SmsGateway { private static final String BASE_URL = "{BASE_URL}"; private static final String API_KEY = "sk_your_api_key"; public static JSONObject sendSms(String mobile, String message, String templateId) throws Exception { String body = "api_key=" + API_KEY + "&mobile=" + URLEncoder.encode(mobile, "UTF-8") + "&message=" + URLEncoder.encode(message, "UTF-8") + "&sender_id=MYSEND" + "&entity_id=YOUR_ENTITY_ID" + "&template_id=" + templateId + "&sms_type=transactional"; URL url = new URL(BASE_URL + "/api/send.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setConnectTimeout(10000); conn.setReadTimeout(30000); try (OutputStream os = conn.getOutputStream()) { os.write(body.getBytes("UTF-8")); } BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) sb.append(line); return new JSONObject(sb.toString()); } public static void main(String[] args) throws Exception { JSONObject result = sendSms("9876543210", "Your OTP is 123456. Valid for 5 minutes.", "1007XXXXXXXXX001"); if (result.getBoolean("success")) { System.out.println("Sent! Balance: ₹" + result.getDouble("balance")); } else { System.out.println("Error: " + result.getString("error")); } } }
using System.Net.Http; using System.Text.Json; public class SmsGateway { private const string BASE_URL = "{BASE_URL}"; private const string API_KEY = "sk_your_api_key"; private static readonly HttpClient _client = new() { Timeout = TimeSpan.FromSeconds(30) }; public static async Task<JsonElement> SendSmsAsync( string mobile, string message, string templateId, string smsType = "transactional") { var form = new FormUrlEncodedContent(new[] { new KeyValuePair<string,string>("api_key", API_KEY), new KeyValuePair<string,string>("mobile", mobile), new KeyValuePair<string,string>("message", message), new KeyValuePair<string,string>("sender_id", "MYSEND"), new KeyValuePair<string,string>("entity_id", "YOUR_ENTITY_ID"), new KeyValuePair<string,string>("template_id", templateId), new KeyValuePair<string,string>("sms_type", smsType), }); var response = await _client.PostAsync($"{BASE_URL}/api/send.php", form); var content = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<JsonElement>(content); } // Usage public static async Task Main() { var result = await SendSmsAsync( "9876543210", "Your OTP is 123456. Valid for 5 minutes.", "1007XXXXXXXXX001" ); if (result.GetProperty("success").GetBoolean()) Console.WriteLine($"Sent! Balance: ₹{result.GetProperty("balance").GetDouble()}"); else Console.WriteLine($"Error: {result.GetProperty("error").GetString()}"); } }
// ⚠️ Always call from your backend — never expose API key in browser const BASE_URL = '{BASE_URL}'; const API_KEY = 'sk_your_api_key'; async function sendSms({ mobile, message, templateId, smsType = 'transactional' }) { const body = new URLSearchParams({ api_key: API_KEY, mobile, message, sender_id: 'MYSEND', entity_id: 'YOUR_ENTITY_ID', template_id: templateId, sms_type: smsType, }); const res = await fetch(`${BASE_URL}/api/send.php`, { method: 'POST', body }); const data = await res.json(); return data; } // Usage sendSms({ mobile: '9876543210', message: 'Your OTP is 123456. Valid for 5 minutes.', templateId: '1007XXXXXXXXX001', }).then(res => { if (res.success) console.log('SMS sent! Balance: ₹' + res.balance); else console.error('Error: ' + res.error); });
curl -X POST "{BASE_URL}/api/send.php" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "api_key=sk_your_api_key" \ -d "mobile=9876543210" \ -d "message=Your OTP is 123456. Valid for 5 minutes." \ -d "sender_id=MYSEND" \ -d "entity_id=YOUR_ENTITY_ID" \ -d "template_id=1007XXXXXXXXX001" \ -d "sms_type=transactional"
curl "{BASE_URL}/api/balance.php?api_key=sk_your_api_key"
curl -X POST "{BASE_URL}/api/send.php" \ -H "X-Api-Key: sk_your_api_key" \ -d "mobile=9876543210" \ -d "message=Your OTP is 123456." \ -d "sender_id=MYSEND" \ -d "entity_id=YOUR_ENTITY_ID" \ -d "template_id=1007XXXXXXXXX001"
function my_send_sms($mobile, $message, $templateId) { $response = wp_remote_post('{BASE_URL}/api/send.php', [ 'timeout' => 30, 'body' => [ 'api_key' => get_option('my_sms_api_key'), 'mobile' => $mobile, 'message' => $message, 'sender_id' => get_option('my_sms_sender_id'), 'entity_id' => get_option('my_sms_entity_id'), 'template_id' => $templateId, 'sms_type' => 'transactional', ], ]); return json_decode(wp_remote_retrieve_body($response), true); }
use Illuminate\Support\Facades\Http; class SmsService { public function send(string $mobile, string $message, string $templateId): array { $response = Http::timeout(30)->asForm()->post( config('services.sms.base_url') . '/api/send.php', [ 'api_key' => config('services.sms.api_key'), 'mobile' => $mobile, 'message' => $message, 'sender_id' => config('services.sms.sender_id'), 'entity_id' => config('services.sms.entity_id'), 'template_id' => $templateId, 'sms_type' => 'transactional', ] ); return $response->json(); } } // config/services.php 'sms' => [ 'base_url' => env('SMS_BASE_URL'), 'api_key' => env('SMS_API_KEY'), 'sender_id' => env('SMS_SENDER_ID'), 'entity_id' => env('SMS_ENTITY_ID'), ]
# sms_service.py import requests from django.conf import settings def send_sms(mobile: str, message: str, template_id: str) -> dict: return requests.post( f"{settings.SMS_GATEWAY_URL}/api/send.php", data={ "api_key": settings.SMS_API_KEY, "mobile": mobile, "message": message, "sender_id": settings.SMS_SENDER_ID, "entity_id": settings.SMS_ENTITY_ID, "template_id": template_id, "sms_type": "transactional", }, timeout=30 ).json() # settings.py SMS_GATEWAY_URL = env('SMS_GATEWAY_URL') SMS_API_KEY = env('SMS_API_KEY') SMS_SENDER_ID = env('SMS_SENDER_ID') SMS_ENTITY_ID = env('SMS_ENTITY_ID')
const express = require('express'); const axios = require('axios'); const qs = require('querystring'); const app = express(); app.use(express.json()); // SMS Service const smsService = { send: async (mobile, message, templateId) => { const { data } = await axios.post( `${process.env.SMS_GATEWAY_URL}/api/send.php`, qs.stringify({ api_key: process.env.SMS_API_KEY, mobile, message, sender_id: process.env.SMS_SENDER_ID, entity_id: process.env.SMS_ENTITY_ID, template_id: templateId, sms_type: 'transactional', }) ); return data; } }; // API Route — Send OTP app.post('/send-otp', async (req, res) => { const { mobile } = req.body; const otp = Math.floor(100000 + Math.random() * 900000); const result = await smsService.send( mobile, `Your OTP is ${otp}. Valid for 5 minutes.`, process.env.OTP_TEMPLATE_ID ); res.json({ success: result.success, message: result.message }); });
success: true in the JSON response before assuming delivery.| Item | Description | Where to Get |
|---|---|---|
| Entity ID | Unique ID assigned to your business on DLT | DLT portal (Jio, Airtel, Vi, BSNL) |
| Sender ID | 6-character ID shown as sender name | Register on DLT portal under Headers |
| Template ID | Unique ID for each approved message template | Register each template on DLT portal |