PHP code example of beziworld / laravel-twilio

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

    

beziworld / laravel-twilio example snippets


use Beziworld\Twilio\Facades\Twilio;
use Beziworld\Twilio\Messages\TwilioMessage;

// Shortcut
$message = Twilio::sendSms('+48500100200', 'Your code is 1234');

// Builder
$message = Twilio::send(
    TwilioMessage::create('Your order #1001 has shipped')
        ->to('+48500100200')
        ->from('Shop')                                // alphanumeric sender where supported
        ->media('https://example.com/label.pdf')      // MMS
        ->statusCallback(route('twilio.webhooks.status'))
        ->validityPeriod(3600)
);

$message->sid;          // SM...
$message->status;       // MessageStatus::Queued
$message->numSegments;

Twilio::message('SM...');                                   // fetch
Twilio::messages(['To' => '+48500100200'], pageSize: 50);   // first page (MessagePage)
Twilio::allMessages(['DateSent>' => now()->subWeek()])      // LazyCollection over every page
    ->each(fn ($message) => ...);
Twilio::redact('SM...');                                    // remove the body, keep metadata
Twilio::deleteMessage('SM...');

$message = Twilio::send(
    TwilioMessage::create('Reminder: your visit is tomorrow at 10:00')
        ->to('+48500100200')
        ->messagingService('MG...')        // or TWILIO_MESSAGING_SERVICE_SID
        ->sendAt($visit->starts_at->subDay())
);

Twilio::cancelScheduled($message->sid);

// Free-form message (inside the 24 hour customer service window)
Twilio::sendWhatsApp('+48500100200', 'Your table is ready');

// Approved content template (send(TwilioMessage::whatsapp('Your invoice')->to('+48500100200')->media('https://example.com/invoice.pdf'));

use Beziworld\Twilio\Enums\VerificationChannel;

Twilio::startVerification('+48500100200');                                   // SMS
Twilio::startVerification('+48500100200', VerificationChannel::WhatsApp, ['Locale' => 'pl']);
Twilio::startVerification('[email protected]', 'email');

if (Twilio::verifyCode('+48500100200', $request->input('code'))) {
    // approved
}

$check = Twilio::checkVerification('123456', to: '+48500100200');   // full Verification object
$check->status;                                                        // VerificationStatus::Approved / Pending

$info = Twilio::lookup('+48500100200', ['line_type_intelligence']);

$info->valid;                                   // bool
$info->phoneNumber;                             // +48500100200
$info->isMobile();                              // LineType::Mobile
$info->lineTypeIntelligence?->carrierName;
$info->package('sms_pumping_risk');             // raw data of any other requested package

Twilio::lookup('500100200', countryCode: 'PL');   // national format

$call = Twilio::call('+48500100200', twiml: '<Response><Say>Your order has shipped.</Say></Response>');
$call = Twilio::call('+48500100200', url: 'https://example.com/twiml/greeting', options: ['Timeout' => 20]);
Twilio::hangup($call->sid);

$balance = Twilio::balance();   // Balance: ->balance ("12.34"), ->currency ("USD"), ->amount()

Twilio::request('GET', '/Accounts/{AccountSid}/IncomingPhoneNumbers.json', ['PageSize' => 20]);
Twilio::request('POST', 'https://messaging.twilio.com/v1/Services', ['FriendlyName' => 'Shop']);

   use Beziworld\Twilio\Events\MessageReceived;
   use Beziworld\Twilio\Events\MessageStatusUpdated;

   Event::listen(function (MessageStatusUpdated $event) {
       SmsLog::where('sid', $event->callback->messageSid)->update([
           'status' => $event->callback->statusValue,
           'error_code' => $event->callback->errorCode,
       ]);
   });

   Event::listen(function (MessageReceived $event) {
       $message = $event->message;   // IncomingMessage: from, to, body, media, profileName, waId, ...

       if (strtoupper(trim($message->body)) === 'STATUS') {
           $event->reply('Your order is on its way.');   // TwiML reply
       }
   });
   

Route::post('twilio/voice', VoiceController::class)->middleware('twilio.signature');

use Beziworld\Twilio\Messages\TwilioMessage;
use Illuminate\Notifications\Notification;

class OrderShipped extends Notification
{
    public function via(object $notifiable): array
    {
        return ['twilio'];
    }

    public function toTwilio(object $notifiable): TwilioMessage|string
    {
        return TwilioMessage::whatsapp()
            ->template('HX...', ['1' => $this->order->number]);
    }
}

public function routeNotificationForTwilio(): ?string
{
    return $this->phone;   // E.164, e.g. +48500100200
}

'connections' => [
    'default' => [
        'account_sid' => env('TWILIO_ACCOUNT_SID'),
        'auth_token' => env('TWILIO_AUTH_TOKEN'),
        'from' => env('TWILIO_FROM'),
    ],
    'marketing' => [   // another account or a subaccount
        'account_sid' => env('TWILIO_MARKETING_ACCOUNT_SID'),
        'auth_token' => env('TWILIO_MARKETING_AUTH_TOKEN'),
        'messaging_service_sid' => env('TWILIO_MARKETING_MESSAGING_SERVICE_SID'),
    ],
],

Twilio::connection('marketing')->sendSms('+48500100200', 'Spring sale!');

// Credentials stored per tenant
$client = Twilio::using([
    'account_sid' => $tenant->twilio_sid,
    'auth_token' => decrypt($tenant->twilio_token),
    'from' => $tenant->twilio_from,
]);

// Webhooks of tenant accounts
Twilio::resolveAuthTokenUsing(
    fn (string $accountSid): ?string => Tenant::firstWhere('twilio_sid', $accountSid)?->twilio_token
);

use Beziworld\Twilio\Exceptions\ApiException;

try {
    Twilio::sendSms($phone, $text);
} catch (ApiException $e) {
    if ($e->errorCode() === 21211) {
        // invalid "To" number
    }
}

Http::fake([
    'api.twilio.com/*' => Http::response(['sid' => 'SM123', 'status' => 'queued'], 201),
]);

// ... code that sends a message

Http::assertSent(fn ($request) => ($request->data()['To'] ?? null) === '+48500100200');