PHP code example of gr8shivam / laravel-sms-api

1. Go to this page and download the library: Download gr8shivam/laravel-sms-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gr8shivam / laravel-sms-api example snippets


use Gr8Shivam\SmsApi\SmsApiFacade as SmsApi;

// Simple usage
SmsApi::sendMessage("9876543210", "Hello from Laravel!");

// Or using helper
smsapi("9876543210", "Hello from Laravel!");

SmsApi::sendMessage(["9876543210", "9876543211"], "Hello everyone!");

$response = SmsApi::sendMessage("9876543210", "Hello!")
    ->response();

$statusCode = SmsApi::sendMessage("9876543210", "Hello!")
    ->getResponseCode();

$isSuccess = SmsApi::sendMessage("9876543210", "Hello!")
    ->isSuccessful(); // Returns true for 2xx status codes

return [
    // Default country code (added to numbers automatically)
    'country_code' => env('SMS_API_COUNTRY_CODE', '91'),

    // Default gateway to use
    'default' => env('SMS_API_DEFAULT_GATEWAY', 'your_gateway'),

    // HTTP client timeouts
    'timeout' => env('SMS_API_TIMEOUT', 30),
    'connect_timeout' => env('SMS_API_CONNECT_TIMEOUT', 10),

    // Optional message validation
    'validation' => [
        'enabled' => env('SMS_API_VALIDATION_ENABLED', false),
        'max_length' => env('SMS_API_MAX_LENGTH', 1000),
    ],
];

'your_gateway' => [
    'method' => 'POST',  // GET, POST, PUT, PATCH, DELETE
    'url' => 'https://api.smsgateway.com/send',
    'params' => [
        'send_to_param_name' => 'mobile',    // Your provider's "to" param name
        'msg_param_name' => 'message',       // Your provider's "message" param name
        'others' => [
            'api_key' => env('SMS_GATEWAY_KEY'),
            'sender_id' => env('SMS_SENDER_ID'),
        ],
    ],
    'headers' => [
        'Accept' => 'application/json',
    ],
    'add_code' => true,  // Automatically add country code
],

'advanced_gateway' => [
    'method' => 'POST',
    'url' => 'https://api.provider.com/v2/send',
    'params' => [
        'send_to_param_name' => 'recipient',
        'msg_param_name' => 'text',
        'others' => [
            'priority' => 'high',
            'ttl' => 3600,
        ],
    ],
    'headers' => [
        'Authorization' => 'Bearer ' . env('SMS_API_TOKEN'),
        'Content-Type' => 'application/json',
    ],
    'json' => true,              // Send as JSON payload
    'jsonToArray' => true,       // Send single number as array: ["9876543210"]
    'wrapper' => 'data',         // Wrap payload in {"data": {...}}
    'wrapperParams' => [
        'campaign_id' => 'welcome_sms',
    ],
    'add_code' => true,
],

'gateway' => [
    'headers' => [
        'Authorization' => 'Bearer ' . env('SMS_API_TOKEN'),
    ],
],

'gateway' => [
    'headers' => [
        'X-API-Key' => env('SMS_API_KEY'),
    ],
],

'gateway' => [
    'headers' => [
        'Authorization' => 'Basic ' . base64_encode(env('SMS_USERNAME') . ':' . env('SMS_PASSWORD')),
    ],
],

'gateway' => [
    'params' => [
        'others' => [
            'api_key' => env('SMS_API_KEY'),
        ],
    ],
],

'json' => true,

'jsonToArray' => false,

'wrapper' => 'sms',  // Creates: {"sms": [{...}]}

'wrapperParams' => [
    'campaign' => 'summer_sale',
    'priority' => 1,
],

'add_code' => true,  // 9876543210 becomes 919876543210

// Quick send
smsapi("9876543210", "Welcome to our platform!");

// Or
smsapi()->sendMessage("9876543210", "Welcome!");

smsapi("9876543210", "Your OTP is 1234", [
    'template_id' => 'OTP_TEMPLATE',
    'priority' => 'high'
]);

smsapi("9876543210", "Hello", [], [
    'X-Custom-Header' => 'value',
    'X-Request-ID' => uniqid()
]);

smsapi()->gateway('backup_gateway')
    ->sendMessage("9876543210", "Message via backup gateway");

smsapi()->countryCode('1')  // USA
    ->sendMessage("5551234567", "Hello from USA!");

