Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twilio Bundle Laravel Package

driveop/twilio-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    • Add the bundle via Composer:
      composer require driveop/twilio-bundle
      
    • Enable the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):
      DriveOp\TwilioBundle\DriveOpTwilioBundle::class => ['all' => true],
      
    • Configure Twilio credentials in config/packages/driveop_twilio.yaml:
      driveop_twilio:
          twilio_sid:    '%env(TWILIO_SID)%'
          twilio_token:  '%env(TWILIO_TOKEN)%'
      
  2. First Use Case:

    • Inject the twilio_client service into a controller or service:
      use Symfony\Component\HttpFoundation\Response;
      
      class WhatsAppController extends AbstractController
      {
          public function sendMessage(Client $twilioClient): Response
          {
              $to = 'whatsapp:+1234567890'; // Recipient in E.164 format
              $from = 'whatsapp:+1987654321'; // Twilio WhatsApp sandbox number
              $body = 'Hello from Twilio!';
      
              $message = $twilioClient->sendWhatsAppMessage($to, $from, $body);
      
              return new Response('Message sent: ' . $message->sid);
          }
      }
      
    • Ensure your Twilio account is configured for WhatsApp/SMS (sandbox or live).

Implementation Patterns

Core Workflows

  1. Sending Messages:

    • WhatsApp: Use sendWhatsAppMessage($to, $from, $body) for WhatsApp messages. Validate recipient format (e.g., whatsapp:+1234567890).
    • SMS: Use sendSmsMessage($to, $from, $body) for SMS. Validate from as a Twilio-verified number (e.g., +1234567890).
    • Media Messages: Extend the bundle or use Twilio’s API directly for MMS (not natively supported in this bundle).
  2. Error Handling:

    • Wrap Twilio calls in try-catch blocks to handle exceptions (e.g., Twilio\Rest\ApiException):
      try {
          $message = $twilioClient->sendWhatsAppMessage($to, $from, $body);
      } catch (\Twilio\Rest\ApiException $e) {
          // Log error or retry logic
          $this->logger->error('Twilio error: ' . $e->getMessage());
      }
      
  3. Configuration Management:

    • Use Symfony’s parameter bag (%env(TWILIO_SID)%) for sensitive credentials. Avoid hardcoding.
    • Override default config in config/packages/driveop_twilio.yaml for environment-specific settings.
  4. Testing:

    • Mock the Twilio\Rest\Client service in PHPUnit tests:
      $this->container->set('twilio_client', $this->createMock(Twilio\Rest\Client::class));
      
    • Use Twilio’s sandbox for testing (e.g., WhatsApp sandbox numbers).
  5. Integration with Symfony Forms:

    • Bind Twilio messages to form submissions:
      public function sendMessageAction(Request $request, Client $twilioClient)
      {
          $form = $this->createForm(WhatsAppForm::class);
          $form->handleRequest($request);
      
          if ($form->isSubmitted() && $form->isValid()) {
              $data = $form->getData();
              $twilioClient->sendWhatsAppMessage(
                  $data['to'],
                  $data['from'],
                  $data['body']
              );
          }
      }
      

Gotchas and Tips

Pitfalls

  1. WhatsApp Sandbox Limitations:

    • Sandbox numbers (e.g., whatsapp:+14155238886) require approval for production use. Test thoroughly in sandbox before going live.
    • Sandbox numbers cannot send messages to other sandbox numbers or non-approved recipients.
  2. Number Formatting:

    • WhatsApp: Always prefix with whatsapp:+ (e.g., whatsapp:+1234567890).
    • SMS: Use E.164 format (e.g., +1234567890) without prefixes.
    • Invalid formats cause InvalidParameterValue exceptions.
  3. Rate Limits:

    • Twilio enforces rate limits (e.g., 240 messages/minute for WhatsApp). Implement exponential backoff for retries:
      use Symfony\Component\Stopwatch\Stopwatch;
      
      $stopwatch = new Stopwatch();
      $event = $stopwatch->start('twilio_retry');
      while (true) {
          try {
              $message = $twilioClient->sendWhatsAppMessage($to, $from, $body);
              break;
          } catch (\Twilio\Rest\ApiException $e) {
              if ($e->getCode() === 429) {
                  $event->lap();
                  sleep($event->getDuration() * 1.5); // Exponential backoff
              } else {
                  throw $e;
              }
          }
      }
      
  4. Webhook Verification:

    • The bundle does not include webhook handling (e.g., for message status updates). Use Twilio’s PHP SDK directly or extend the bundle:
      use Twilio\Webhooks\Twiml;
      
      public function handleWebhook(Request $request)
      {
          $twiml = new Twiml();
          // Handle incoming messages (e.g., replies)
          return new Response($twiml);
      }
      
  5. Dependency Conflicts:

    • The bundle requires twilio/sdk (^5.0). Ensure no other packages in your project conflict with this version.

Tips

  1. Logging:

    • Log Twilio message SIDs for debugging:
      $this->logger->info('Sent WhatsApp message', [
          'sid' => $message->sid,
          'to' => $to,
      ]);
      
  2. Environment-Specific Config:

    • Use %kernel.environment% to load different Twilio credentials for dev vs. prod:
      # config/packages/driveop_twilio.yaml
      driveop_twilio:
          twilio_sid:    '%env(resolve:TWILIO_SID_%kernel.environment%)%'
          twilio_token:  '%env(resolve:TWILIO_TOKEN_%kernel.environment%)%'
      
  3. Extending the Bundle:

    • Override the TwilioClient service to add custom logic:
      # config/services.yaml
      services:
          App\Service\CustomTwilioClient:
              decorates: 'twilio_client'
              arguments:
                  $inner: '@.inner'
      
      // src/Service/CustomTwilioClient.php
      class CustomTwilioClient extends TwilioClient
      {
          public function sendWhatsAppMessage($to, $from, $body)
          {
              // Add custom logic (e.g., logging, validation)
              return parent::sendWhatsAppMessage($to, $from, $body);
          }
      }
      
  4. Template Messages:

    • For WhatsApp template messages, use Twilio’s API directly (not supported in this bundle):
      $client->messages->create(
          $to,
          ['from' => $from, 'body' => $body, 'templateSid' => 'YOUR_TEMPLATE_SID']
      );
      
  5. Security:

    • Restrict Twilio API access to your Symfony app’s IP in the Twilio Console to prevent abuse.
    • Use Symfony’s ParameterBag to validate credentials on bundle load:
      // src/DependencyInjection/DriveOpTwilioExtension.php
      if (empty($config['twilio_sid']) || empty($config['twilio_token'])) {
          throw new \InvalidArgumentException('Twilio credentials are required.');
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle