Developer Guide

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.

Before You Begin

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

  1. Create an account — Sign up at onlinesmsservice.com
  2. Get your API key — Find it in Dashboard → Settings → API Keys
  3. Register DLT templates — Required for sending SMS in India
  4. Whitelist your server IP — Optional but recommended for security
Method 1

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.php
<?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";
}
💡 Pro Tip: Store your API key in environment variables ($_ENV['SMS_API_KEY']) or a .env file — never hard-code secrets in production.
Method 2

Install via Composer SDK

Our official PHP SDK handles authentication, retries, and error parsing for you.

Terminal
composer require onlinesmsservice/php-sdk
PHP — Using the 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";
}
Method 3

Laravel Integration

Use our Laravel service provider for clean, framework-native SMS sending with queues and notifications.

Terminal
composer require onlinesmsservice/laravel-sms
.env
SMS_API_KEY=your_api_key_here
SMS_SENDER_ID=YOURID
SMS_DEFAULT_TYPE=transactional
PHP — app/Notifications/OtpNotification.php
<?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'));
Method 4

WordPress Plugin Integration

Send SMS notifications on WooCommerce orders, form submissions, and user registrations.

PHP — wp-content/plugins/oss-sms/oss-sms.php
<?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();
Reference

API Response & Error Codes

Every API call returns a JSON object. Here are the most common status codes.

HTTP CodeStatusMeaning
200successMessage accepted and queued for delivery
400invalid_requestMissing or malformed parameters
401unauthorizedInvalid API key or IP not whitelisted
402insufficient_balanceTop up your account to continue sending
422dlt_errorDLT template not registered or mismatch
429rate_limitedToo many requests — implement backoff
500server_errorTransient issue — safe to retry with backoff
JSON — Success Response
{
  "status": "success",
  "message_id": "msg_abc123xyz",
  "to": "919876543210",
  "credits_used": 1,
  "credits_remaining": 9487
}
Best Practices

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
FAQ

Common Questions

Do I need DLT registration to send SMS in India?
Yes. TRAI mandates DLT registration for all commercial SMS in India. You need to register your Principal Entity (PE), Sender IDs, and message templates. Read our DLT registration guide →
What is the rate limit for the API?
The default rate limit is 100 requests per second. Enterprise plans can request higher limits. The bulk endpoint accepts up to 10,000 numbers per call, which is the recommended approach for high-volume sending.
Can I send OTP SMS with this API?
Absolutely. Use the 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?
Yes. Our SDK is tested on PHP 7.4, 8.0, 8.1, 8.2, and 8.3. We use named arguments, union types, and other modern PHP features where supported.
How do I check delivery status?
Two ways: (1) Poll the GET /v1/sms/{message_id}/status endpoint, or (2) configure a webhook URL in your dashboard to receive real-time delivery receipts via POST.

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.