How to Integrate SMS Gateway in PHP
Production-ready code examples for cURL, Composer SDK, Laravel, and WordPress — send your first SMS in under 5 minutes.
5-Minute Setup
Get your API key, install our SDK via Composer, and send your first SMS — all in under five minutes.
Enterprise-Grade
HTTPS-only endpoints, bearer-token auth, IP whitelisting, and TRAI DLT compliance built in.
Real-Time Reports
Delivery receipts, webhook callbacks, and a full analytics dashboard — all via the same API.
Prerequisites
System Requirements
- PHP 7.4 or higher (PHP 8.x recommended)
- cURL extension enabled (
php -m | grep curl) - JSON extension enabled (default in PHP 7+)
- Composer (optional, for SDK installation)
- SSL certificate on your server (HTTPS)
Account Setup
- Create an account — Sign up at onlinesmsservice.com
- Get your API key — Find it in Dashboard → Settings → API Keys
- Register DLT templates — Required for sending SMS in India
- Whitelist your server IP — Optional but recommended for security
Send SMS with PHP cURL (No Dependencies)
The simplest approach — no external libraries required. Works on any PHP installation with cURL enabled.
<?php
/**
* Send SMS using OnlineSMSService API with cURL
*/
function sendSMS(string $to, string $message, string $senderId = 'YOURID'): array
{
$apiKey = 'YOUR_API_KEY'; // Replace with your key
$apiUrl = 'https://api.onlinesmsservice.com/v1/sms/send';
$payload = json_encode([
'to' => $to,
'message' => $message,
'sender' => $senderId,
'type' => 'transactional', // or 'promotional'
]);
$ch = curl_init($apiUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
$error = curl_error($ch);
curl_close($ch);
throw new RuntimeException("cURL error: {$error}");
}
curl_close($ch);
$data = json_decode($response, true);
$data['http_code'] = $httpCode;
return $data;
}
// ── Usage ──────────────────────────────────────
try {
$result = sendSMS('919876543210', 'Your OTP is 482910. Valid for 5 min.');
echo "Status : {$result['status']}\n";
echo "Msg ID : {$result['message_id']}\n";
} catch (RuntimeException $e) {
echo "Error : {$e->getMessage()}\n";
}
$_ENV['SMS_API_KEY']) or a .env file — never hard-code secrets in production.
Install via Composer SDK
Our official PHP SDK handles authentication, retries, and error parsing for you.
composer require onlinesmsservice/php-sdk
<?php
require 'vendor/autoload.php';
use OnlineSMSService\Client;
use OnlineSMSService\Message;
$client = new Client('YOUR_API_KEY');
// Single SMS
$result = $client->send(
Message::create()
->to('919876543210')
->text('Hello from OnlineSMSService!')
->sender('YOURID')
->type('transactional')
);
echo $result->messageId(); // e.g. "msg_abc123"
echo $result->status(); // "queued"
// Bulk SMS — up to 10,000 numbers
$bulk = $client->sendBulk(
Message::create()
->to(['919876543210', '919876543211', '919876543212'])
->text('Flash sale! 40% off everything today.')
->sender('YOURID')
->type('promotional')
);
foreach ($bulk->results() as $r) {
echo "{$r->phone()} → {$r->status()}\n";
}
Laravel Integration
Use our Laravel service provider for clean, framework-native SMS sending with queues and notifications.
composer require onlinesmsservice/laravel-sms
SMS_API_KEY=your_api_key_here
SMS_SENDER_ID=YOURID
SMS_DEFAULT_TYPE=transactional
<?php
namespace App\Notifications;
use Illuminate\Notifications\Notification;
use OnlineSMSService\Laravel\SmsChannel;
use OnlineSMSService\Laravel\SmsMessage;
class OtpNotification extends Notification
{
public function __construct(private string $otp) {}
public function via($notifiable): array
{
return [SmsChannel::class];
}
public function toSms($notifiable): SmsMessage
{
return (new SmsMessage)
->to($notifiable->phone)
->text("Your OTP is {$this->otp}. Valid for 5 minutes.");
}
}
// In your controller:
$user->notify(new OtpNotification('482910'));
WordPress Plugin Integration
Send SMS notifications on WooCommerce orders, form submissions, and user registrations.
<?php
/*
* Plugin Name: OnlineSMSService SMS Gateway
* Description: Send SMS from WordPress via OnlineSMSService API
* Version: 1.0.0
*/
if (!defined('ABSPATH')) exit;
class OSS_SMS_Plugin {
private $api_key;
public function __construct() {
$this->api_key = get_option('oss_sms_api_key', '');
add_action('admin_menu', [$this, 'settings_page']);
// WooCommerce order hook
add_action('woocommerce_order_status_completed', [$this, 'order_sms']);
}
public function send($to, $message) {
return wp_remote_post('https://api.onlinesmsservice.com/v1/sms/send', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->api_key,
],
'body' => wp_json_encode([
'to' => $to,
'message' => $message,
'type' => 'transactional',
]),
]);
}
public function order_sms($order_id) {
$order = wc_get_order($order_id);
$phone = $order->get_billing_phone();
$this->send($phone, "Order #{$order_id} shipped! Track at yoursite.com/track/{$order_id}");
}
}
new OSS_SMS_Plugin();
API Response & Error Codes
Every API call returns a JSON object. Here are the most common status codes.
| HTTP Code | Status | Meaning |
|---|---|---|
200 | success | Message accepted and queued for delivery |
400 | invalid_request | Missing or malformed parameters |
401 | unauthorized | Invalid API key or IP not whitelisted |
402 | insufficient_balance | Top up your account to continue sending |
422 | dlt_error | DLT template not registered or mismatch |
429 | rate_limited | Too many requests — implement backoff |
500 | server_error | Transient issue — safe to retry with backoff |
{
"status": "success",
"message_id": "msg_abc123xyz",
"to": "919876543210",
"credits_used": 1,
"credits_remaining": 9487
}
Production Checklist
🔐 Security
- Store API keys in environment variables, not code
- Use HTTPS for all API calls (enforced by default)
- Whitelist server IPs in your dashboard
- Rotate API keys periodically
⚡ Performance
- Use the bulk endpoint for 100+ messages
- Implement exponential backoff on 429/500 errors
- Queue SMS sends asynchronously (Laravel Queue, Redis, etc.)
- Set a 30-second cURL timeout
✅ Compliance
- Register DLT templates before sending
- Include opt-out instructions in promotional SMS
- Respect DND (Do Not Disturb) preferences
- Keep audit logs of all sent messages
🧪 Testing
- Use sandbox mode for development
- Verify delivery with webhook callbacks
- Test all error-code paths (401, 402, 422, etc.)
- Monitor credits balance with API alerts
Common Questions
Do I need DLT registration to send SMS in India?
What is the rate limit for the API?
Can I send OTP SMS with this API?
type: "transactional" parameter for OTPs. Transactional messages are delivered 24/7 with priority routing, achieving 2–6 second delivery times.Does the SDK support PHP 8?
How do I check delivery status?
GET /v1/sms/{message_id}/status endpoint, or (2) configure a webhook URL in your dashboard to receive real-time delivery receipts via POST.More Integration Guides
Ready to Send Your First SMS?
Get 500 free SMS credits when you sign up upon successful registration and DLT mapping with an approved telemarketer.