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

Nexmo Bundle Laravel Package

docdocdoc/nexmo-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require docdocdoc/nexmo-bundle
    

    Add to config/bundles.php (Symfony 4.4+):

    return [
        DocDocDoc\NexmoBundle\DocDocDocNexmoBundle::class => ['all' => true],
    ];
    

    Or register in AppKernel.php (Symfony <4.4):

    new DocDocDoc\NexmoBundle\DocDocDocNexmoBundle(),
    
  2. Configure API Credentials Add to config/packages/doc_doc_doc_nexmo.yaml:

    doc_doc_doc_nexmo:
        api_key: "%env(NEXMO_API_KEY)%"
        api_secret: "%env(NEXMO_API_SECRET)%"
    
  3. First SMS Send Inject the service and use it in a controller/service:

    use DocDocDoc\NexmoBundle\Message\Simple;
    use DocDocDoc\NexmoBundle\NexmoService;
    
    public function sendSms(NexmoService $nexmo)
    {
        $message = new Simple('MyApp', '+1234567890', 'Hello from Laravel!');
        $response = $nexmo->send($message);
        return $response->getMessages()[0]->getStatus();
    }
    

Implementation Patterns

Core Workflow

  1. Message Creation Use Simple for basic SMS:

    $message = new Simple('SenderID', 'recipient', 'content');
    

    For Unicode/long messages, extend AbstractMessage or use MessageBuilder (if available).

  2. Service Integration

    • Controllers: Inject NexmoService and call send().
    • Services/Jobs: Pass the service via constructor or resolve via container.
    • Forms: Validate phone numbers with Symfony\Validator\Constraints\PhoneNumber.
  3. Response Handling Check $response->getMessages()[0]->getStatus() for:

    • 0: Success.
    • 1: Error (e.g., invalid number). Log errors for debugging:
    if ($response->getMessages()[0]->getErrorCode()) {
        $this->logger->error('Nexmo error: ' . $response->getMessages()[0]->getErrorText());
    }
    
  4. Batch Sending Loop through a collection and send sequentially (avoid rate limits):

    foreach ($users as $user) {
        $message = new Simple('SenderID', $user->phone, 'Your OTP: ' . $user->otp);
        $nexmo->send($message);
    }
    

Advanced Patterns

  • Event Listeners: Trigger post-send logic (e.g., analytics):
    // config/services.yaml
    services:
        App\Listener\SmsSentListener:
            tags:
                - { name: kernel.event_listener, event: docdocdoc.nexmo.message.sent, method: onSmsSent }
    
  • Custom Providers: Extend AbstractProvider for custom logic (e.g., logging to DB).
  • Docker/Environments: Use .env for credentials:
    NEXMO_API_KEY=your_key
    NEXMO_API_SECRET=your_secret
    

Gotchas and Tips

Common Pitfalls

  1. API Key/Secret Mismatch

    • Symptom: AuthenticationError or empty responses.
    • Fix: Double-check config/packages/doc_doc_doc_nexmo.yaml and .env values.
    • Debug: Enable debug mode (APP_DEBUG=true) to see raw Nexmo API errors.
  2. Phone Number Formatting

    • Symptom: InvalidNumber error.
    • Fix: Use E.164 format (e.g., +1234567890, not 123-456-7890).
    • Validation: Add a validator:
      # config/validator/constraints.yaml
      App\Validator\Constraints\E164Phone:
          message: 'Phone number must be in E.164 format.'
      
  3. Rate Limits

    • Symptom: Throttled errors or delayed deliveries.
    • Fix: Implement exponential backoff in your sender loop:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              $nexmo->send($message);
              break;
          } catch (\Exception $e) {
              $attempts++;
              sleep(2 ** $attempts); // Exponential delay
          }
      }
      
  4. Provider Misconfiguration

    • Symptom: SMS not sent (e.g., noop or send_mail not working).
    • Fix: Verify provider key in config:
      doc_doc_doc_nexmo:
          provider: doc_doc_doc_nexmo.send_mail # For testing
          mail_to: test@example.com
      

Debugging Tips

  • Log Raw Responses Extend NexmoService to log responses:
    public function send(MessageInterface $message)
    {
        $response = parent::send($message);
        $this->logger->debug('Nexmo response:', ['data' => $response->toArray()]);
        return $response;
    }
    
  • Test with noop Provider Disable actual sends in config/packages/doc_doc_doc_nexmo.yaml:
    doc_doc_doc_nexmo:
        provider: doc_doc_doc_nexmo.noop
    
  • Check Nexmo Dashboard Monitor sent messages and errors at Nexmo Dashboard.

Extension Points

  1. Custom Message Types Extend AbstractMessage for structured data (e.g., templates):

    class TemplateMessage extends AbstractMessage {
        public function __construct(string $templateName, array $variables) {
            parent::__construct('SenderID', $variables['to'], $this->renderTemplate($templateName, $variables));
        }
    }
    
  2. Async Sending Use Symfony Messenger or queues (e.g., RabbitMQ) to offload SMS sending:

    // Dispatch a message
    $this->messageBus->dispatch(new SendSmsMessage($message));
    
    // Handler
    public function __invoke(SendSmsMessage $message) {
        $this->nexmoService->send($message->getMessage());
    }
    
  3. Webhook Integration Listen for Nexmo inbound SMS via docdocdoc.nexmo.webhook.received event:

    public function onWebhookReceived(WebhookEvent $event) {
        $this->handleInboundSms($event->getMessage());
    }
    
  4. Fallback Providers Chain providers for redundancy (e.g., Nexmo + Twilio):

    doc_doc_doc_nexmo:
        providers:
            - doc_doc_doc_nexmo.nexmo
            - doc_doc_doc_nexmo.twilio # Custom provider
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope