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 Notifier Laravel Package

symfony/nexmo-notifier

Symfony Notifier bridge for Vonage (formerly Nexmo). Sends SMS notifications via the Notifier component, integrating with Symfony’s channel system. Configure Vonage credentials and deliver messages through a Nexmo/Vonage transport in your apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require symfony/nexmo-notifier
    

    Ensure symfony/nexmo-notifier is registered in config/nexmo.php (if using Symfony) or manually configure the client in Laravel.

  2. First Use Case: Sending an SMS Initialize the client in Laravel’s service container (e.g., config/services.php):

    'nexmo' => [
        'key' => env('NEXMO_KEY'),
        'secret' => env('NEXMO_SECRET'),
        'api_url' => env('NEXMO_API_URL', 'https://api.nexmo.com'),
    ],
    

    Register a binding in AppServiceProvider:

    $this->app->bind(\Nexmo\Client, function ($app) {
        return new \Nexmo\Client(
            $app['config']['services.nexmo.key'],
            $app['config']['services.nexmo.secret'],
            $app['config']['services.nexmo.api_url']
        );
    });
    
  3. Send a Test Message Create a helper class or facade (e.g., NexmoService):

    use Nexmo\Client;
    use Nexmo\Message\Sms\Message;
    
    class NexmoService {
        protected $client;
    
        public function __construct(Client $client) {
            $this->client = $client;
        }
    
        public function sendSms(string $to, string $message) {
            $message = new Message();
            $message->setTo($to)
                    ->setFrom(env('NEXMO_FROM_NUMBER'))
                    ->setText($message);
    
            return $this->client->message()->create($message);
        }
    }
    

    Use it in a controller:

    $nexmo = app(NexmoService::class);
    $response = $nexmo->sendSms('+1234567890', 'Hello from Laravel!');
    

Implementation Patterns

Workflows

  1. SMS Notifications

    • Bulk Sending: Use a queue job to process large lists of recipients:
      class SendBulkSmsJob implements ShouldQueue {
          use Dispatchable, InteractsWithQueue, Queueable;
      
          public function handle(NexmoService $nexmo) {
              foreach ($recipients as $phone) {
                  $nexmo->sendSms($phone, 'Your message here');
              }
          }
      }
      
    • Templates: Store SMS templates in the database and fetch them dynamically:
      $template = Template::find($id);
      $nexmo->sendSms($phone, $template->body);
      
  2. Voice Calls Leverage the Voice\Call class for voice notifications:

    use Nexmo\Voice\Call;
    
    $call = new Call();
    $call->setTo($phone)
         ->setFrom(env('NEXMO_FROM_NUMBER'))
         ->setAnswerUrl('https://example.com/voice-answer');
    
    $this->client->voice()->create($call);
    
  3. Webhooks Validate and process Nexmo webhooks (e.g., for delivery reports):

    Route::post('/nexmo/webhook', function (Request $request) {
        $validator = new \Nexmo\Validator\WebhookValidator();
        if ($validator->validate($request->all())) {
            // Handle event (e.g., SMS delivery status)
        }
    });
    

Integration Tips

  • Logging: Wrap API calls in a try-catch block to log failures:
    try {
        $response = $nexmo->sendSms($to, $message);
    } catch (\Exception $e) {
        Log::error("Nexmo SMS failed: " . $e->getMessage());
    }
    
  • Rate Limiting: Use Laravel’s throttle middleware for API endpoints triggering Nexmo calls.
  • Testing: Mock the Nexmo\Client in unit tests:
    $mock = Mockery::mock(Nexmo\Client::class);
    $mock->shouldReceive('message')->andReturnSelf();
    $mock->shouldReceive('create')->andReturn(new stdClass());
    
    $this->app->instance(Nexmo\Client::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warnings The package is archived and may not support newer Nexmo API versions. Verify compatibility with Nexmo’s PHP SDK if issues arise.

  2. Webhook Security Always validate webhook signatures to prevent spoofing:

    $validator = new \Nexmo\Validator\WebhookValidator();
    $validator->setKey(env('NEXMO_WEBHOOK_KEY'));
    if (!$validator->validate($request->all())) {
        abort(403, 'Invalid webhook signature');
    }
    
  3. Number Formatting Ensure phone numbers are in E.164 format (e.g., +1234567890). Use a library like libphonenumber for validation:

    use libphonenumber\PhoneNumberUtil;
    use libphonenumber\PhoneNumberFormat;
    
    $phoneUtil = PhoneNumberUtil::getInstance();
    $phone = $phoneUtil->parse($rawPhone, 'US');
    $e164 = $phoneUtil->format($phone, PhoneNumberFormat::E164);
    
  4. API Credentials Avoid hardcoding credentials. Use Laravel’s .env and validate them in AppServiceProvider:

    if (empty(env('NEXMO_KEY')) || empty(env('NEXMO_SECRET'))) {
        throw new \RuntimeException('Nexmo credentials not configured.');
    }
    

Debugging

  • Enable Debugging: Set the debug flag in the Nexmo client:

    $client = new \Nexmo\Client($key, $secret, $apiUrl, [
        'debug' => true,
    ]);
    

    Logs will appear in storage/logs/nexmo.log (if configured).

  • HTTP Client Errors: Use Guzzle’s middleware to inspect requests/responses:

    $client = new \Nexmo\Client($key, $secret, $apiUrl, [
        'http_client' => new \GuzzleHttp\Client([
            'handler' => \GuzzleHttp\HandlerStack::create([
                new \GuzzleHttp\Middleware::tap(function ($request, $options) {
                    Log::debug('Nexmo Request:', ['url' => $request->getUri(), 'body' => $request->getBody()]);
                }),
            ]),
        ]),
    ]);
    

Extension Points

  1. Custom Responses Extend the NexmoService to handle custom Nexmo responses:

    public function sendSms(string $to, string $message) {
        $response = $this->client->message()->create($message);
        return new NexmoResponse($response->getMessageId(), $response->getStatus());
    }
    
  2. Retry Logic Implement exponential backoff for failed requests using Laravel’s retry helper:

    try {
        $nexmo->sendSms($to, $message);
    } catch (\Exception $e) {
        retry()->times(3)->later()->catch(\Exception::class, function () {
            Log::error("Max retries reached for Nexmo SMS.");
        });
    }
    
  3. Event Dispatching Trigger Laravel events after sending messages:

    event(new SmsSent($to, $message));
    

    Listen for events in EventServiceProvider:

    protected $listen = [
        SmsSent::class => [
            SendSmsNotification::class,
            LogSmsActivity::class,
        ],
    ];
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor