PHP code example of webimpian / smsniaga-php

1. Go to this page and download the library: Download webimpian/smsniaga-php 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/ */

    

webimpian / smsniaga-php example snippets


use Webimpian\SmsNiaga\SmsNiaga;

$sms = new SmsNiaga('your-api-token');

$result = $sms->send('012-345 6789', 'Your order #1024 has shipped.');

$result->uuid;         // Use it to get the delivery report
$result->totalCharge;  // 0.1 (RM)

$sms = new SmsNiaga(
    token: 'your-api-token',
    timeout: 30,          // Optional. Seconds to wait for a response
    connectTimeout: 10,   // Optional. Seconds to wait for a connection
    httpClient: null,     // Optional. Your own Guzzle client, for a proxy, logging or tests
);

// config/services.php
'smsniaga' => ['token' => env('SMSNIAGA_TOKEN')],

// AppServiceProvider::register()
$this->app->singleton(SmsNiaga::class, fn () => new SmsNiaga((string) config('services.smsniaga.token')));

$sms->send('012-345 6789', 'Your verification code is 482913.');

$sms->send(['0123456789', '+60 19-876 5432'], 'Branch closes at 6pm today.');

$sms->send('0123456789', 'Your parcel is out for delivery.', senderId: 'MYSHOP');
// Recipient sees: RM0 MYSHOP: Your parcel is out for delivery.

$preview = $sms->messages()->preview('0123456789', 'Your order has shipped.', senderId: 'MYSHOP');

$preview->message;       // "RM0 MYSHOP: Your order has shipped." as the recipient sees it
$preview->charCount;     // 35
$preview->messagePages;  // 1 credit per recipient
$preview->totalCharge;   // 0.1 (RM)

$result = $sms->messages()->sendBulk($phones, 'Raya sale: 30% off this weekend.');

$result->totalNumbers();  // Recipients who were sent the message
$result->totalCharge();   // Total cost in RM
$result->uuids();         // One message UUID per batch

if ($result->hasFailures()) {
    $retryLater = $result->failedNumbers();
}

use Webimpian\SmsNiaga\Support\SmsLength;

$length = SmsLength::of('Your order #1024 has shipped.', 'MYSHOP');

$length->type;         // "ascii"
$length->characters;   // 41, including "RM0 MYSHOP: "
$length->credits;      // 1
$length->remaining();  // 119 characters left before the next credit

$report = $sms->messages()->report($result->uuid);

$report->isFullyDelivered();  // true when every recipient has it
$report->isComplete();        // true when no recipient is still pending

foreach ($report->failed() as $recipient) {
    echo "{$recipient->phone}: {$recipient->description()}";
    // 60123456789: Absent subscriber.
}

$balance = $sms->balance();

$balance->amount;       // 36.8
echo $balance;          // RM36.80
$balance->isBelow(20);  // true when it's time to top up

$shop = $sms->senderIds()->create('MYSHOP', 'Online store');
$sms->senderIds()->setDefault($shop->uuid);

$vip = $sms->groups()->firstOrCreate('VIP Customers');

$aisyah = $sms->subscribers()->create('012-345 6789', name: 'Aisyah', groupUuid: $vip->uuid);
$sms->subscribers()->update($aisyah->uuid, email: '[email protected]');

use Webimpian\SmsNiaga\Support\DeliveryReportCode;

DeliveryReportCode::describe('071');     // "Subscriber opted out from receiving SMS."
DeliveryReportCode::isDelivered('000');  // true
DeliveryReportCode::isPending('111');    // true
DeliveryReportCode::all();               // Every code and its description

use Webimpian\SmsNiaga\Exceptions\ConnectionException;
use Webimpian\SmsNiaga\Exceptions\SmsNiagaException;
use Webimpian\SmsNiaga\Exceptions\ValidationException;

try {
    $sms->send($phone, $message, senderId: 'MYSHOP');
} catch (ValidationException $e) {
    // SMS Niaga rejected the request, e.g. an unknown sender ID
} catch (ConnectionException $e) {
    // Timeout or network failure. The SMS may already have been sent, so check before you retry.
} catch (SmsNiagaException $e) {
    // Anything else
}

use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

$mock = new MockHandler([
    new Response(200, [], json_encode(['data' => ['uuid' => 'test-uuid', 'numbers' => ['60123456789'], 'total_charge' => 1000]])),
]);

$sms = new SmsNiaga('test-token', httpClient: new Client(['handler' => HandlerStack::create($mock)]));
bash
composer