PHP code example of tekkenking / swissecho

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

    

tekkenking / swissecho example snippets


'sms' => [
    'gateway_options' => [ /* ... */ ],
    'places' => [
        'nga' => [                          // Nigeria
            'gateway'   => 'nigerianbulksms',
            'phonecode' => '234'
        ],
        'gha' => [                          // Ghana
            'gateway'   => 'wirepick',
            'phonecode' => '233'
        ],
        'aus' => [                          // Australia
            'gateway'   => 'smsbroadcast',
            'phonecode' => '61'
        ],
        'nzl' => [                          // New Zealand
            'gateway'   => 'tnz',
            'phonecode' => '64'
        ],
    ]
],

'sms' => [
    'default_place' => 'aus',  // SMS will default to Australia
    'gateway_options' => [ /* ... */ ],
    'places' => [ /* ... */ ],
],



namespace App\Sms\Gateways\MyProvider;

use Tekkenking\Swissecho\Routes\Sms\Gateways\BaseGateway;

class MyProvider extends BaseGateway
{
    /**
     * Build and return the request payload that will be passed to send().
     *
     * Available properties (populated by BaseGateway from the message builder):
     *   $this->to      — array of recipient phone numbers
     *   $this->sender  — sender ID / name
     *   $this->body    — the SMS message text
     *   $this->config  — your gateway's config block from config/swissecho.php
     *
     * @return mixed  Any value you like — it will be passed directly to send().
     *                Typically a URL string, an array, or a Guzzle request object.
     */
    public function init(): mixed
    {
        // Example: build a query-string URL
        $url  = $this->config['url'];
        $url .= '?api_key='   . $this->config['auth']['api_key'];
        $url .= '&from='      . $this->sender;
        $url .= '&to='        . implode(',', $this->to);
        $url .= '&message='   . urlencode($this->body);

        return $url;
    }

    /**
     * Receive the value returned by init(), make the HTTP call,
     * and return a configured cURL handle.
     *
     * @param  mixed $data  Whatever init() returned.
     * @return \CurlHandle|bool  A ready-to-execute cURL handle.
     *                           Swissecho calls curl_exec() on it automatically.
     */
    public function send($data): \CurlHandle|bool
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // ⚠️ Only disable in local/testing environments; keep true in production
        return $ch;
    }
}

use App\Sms\Gateways\MyProvider\MyProvider; // ← import your class

'routes_options' => [
    'sms' => [
        'gateway_options' => [

            // ... existing gateways ...

            'myprovider' => [               // ← the key becomes the gateway "name"
                'class'  => MyProvider::class,
                'url'    => env('MYPROVIDER_URL'),
                'auth'   => [
                    'api_key' => env('MYPROVIDER_API_KEY'),
                ],
                // add any other keys your gateway needs — they will all be
                // available inside your class as $this->config['...']
            ],
        ],
    ],
],

// Direct / fluent sending
swissecho()->gateway('myprovider')->quick('2348012345678', 'Hello!');

// Or inside a route callback
swissecho()->route('sms', function ($ms) {
    return $ms->to('2348012345678')
              ->content('Your OTP is 9988')
              ->gateway('myprovider');
})->go();

// Or inside a Laravel Notification
public function toSms($notifiable): SwissechoMessage
{
    return (new SwissechoMessage())
        ->line('Your order has shipped!')
        ->gateway('myprovider');
}

'places' => [
    'zaf' => [                  // South Africa, for example
        'gateway'   => 'myprovider',
        'phonecode' => '27',
    ],
],

// 1. Global helper function
swissecho()

// 2. Laravel Facade
use Tekkenking\Swissecho\Facades\Swissecho;

Swissecho::

// 3. From the container
app('swissecho')

swissecho()->quick('2348012345678', 'Your OTP code is 1234');

swissecho()->gateway('vonage')->quick('2348012345678', 'Your OTP code is 1234');

swissecho()->route('sms', function ($ms) {
    return $ms->to('2348012345678, 2348098765432')  // comma-separated recipients
              ->content('Your order has been shipped!')
              ->line('Track it at https://example.com/track');  // appends a new line
              // ->gateway('routemobile')   // override gateway inside callback
              // ->sender('MyBrand')        // override sender inside callback
})
->to('2348011111111')       // optional: additional/fallback recipient
->sender('MyApp')           // optional: override sender
->gateway('termii')         // optional: override gateway
->go();                     // 🚀 sends the message

