PHP code example of moonlydays / php-kannel

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

    

moonlydays / php-kannel example snippets


use MoonlyDays\Kannel\Client;
use MoonlyDays\Kannel\Enum\HttpMethod;
use MoonlyDays\Kannel\Gateway;
use MoonlyDays\Kannel\Message\SmsBuilder;

$gateway = new Gateway(
    name: 'default',
    sendSmsUrl: 'https://kannel.example.com/cgi-bin/sendsms',
    username: 'user',
    password: 'pass',
    httpMethod: HttpMethod::Post,
);

$client = new Client($gateway);

$sms = (new SmsBuilder())
    ->to('+14155550123')
    ->from('MyBrand')
    ->text('Your verification code is 123456')
    ->build();

$result = $client->send($sms);

if ($result->isAccepted()) {
    // $result->status, $result->kannelMessageId, $result->rawBody
}

use MoonlyDays\Kannel\AdminCredentials;
use MoonlyDays\Kannel\Enum\HttpMethod;
use MoonlyDays\Kannel\Gateway;

$gateway = new Gateway(
    name: 'primary',
    sendSmsUrl: 'https://kannel.example.com/cgi-bin/sendsms',
    username: 'user',
    password: 'pass',
    httpMethod: HttpMethod::Post,
    admin: new AdminCredentials(                       // optional — only if using admin API
        url: 'http://kannel.example.com:13000',
        password: 'admin-secret',
    ),
    defaultSmscId: 'operator-a',                       // optional per-gateway default
    defaultDlrUrl: 'https://your.app/kannel/dlr',      // optional fallback dlr-url
    timeoutSeconds: 30,
);

use MoonlyDays\Kannel\GatewayRegistry;

$registry = new GatewayRegistry(
    gateways: [$primary, $fallback, $operatorA],
    default: 'primary',
);

$client = new Client($registry);

$client->send($sms);                       // default gateway
$client->send($sms, via: 'operatorA');     // named gateway

$client = new Client(
    gateway: $gateway,
    httpClient: $yourPsr18Client,
    requestFactory: $yourPsr17Factory,
    streamFactory: $yourPsr17Factory,
    dispatcher: $yourPsr14Dispatcher,
    logger: $yourPsr3Logger,
);

use MoonlyDays\Kannel\Enum\Coding;
use MoonlyDays\Kannel\Enum\DlrEvent;
use MoonlyDays\Kannel\Enum\MessageClass;

$sms = (new SmsBuilder())
    ->to('+14155550123')
    ->from('ALERT')
    ->text('Héllo 👋')
    ->coding(Coding::Ucs2)                 // GSM-7 | Binary | UCS-2
    ->messageClass(MessageClass::Flash)    // or ->flash() shorthand
    ->dlrMask(DlrEvent::Delivered, DlrEvent::DeliveryFailure, DlrEvent::SmscRejected)
    ->dlrUrl('https://your.app/kannel/dlr?msgid=abc-123')
    ->smsc('operator-a')
    ->priority(1)
    ->validity(1440)                       // minutes
    ->deferred(5)                          // minutes
    ->metaData('smpp', 'service_type', 'VERIFY')
    ->build();

$result = $client->send($sms);

$result->status;             // SendStatus enum — Accepted | Queued | Malformed | ...
$result->httpStatusCode;     // raw HTTP status from Kannel
$result->rawBody;            // raw response body, e.g. "0: Accepted for delivery"
$result->kannelMessageId;    // extracted when present in the body
$result->isAccepted();
$result->isQueued();
$result->isSuccess();        // Accepted or Queued

use MoonlyDays\Kannel\Dlr\DlrUrl;

$dlrUrl = (new DlrUrl('https://your.app/kannel/dlr'))
    ->withQuery('msgid', 'abc-123')         // literal value
    ->withStatus('status')                  // binds to %d
    ->withPhone('to')                       // binds to %p
    ->withTimestamp('ts')                   // binds to %T
    ->withSmscMessageId('smsid')            // binds to %I
    ->build();