$recipients = ["9876543210", "9876543211", "9876543212"];
smsapi($recipients, "Bulk message to all!");

smsapi()->addWrapperParams([
        'campaign' => 'newsletter',
        'tracking_id' => '12345'
    ])
    ->sendMessage("9876543210", "Newsletter message");

smsapi()
    ->gateway('primary_gateway')
    ->countryCode('91')
    ->addWrapperParams(['campaign' => 'promo'])
    ->sendMessage("9876543210", "Promotional offer!", [
        'template_id' => 'PROMO_123'
    ]);

use Gr8Shivam\SmsApi\SmsApiFacade as SmsApi;

// Basic usage
SmsApi::sendMessage("9876543210", "Hello!");

// With gateway selection
SmsApi::gateway('gateway_name')
    ->sendMessage("9876543210", "Hello!");

// With country code
SmsApi::countryCode('44')  // UK
    ->sendMessage("7911123456", "Hello from UK!");

// Bulk SMS
SmsApi::sendMessage(
    ["9876543210", "9876543211"],
    "Bulk message"
);

// Get response
$response = SmsApi::sendMessage("9876543210", "Test")
    ->response();

// Get status code
$code = SmsApi::sendMessage("9876543210", "Test")
    ->getResponseCode();

// Check success
$success = SmsApi::sendMessage("9876543210", "Test")
    ->isSuccessful();

use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Route notifications for SMS API channel
     */
    public function routeNotificationForSmsApi()
    {
        return $this->phone;  // Return the phone number column
    }
}

namespace App\Notifications;

use Illuminate\Notifications\Notification;
use Gr8Shivam\SmsApi\Notifications\SmsApiChannel;
use Gr8Shivam\SmsApi\Notifications\SmsApiMessage;

class WelcomeNotification extends Notification
{
    public function via($notifiable)
    {
        return [SmsApiChannel::class];
    }

    public function toSmsApi($notifiable)
    {
        return (new SmsApiMessage)
            ->content("Welcome {$notifiable->name}!");
    }
}

$user = User::find(1);
$user->notify(new WelcomeNotification());

public function toSmsApi($notifiable)
{
    return (new SmsApiMessage)
        ->content("Your OTP is: {$this->otp}")
        ->params([
            'template_id' => 'OTP_VERIFY',
            'priority' => 'high'
        ]);
}

public function toSmsApi($notifiable)
{
    return (new SmsApiMessage)
        ->content($this->message)
        ->params(['campaign' => 'marketing'])
        ->headers(['X-Campaign-ID' => '12345']);
}

public function toSmsApi($notifiable)
{
    return (new SmsApiMessage)
        ->content("नमस्ते! Welcome")
        ->unicode();
}

public function toSmsApi($notifiable)
{
    return SmsApiMessage::create("Hello {$notifiable->name}!")
        ->addParam('template_id', 'WELCOME_001')
        ->addHeader('X-Priority', 'high');
}

public function toSmsApi($notifiable)
{
    return "Welcome to our platform!";  // Automatically converted to SmsApiMessage
}

if (send_sms("9876543210", "Hello!")) {
    echo "SMS sent successfully!";
} else {
    echo "SMS failed. Error logged.";
}

$sms = smsapi()->sendMessage("9876543210", "Hello!");

// Get raw response
$response = $sms->response();

// Get status code
$code = $sms->getResponseCode();

// Check if successful
if ($sms->isSuccessful()) {
    // 2xx status code
}

$message = new SmsApiMessage("Your message here");

// Get message length
$length = $message->length();

// Check if empty
if ($message->isEmpty()) {
    // Handle empty message
}

// Estimate SMS segments (for cost calculation)
$segments = $message->estimateSegments();  // Returns 1, 2, 3...

// Get preview
$preview = $message->preview(50);  // First 50 characters

'validation' => [
    'enabled' => true,
    'max_length' => 1000,
],

try {
    $message->validate();
} catch (\InvalidArgumentException $e) {
    // Handle validation error
}

$gateway = $user->isPremium() ? 'premium_gateway' : 'basic_gateway';

smsapi()->gateway($gateway)
    ->sendMessage($user->phone, "Relevant message");

// .env
SMS_API_DEFAULT_GATEWAY=twilio
SMS_API_COUNTRY_CODE=1
SMS_API_TIMEOUT=60
TWILIO_ACCOUNT_SID=your_sid
TWILIO_AUTH_TOKEN=your_token
TWILIO_FROM_NUMBER=+15551234567