$sw = swissecho();
$sw->gateway('termii');
$sw->to = '2348012345678';
$sw->sender = 'MyApp';
$sw->message = 'The world is a beautiful place created by GOD';
$sw->go();

swissecho()->route('whatsapp', function ($ms) {
    return $ms->to('2348012345678')
              ->content('Hello from WhatsApp!');
})->go();

swissecho()->message('Deployment finished ✅')
    ->route('slack')
    ->go();

swissecho()->message('Hello team!')
    ->to('#alerts')
    ->route('slack')
    ->go();

swissecho()->message('Server restarted 🔄')
    ->to('123456789')   // your Telegram chat_id
    ->route('telegram')
    ->go();

swissecho()->route('voice', function ($ms) {
    return $ms->to('2348012345678')
              ->content('Your OTP is 5 6 7 8');
})->gateway('termii')->go();



namespace App\Notifications;

use Illuminate\Notifications\Notification;
use Tekkenking\Swissecho\SwissechoMessage;

class OrderShipped extends Notification
{
    /**
     * The delivery channels.
     */
    public function via($notifiable): array
    {
        return ['swissecho'];
    }

    /**
     * (Optional) Tell Swissecho which routes to use.
     * If omitted, defaults to ['sms', 'slack', 'whatsapp', 'telegram'].
     */
    public function swissechoRoutes($notifiable): array
    {
        return ['sms'];
    }

    /**
     * Build the SMS message.
     * Method name follows the pattern: to{Route}  →  toSms, toVoice, toWhatsapp, toSlack, toTelegram
     */
    public function toSms($notifiable): SwissechoMessage
    {
        return (new SwissechoMessage())
            ->line('Hi ' . $notifiable->name . '!')
            ->line('Your order has been shipped.')
            ->sender('MyStore');
    }
}

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Option A: Have a `phone` attribute on the model (e.g. column in DB).
     * Swissecho checks $notifiable->phone automatically.
     */

    /**
     * Option B: Define this method for custom logic.
     */
    public function routeNotificationPhone(): string
    {
        return $this->mobile_number;
    }

    /**
     * (Optional) Slack channel for this user.
     */
    public function routeNotificationSlackChannel(): string
    {
        return '#team-alerts';
    }

    /**
     * (Optional) Telegram chat_id for this user.
     */
    public function routeNotificationTelegramChatId(): string
    {
        return $this->telegram_chat_id;
    }

    /**
     * (Optional) Tell Swissecho the recipient's country for geo-routing.
     * Return a 3-letter ISO code matching a key in config places.
     */
    public function routeNotificationPlace(): string
    {
        return 'nga'; // Nigeria
    }
}

$user->notify(new OrderShipped());

// app/Providers/EventServiceProvider.php
protected $listen = [
    \Tekkenking\Swissecho\Events\AfterSend::class => [
        \App\Listeners\LogSmsDelivery::class,
    ],
];


// app/Listeners/LogSmsDelivery.php

namespace App\Listeners;

use Tekkenking\Swissecho\Events\AfterSend;

class LogSmsDelivery
{
    public function handle(AfterSend $event): void
    {
        // $event->formattedResponse['status']   — true/false
        // $event->formattedResponse['to']       — recipient array
        // $event->formattedResponse['gateway']  — which gateway was used
        // $event->insightPayload['request']     — raw request payload
        // $event->insightPayload['response']    — raw response from provider

        logger()->info('SMS sent', $event->formattedResponse);
    }
}

'{$gateway}' => [
    // ...
    'webhook' => [
        'secret' => env('TERMI_WEBHOOK_SECRET', 'your-secret-here'),
        'handle' => 'webhook'   // method name on the gateway class
    ]
],

addCountryCodeToPhoneNumber('08012345678', '234');
// Returns: "2348012345678"

removeCountryCodeFromPhoneNumber('2348012345678', '234');
// Returns: "8012345678"

convertPhoneNumberToArray('2348012345678, 2348098765432');
// Returns: ["2348012345678", "2348098765432"]
bash
php artisan vendor:publish --tag=swissecho-config
dotenv
MYPROVIDER_URL=https://api.myprovider.com/send
MYPROVIDER_API_KEY=your_api_key_here