$sms = (new SmsBuilder())
    ->to('+14155550123')
    ->text('hello')
    ->dlrUrl($dlrUrl)
    ->dlrMask(DlrEvent::Delivered, DlrEvent::DeliveryFailure)
    ->build();

use MoonlyDays\Kannel\Inbound\DlrBinding;

$binding = new DlrBinding();                          // sensible defaults
$dlrUrl = $binding->toDlrUrl('https://your.app/kannel/dlr');

$sms = (new SmsBuilder())
    ->to('+14155550123')
    ->text('hello')
    ->dlrUrl($dlrUrl)
    ->dlrMask(DlrEvent::Delivered, DlrEvent::DeliveryFailure)
    ->build();

use MoonlyDays\Kannel\Inbound\InboundHandler;

$inbound = new InboundHandler();                      // default bindings
// — or —
$inbound = new InboundHandler(
    dlrBinding: $binding,
    dispatcher: $psr14Dispatcher,                     // fires DlrReceived event
);

// Inside your PSR-7 controller / middleware:
public function handleDlr(ServerRequestInterface $request): ResponseInterface
{
    $dlr = $inbound->receiveDlr($request);
    //  DeliveryReport {
    //      status: DlrEvent,
    //      recipient, sender, smscId, smscMessageId,
    //      receivedAt: ?DateTimeImmutable,
    //      replyText,
    //      raw: array         // all query/body params, for custom fields
    //  }

    // persist, update order state, whatever

    return new Response(200);
}

use MoonlyDays\Kannel\Inbound\InboundHandler;
use MoonlyDays\Kannel\Inbound\MoBinding;

$inbound = new InboundHandler(
    moBinding: new MoBinding(),                       // or customize keys to match your sms-service config
    dispatcher: $psr14Dispatcher,                     // fires MoReceived event
);

public function handleMo(ServerRequestInterface $request): ResponseInterface
{
    $mo = $inbound->receiveMo($request);
    //  IncomingMessage {
    //      from, to, text, binary, udh,
    //      coding: ?Coding,
    //      smscId, receivedAt, raw
    //  }

    return new Response(200);
}

use MoonlyDays\Kannel\Admin\AdminClient;
use MoonlyDays\Kannel\Enum\LogLevel;

$admin = new AdminClient($gateway);

$status = $admin->status();           // GatewayStatus DTO parsed from status.xml
$text   = $admin->statusText();       // raw plain-text status

$admin->suspend();
$admin->isolate();
$admin->resume();
$admin->flushDlr();
$admin->reloadLists();
$admin->setLogLevel(LogLevel::Debug);
$admin->removeSmsc('operator-a');
$admin->addSmsc('operator-a');
$admin->shutdown();
$admin->restart();

$client = new Client($gateway, dispatcher: $dispatcher);
$inbound = new InboundHandler(dispatcher: $dispatcher);

$client = new Client($gateway, logger: $logger);

use MoonlyDays\Kannel\Testing\FakeClient;
use MoonlyDays\Kannel\Enum\SendStatus;
use MoonlyDays\Kannel\Http\SendResult;

$fake = new FakeClient();
$service->sendWelcomeSms($user, $fake);

expect($fake->count())->toBe(1);
expect($fake->sent()[0]->sms->to)->toBe('+14155550123');
expect($fake->sent()[0]->via)->toBeNull();
expect($fake->messages()[0]->text)->toStartWith('Welcome');

$fake->willReturnFor('broken', new SendResult(
    status: SendStatus::InternalError,
    httpStatusCode: 500,
    rawBody: '4: Internal error',
));

$ok  = $fake->send($sms);                   // uses default (accepted)
$bad = $fake->send($sms, via: 'broken');    // returns the configured failure

use MoonlyDays\Kannel\Exception\ExceptionInterface;

try {
    $client->send($sms);
} catch (ExceptionInterface $e) {
    // library-level error
}
bash
composer