// Array of numbers
$recipients = User::where('notify_sms', true)
    ->pluck('phone')
    ->toArray();

smsapi($recipients, "Important announcement!");

// Check logs/laravel.log for:
// [INFO] SMS Gateway Response Code: 200
// [INFO] SMS Gateway Response Body: {...}
// [ERROR] SMS Gateway Response Code: 400
// [ERROR] SMS Gateway Response Body: {...}

'twilio' => [
    'method' => 'POST',
    'url' => 'https://api.twilio.com/2010-04-01/Accounts/' . env('TWILIO_ACCOUNT_SID') . '/Messages.json',
    'params' => [
        'send_to_param_name' => 'To',
        'msg_param_name' => 'Body',
        'others' => [
            'From' => env('TWILIO_FROM_NUMBER'),
        ],
    ],
    'headers' => [
        'Authorization' => 'Basic ' . base64_encode(env('TWILIO_ACCOUNT_SID') . ':' . env('TWILIO_AUTH_TOKEN')),
    ],
    'add_code' => true,
],

smsapi()->gateway('twilio')->sendMessage("5551234567", "Hello from Twilio!");

'msg91' => [
    'method' => 'POST',
    'url' => 'https://control.msg91.com/api/v2/sendsms',
    'params' => [
        'send_to_param_name' => 'to',
        'msg_param_name' => 'message',
        'others' => [
            'authkey' => env('MSG91_AUTH_KEY'),
            'sender' => env('MSG91_SENDER_ID'),
            'route' => '4',
            'country' => '91',
        ],
    ],
    'json' => true,
    'wrapper' => 'sms',
    'add_code' => false,
],

smsapi()->gateway('msg91')->sendMessage("9876543210", "Hello from MSG91!");

'aws_sns' => [
    'method' => 'POST',
    'url' => 'https://sns.us-east-1.amazonaws.com/',
    'params' => [
        'send_to_param_name' => 'PhoneNumber',
        'msg_param_name' => 'Message',
        'others' => [
            'Action' => 'Publish',
        ],
    ],
    'headers' => [
        'Authorization' => 'AWS4-HMAC-SHA256 ...',  // Use AWS SDK for proper signing
    ],
    'add_code' => true,
],

'nexmo' => [
    'method' => 'POST',
    'url' => 'https://rest.nexmo.com/sms/json',
    'params' => [
        'send_to_param_name' => 'to',
        'msg_param_name' => 'text',
        'others' => [
            'api_key' => env('NEXMO_API_KEY'),
            'api_secret' => env('NEXMO_API_SECRET'),
            'from' => env('NEXMO_FROM'),
        ],
    ],
    'json' => true,
    'add_code' => true,
],

'generic_api' => [
    'method' => 'POST',
    'url' => 'https://api.smsprovider.com/v1/send',
    'params' => [
        'send_to_param_name' => 'to',
        'msg_param_name' => 'message',
        'others' => [
            'sender' => 'YourApp',
        ],
    ],
    'headers' => [
        'Authorization' => 'Bearer ' . env('SMS_BEARER_TOKEN'),
        'Content-Type' => 'application/json',
        'Accept' => 'application/json',
    ],
    'json' => true,
    'add_code' => true,
],

use Gr8Shivam\SmsApi\Tests\AbstractTestCase;
use Gr8Shivam\SmsApi\SmsApiFacade as SmsApi;

class MyFeatureTest extends AbstractTestCase
{
    /** @test */
    public function it_sends_sms()
    {
        $this->mockSmsGateway(200, 'Success');

        $response = SmsApi::sendMessage("9876543210", "Test");

        $this->assertEquals(200, $response->getResponseCode());
        $this->assertTrue($response->isSuccessful());
    }
}

$sms = smsapi()->sendMessage("9876543210", "Test");
dd([
    'code' => $sms->getResponseCode(),
    'response' => $sms->response(),
    'success' => $sms->isSuccessful()
]);

   $user->notify(new WelcomeNotification());  // Use ShouldQueue trait
   
bash
php artisan vendor:publish --provider="Gr8Shivam\SmsApi\SmsApiServiceProvider"
bash
php artisan make:notification WelcomeNotification
bash
   php artisan tinker
   >>> smsapi()->sendMessage("YOUR_NUMBER", "Test")->response();
   
bash
php artisan config:clear
php artisan cache:clear