PHP code example of citricguy / twilio-laravel

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

    

citricguy / twilio-laravel example snippets


// Uses the 'from' parameter directly
Twilio::sendMessage('+1234567890', 'Message with custom from', ['from' => '+15551234567']);

// Uses the messaging service configured in .env / config
Twilio::sendMessage('+1234567890', 'Message via messaging service');

// Uses the default configuration from .env
Twilio::sendMessage('+1234567890', 'Message with default sender');

// In config/twilio-laravel.php
'notifications' => [
    'channel_name' => 'twilioSms',     // SMS notifications channel
    'call_channel_name' => 'twilioCall',  // Call notifications channel
],

use Citricguy\TwilioLaravel\Facades\Twilio;

// Basic usage
Twilio::sendMessage('+1234567890', 'Hello from Twilio Laravel!');

// With custom from number
Twilio::sendMessage(
    '+1234567890',
    'Hello from a different number!',
    ['from' => '+1987654321']
);

// Send immediately (bypass queue)
Twilio::sendMessageNow('+1234567890', 'This is urgent!');

// Send MMS with media
Twilio::sendMessage(
    '+1234567890',
    'Check out this image!',
    ['mediaUrls' => ['https://example.com/image.jpg']]
);

// With status callback URL
Twilio::sendMessage(
    '+1234567890',
    'Track message delivery!',
    ['statusCallback' => 'https://yourdomain.com/webhooks/twilio/status-updates']
);

// Custom queue options
Twilio::sendMessage(
    '+1234567890',
    'Hello from a custom queue!',
    [
        'queue' => 'high-priority',
        'delay' => 30 // delay in seconds
    ]
);

// Disable queuing to send all messages immediately
'queue_messages' => false,

// Set a custom queue name
'queue_name' => 'twilio',

use Citricguy\TwilioLaravel\Facades\Twilio;

// Basic voice call - With custom from number
Twilio::makeCall(
    '+1234567890',
    'https://example.com/twiml',
    ['from' => '+1987654321']
);

// Make an immediate call (bypass queue)
Twilio::makeCallNow('+1234567890', 'https://example.com/twiml');

// With status callback URL
Twilio::makeCall(
    '+1234567890',
    'https://example.com/twiml',
    ['statusCallback' => 'https://yourdomain.com/webhooks/twilio/call-status']
);

// With status callback events
Twilio::makeCall(
    '+1234567890',
    'https://example.com/twiml',
    [
        'statusCallback' => 'https://yourdomain.com/webhooks/twilio/call-status',
        'statusCallbackEvent' => ['initiated', 'ringing', 'answered', 'completed']
    ]
);

// Enable call recording
Twilio::makeCall(
    '+1234567890',
    'https://example.com/twiml',
    ['record' => true]
);

// Custom queue options
Twilio::makeCall(
    '+1234567890',
    'https://example.com/twiml',
    [
        'queue' => 'high-priority',
        'delay' => 30 // delay in seconds
    ]
);

// High-level webhook categorization
$event->isVoiceWebhook();  // Any voice-related webhook
$event->isMessageWebhook(); // Any message-related webhook

// Inbound communication
$event->isInboundMessage(); // Any incoming message (SMS or MMS)
$event->isInboundSms();     // Specifically SMS
$event->isInboundMms();     // Specifically MMS
$event->isInboundVoiceCall(); // Incoming voice call
  
// Status updates
$event->isMessageStatusUpdate(); // Message status updates
$event->isVoiceStatusUpdate();   // Voice call status updates
$event->isStatusUpdate();        // Any status update
  
// Get the specific status value
$event->getStatusType(); // Returns normalized lowercase status value

use Citricguy\TwilioLaravel\Events\TwilioWebhookReceived;

protected $listen = [
    TwilioWebhookReceived::class => [
        App\Listeners\HandleTwilioWebhook::class,
    ],
];

namespace App\Listeners;

use Citricguy\TwilioLaravel\Events\TwilioWebhookReceived;
use Illuminate\Support\Facades\Log;

class HandleTwilioWebhook
{
    public function handle(TwilioWebhookReceived $event)
    {
        // Voice call handling - 

protected $listen = [
    \Citricguy\TwilioLaravel\Events\TwilioMessageSending::class => [
        \App\Listeners\ValidateMessageBeforeSending::class,
    ],
    \Citricguy\TwilioLaravel\Events\TwilioMessageSent::class => [
        \App\Listeners\LogTwilioMessageSent::class,
    ],
    \Citricguy\TwilioLaravel\Events\TwilioMessageQueued::class => [
        \App\Listeners\LogTwilioMessageQueued::class,
    ],
    \Citricguy\TwilioLaravel\Events\TwilioWebhookReceived::class => [
        \App\Listeners\HandleTwilioWebhook::class,
    ],
];

namespace App\Listeners;

use Citricguy\TwilioLaravel\Events\TwilioMessageSending;
use App\Models\BlockedNumber;
use App\Services\PhoneNumberService;

class ValidateMessageBeforeSending
{
    protected $phoneNumberService;
    
    public function __construct(PhoneNumberService $phoneNumberService)
    {
        $this->phoneNumberService = $phoneNumberService;
    }
    
    public function handle(TwilioMessageSending $event)
    {
        $to = $event->to;
        
        // Example 1: Check against database of blocked numbers
        if (BlockedNumber::where('phone_number', $to)->exists()) {
            return $event->cancel('Number is in blocked list');
        }
        
        // Example 2: Check area code restrictions
        $areaCode = $this->phoneNumberService->getAreaCode($to);
        $blockedAreaCodes = ['555', '900'];
        
        if (in_array($areaCode, $blockedAreaCodes)) {
            return $event->cancel('Area code is not allowed');
        }
        
        // Example 3: Check for international numbers if not allowed
        if (!config('app.allow_international_sms') && !$this->phoneNumberService->isDomestic($to)) {
            return $event->cancel('International messages are disabled');
        }
        
        // Example 4: Rate limiting
        if ($this->phoneNumberService->isRateLimited($to)) {
            return $event->cancel('Rate limit exceeded for this number');
        }
    }
}

namespace App\Listeners;

use Citricguy\TwilioLaravel\Events\TwilioMessageQueued;
use App\Models\SmsMessage;
use Illuminate\Support\Facades\Log;

class LogTwilioMessageQueued
{
    public function handle(TwilioMessageQueued $event)
    {
        // Example 1: Record in database for tracking/analytics
        SmsMessage::create([
            'to' => $event->to,
            'message' => $event->message,
            'status' => 'queued',
            'segments' => $event->segmentsCount,
            'queued_at' => now(),
        ]);
        
        // Example 2: Add custom logging
        Log::channel('sms')->info('SMS queued for sending', [
            'operation' => 'message-queued',
        ]);
        
        // Example 3: Notify admin of high-priority messages
        if (!empty($event->options['priority']) && $event->options['priority'] === 'high') {
            // Send notification to admin dashboard
            event(new \App\Events\HighPrioritySmsQueued($event->to, $event->message));
        }
    }
}

namespace App\Listeners;

use Citricguy\TwilioLaravel\Events\TwilioMessageSent;
use App\Models\SmsMessage;

class LogTwilioMessageSent
{
    public function handle(TwilioMessageSent $event)
    {
        // Example 1: Update message status in database
        SmsMessage::updateOrCreate(
            ['to' => $event->to, 'status' => 'queued'],
            [
                'message_sid' => $event->messageSid,
                'status' => $event->status,
                'segments' => $event->segmentsCount,
                'sent_at' => now(),
            ]
        );
        
        // Reconcile final Twilio usage before billing. segmentsCount can be an estimate.

        // Example 3: Record analytics
        app('analytics')->trackEvent('sms_sent', [
            'to' => $event->to,
            'segments' => $event->segmentsCount,
            'status' => $event->status
        ]);
    }
}

protected $listen = [
    \Citricguy\TwilioLaravel\Events\TwilioCallSending::class => [
        \App\Listeners\ValidateCallBeforeInitiating::class,
    ],
    \Citricguy\TwilioLaravel\Events\TwilioCallSent::class => [
        \App\Listeners\LogTwilioCallSent::class,
    ],
    \Citricguy\TwilioLaravel\Events\TwilioCallQueued::class => [
        \App\Listeners\LogTwilioCallQueued::class,
    ],
];

namespace App\Listeners;

use Citricguy\TwilioLaravel\Events\TwilioCallSending;
use App\Models\BlockedNumber;
use App\Services\PhoneNumberService;

class ValidateCallBeforeInitiating
{
    protected $phoneNumberService;
    
    public function __construct(PhoneNumberService $phoneNumberService)
    {
        $this->phoneNumberService = $phoneNumberService;
    }
    
    public function handle(TwilioCallSending $event)
    {
        $to = $event->to;
        
        // Example: Check against database of blocked numbers
        if (BlockedNumber::where('phone_number', $to)->exists()) {
            return $event->cancel('Number is in blocked list');
        }
        
        // Example: Check time restrictions
        $currentHour = now()->hour;
        if ($currentHour < 8 || $currentHour > 20) {
            return $event->cancel('Calls are only allowed between 8 AM and 8 PM');
        }
    }
}

namespace App\Listeners;

use Citricguy\TwilioLaravel\Events\TwilioWebhookReceived;
use App\Models\SmsMessage;
use App\Models\Conversation;

class HandleTwilioWebhook
{
    public function handle(TwilioWebhookReceived $event)
    {
        // Example 1: Handle incoming SMS
        if ($event->isInboundSms()) {
            // Store the incoming message
            $incomingSms = [
                'from' => $event->payload['From'],
                'body' => $event->payload['Body'],
                'sid' => $event->payload['MessageSid'],
            ];
            
            // Create or update a conversation
            $conversation = Conversation::firstOrCreate(['phone_number' => $incomingSms['from']]);
            $conversation->messages()->create([
                'direction' => 'inbound',
                'body' => $incomingSms['body'],
                'message_sid' => $incomingSms['sid'],
            ]);
            
            // Potentially trigger automated response
            // ...
        }
        
        // Example 2: Handle delivery status updates
        if ($event->isMessageStatusUpdate()) {
            $messageSid = $event->payload['MessageSid'];
            $status = $event->getStatusType();
            
            // Update message status in your database
            SmsMessage::where('message_sid', $messageSid)
                ->update([
                    'status' => $status,
                    'status_updated_at' => now(),
                ]);
            
            // If it's a failure, you might want to alert someone
            if (in_array($status, ['failed', 'undelivered'])) {
                // Notify admins or trigger a retry
                // ...
            }
        }
        
        // Example 3: Handle voice calls with TwiML response
        if ($event->isInboundVoiceCall()) {
            // Generate TwiML response
            return response(
                '<?xml version="1.0" encoding="UTF-8"

// In app/Providers/EventServiceProvider.php
protected $listen = [
    \Citricguy\TwilioLaravel\Events\TwilioWebhookReceived::class => [
        \App\Listeners\TwilioWebhookHandler::class,
    ],
];

// app/Listeners/TwilioWebhookHandler.php
namespace App\Listeners;

use Citricguy\TwilioLaravel\Events\TwilioWebhookReceived;

class TwilioWebhookHandler
{
    public function handle(TwilioWebhookReceived $event)
    {
        if ($event->isInboundVoiceCall()) {
            // Voice calls 

namespace App\Listeners;

use Citricguy\TwilioLaravel\Events\TwilioWebhookReceived;
use Illuminate\Contracts\Queue\ShouldQueue;

class ProcessMessageStatusUpdates implements ShouldQueue
{
    public function handle(TwilioWebhookReceived $event)
    {
        if ($event->isMessageStatusUpdate()) {
            // This will run in the background
            // Process the status update...
        }
    }
}

protected $listen = [
    \Citricguy\TwilioLaravel\Events\TwilioWebhookReceived::class => [
        \App\Listeners\TwilioImmediateResponseHandler::class,  // Not queued
        \App\Listeners\ProcessMessageStatusUpdates::class,     // Queued
    ],
];

namespace App\Listeners;

use App\Jobs\ProcessSmsMessage;
use Citricguy\TwilioLaravel\Events\TwilioWebhookReceived;

class TwilioWebhookHandler
{
    public function handle(TwilioWebhookReceived $event)
    {
        if ($event->isInboundVoiceCall()) {
            // Handle voice calls immediately
            return $this->generateVoiceResponse();
        }
        
        if ($event->isInboundSms()) {
            // Queue the heavy processing
            ProcessSmsMessage::dispatch($event->payload)
                ->onQueue('twilio-webhooks');
        }
    }
    
    private function generateVoiceResponse()
    {
        // Generate and return TwiML
    }
}

// In EventServiceProvider.php
protected $listen = [
    \Citricguy\TwilioLaravel\Events\TwilioWebhookReceived::class => [
        \App\Listeners\TwilioVoiceHandler::class,
        \App\Listeners\TwilioMessageHandler::class,
    ],
];

// In TwilioVoiceHandler.php
public function handle(TwilioWebhookReceived $event)
{
    if (!$event->isVoiceWebhook()) {
        return; // Only process voice webhooks
    }
    
    if ($event->isInboundVoiceCall()) {
        return $this->generateTwimlResponse();
    }
}

// In TwilioMessageHandler.php (could implement ShouldQueue)
public function handle(TwilioWebhookReceived $event)
{
    if (!$event->isMessageWebhook()) {
        return; // Only process message webhooks
    }
    
    // Process message webhooks...
}

// In app/Services/TwilioWebhookService.php
namespace App\Services;

use Citricguy\TwilioLaravel\Events\TwilioWebhookReceived;

class TwilioWebhookService
{
    public function handleVoiceCall(array $payload)
    {
        // Process voice call and return TwiML
        return response($this->generateTwiml(), 200, ['Content-Type' => 'text/xml']);
    }
    
    public function processIncomingSms(array $payload)
    {
        // Process SMS...
    }
    
    private function generateTwiml()
    {
        // Generate TwiML
    }
}

// In your listener
public function handle(TwilioWebhookReceived $event)
{
    $service = app(TwilioWebhookService::class);
    
    if ($event->isInboundVoiceCall()) {
        return $service->handleVoiceCall($event->payload);
    }
    
    if ($event->isInboundSms()) {
        $service->processIncomingSms($event->payload);
    }
}

use Citricguy\TwilioLaravel\Facades\Twilio;

// In your test method or setUp
Twilio::fake();

// Now any calls to Twilio::sendMessage() won't actually call the Twilio API
Twilio::sendMessage('+1234567890', 'Test message');

// You can make assertions on the messages that would have been sent
Twilio::assertSent(function ($message) {
    return $message->to === '+1234567890' &&
           $message->body === 'Test message';
});

// Assert a message was sent to a specific number
Twilio::assertSentTo('+1234567890');

// Assert a specific number of messages were sent
Twilio::assertSentCount(1);

// Assert no messages were sent
Twilio::assertNothingSent();

use Citricguy\TwilioLaravel\Facades\Twilio;

// In your test method or setUp
Twilio::fake();

// Now any calls to Twilio::makeCall() won't actually call the Twilio API
Twilio::makeCall('+1234567890', 'https://example.com/twiml');

// You can make assertions on the calls that would have been made
Twilio::assertCallMade(function ($call) {
    return $call->to === '+1234567890' &&
           $call->url === 'https://example.com/twiml';
});

// Assert a call was made to a specific number
Twilio::assertCalledTo('+1234567890');

// Assert a specific number of calls were made
Twilio::assertCallCount(1);

// Assert no calls were made
Twilio::assertNoCalls();

// In your test
public function test_can_handle_voice_call()
{
    // Create a test payload
    $payload = [
        'CallSid' => 'CA123456',
        'From' => '+12345678901',
        'CallStatus' => 'ringing',
    ];
    
    // Create the event
    $event = new TwilioWebhookReceived($payload);
    
    // Dispatch the event and get responses
    $responses = Event::dispatch($event);
    
    // Check if a TwiML response was returned
    $this->assertInstanceOf(\Illuminate\Http\Response::class, $responses[0]);
    $this->assertStringContainsString('<Response>', $responses[0]->getContent());
}

public function test_webhook_endpoint_processes_sms()
{
    // Disable signature validation for testing
    config(['twilio-laravel.validate_webhook' => false]);
    
    // Mock the event listener to verify it gets called
    Event::fake([TwilioWebhookReceived::class]);
    
    // Send a request to the webhook endpoint
    $response = $this->postJson(config('twilio-laravel.webhook_path'), [
        'MessageSid' => 'SM123456',
        'From' => '+12345678901',
        'Body' => 'Test message',
    ]);
    
    // Verify response
    $response->assertStatus(202);
    
    // Verify event was dispatched with correct payload
    Event::assertDispatched(TwilioWebhookReceived::class, function ($event) {
        return $event->isInboundSms() && 
               $event->payload['From'] === '+12345678901';
    });
}

public function test_voice_call_returns_twiml()
{
    // Disable signature validation for testing
    config(['twilio-laravel.validate_webhook' => false]);
    
    // Use the real event dispatcher so listeners can return a response
    
    // Send a voice webhook
    $response = $this->postJson(config('twilio-laravel.webhook_path'), [
        'CallSid' => 'CA123456',
        'From' => '+12345678901',
        'CallStatus' => 'ringing',
    ]);
    
    // For voice calls, we should get a TwiML response
    $response->assertStatus(200);
    $response->assertHeader('Content-Type', 'text/xml');
    $response->assertSee('<Response>');
}

public function routeNotificationForTwilioSms($notification)
{
    return $this->phone_number; // Replace with your phone field
}

namespace App\Notifications;

use Citricguy\TwilioLaravel\Notifications\TwilioSmsMessage;
use Illuminate\Notifications\Notification;

class VerificationCodeNotification extends Notification
{
    protected $code;

    public function __construct($code)
    {
        $this->code = $code;
    }

    public function via($notifiable)
    {
        return ['twilioSms'];
    }

    public function toTwilioSms($notifiable)
    {
        return (new TwilioSmsMessage)
            ->content("Your verification code is {$this->code}")
            ->from('+1234567890'); // Optional custom sender
    }
}

$user->notify(new VerificationCodeNotification('1234'));

public function toTwilioSms($notifiable)
{
    return (new TwilioSmsMessage)
        ->content('Check out this image!')
        ->mediaUrls(['https://example.com/image.jpg']);
}

public function toTwilioSms($notifiable)
{
    return (new TwilioSmsMessage)
        ->content('Your message here')
        ->from('+1234567890')                                // Custom sender number
        ->mediaUrls(['https://example.com/image.jpg'])       // For MMS
        ->statusCallback('https://example.com/webhook/status') // Status callback URL
        ->options([                                         // Additional custom options
            'delay' => 30, // delay in seconds
            'queue' => 'high-priority',
        ]);
}

public function toTwilioSms($notifiable)
{
    return "Your verification code is {$this->code}";
}

// In your event listener
public function handle(TwilioMessageSent $event)
{
    if (isset($event->options['_notification'])) {
        // This message was sent via a notification
        $notificationType = $event->options['_notification']['type'];
        $notifiableType = $event->options['_notification']['notifiable'];
        $notifiableId = $event->options['_notification']['notifiable_id'];
        
        // Do notification-specific processing
    }
}

public function routeNotificationForTwilioCall($notification)
{
    return $this->phone_number; // Replace with your phone field
}

namespace App\Notifications;

use Citricguy\TwilioLaravel\Notifications\TwilioCallMessage;
use Illuminate\Notifications\Notification;

class EmergencyAlertNotification extends Notification
{
    public function via($notifiable)
    {
        return ['twilioCall'];
    }

    public function toTwilioCall($notifiable)
    {
        return (new TwilioCallMessage)
            ->url('https://example.com/emergency-twiml')
            ->from('+1234567890'); // Optional custom caller
    }
}

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

public function toTwilioCall($notifiable)
{
    return (new TwilioCallMessage)
        ->url('https://example.com/twiml-instructions')
        ->from('+1234567890')                               // Custom caller number
        ->statusCallback('https://example.com/call-status')  // Status callback URL
        ->statusCallbackEvent(['initiated', 'completed'])    // Which events to receive
        ->record(true)                                       // Record the call
        ->timeout(30)                                        // Call timeout in seconds
        ->options([                                          // Additional custom options
            'delay' => 30,     // delay in seconds
            'queue' => 'high-priority',
        ]);
}

public function toTwilioCall($notifiable)
{
    return "https://example.com/twiml-instructions";
}
bash
php artisan vendor:publish --provider="Citricguy\TwilioLaravel\TwilioLaravelServiceProvider" --tag="config"