Giter VIP home page Giter VIP logo

twilio's Introduction

Twilio notifications channel for Laravel

Latest Version on Packagist Software License Build Status StyleCI Quality Score Code Coverage Total Downloads

This package makes it easy to send Twilio notifications with Laravel 5.5+, 6.x, 7.x, 8.x & 9.x

You are viewing the 3.x documentation. Click here to view the 2.x documentation.

Contents

Installation

You can install the package via composer:

composer require laravel-notification-channels/twilio

Configuration

Add your Twilio Account SID, Auth Token, and From Number (optional) to your .env:

TWILIO_USERNAME=XYZ # optional when using auth token
TWILIO_PASSWORD=ZYX # optional when using auth token
TWILIO_AUTH_TOKEN=ABCD # optional when using username and password
TWILIO_ACCOUNT_SID=1234 # always required
TWILIO_FROM=100000000 # optional default from
TWILIO_ALPHA_SENDER=HELLO # optional
TWILIO_DEBUG_TO=23423423423 # Set a number that call calls/messages should be routed to for debugging
TWILIO_SMS_SERVICE_SID=MG0a0aaaaaa00aa00a00a000a00000a00a # Optional but recommended
TWILIO_SHORTEN_URLS=true # optional, enable URL shortener

Advanced configuration

Run php artisan vendor:publish --provider="NotificationChannels\Twilio\TwilioProvider"

/config/twilio-notification-channel.php

Suppressing specific errors or all errors

Publish the config using the above command, and edit the ignored_error_codes array. You can get the list of exception codes from the documentation.

If you want to suppress all errors, you can set the option to ['*']. The errors will not be logged but notification failed events will still be emitted.

Recommended Configuration

Twilio recommends always using a Messaging Service because it gives you access to features like Advanced Opt-Out, Sticky Sender, Scaler, Geomatch, Shortcode Reroute, and Smart Encoding.

Having issues with SMS? Check Twilio's best practices.

Upgrading from 2.x to 3.x

If you're upgrading from version 2.x, you'll need to make sure that your set environment variables match those above in the config section. None of the environment variable names have changed, but if you used different keys in your services.php config then you'll need to update them to match the above, or publish the config file and change the env key.

You should also remove the old entry for twilio from your services.php config, since it's no longer used.

The main breaking change between 2.x and 3.x is that failed notification will now throw an exception unless they are in the list of ignored error codes (publish the config file to edit these).

You can replicate the 2.x behaviour by setting 'ignored_error_codes' => ['*'], which will case all exceptions to be suppressed.

Usage

Now you can use the channel in your via() method inside the notification:

use NotificationChannels\Twilio\TwilioChannel;
use NotificationChannels\Twilio\TwilioSmsMessage;
use Illuminate\Notifications\Notification;

class AccountApproved extends Notification
{
    public function via($notifiable)
    {
        return [TwilioChannel::class];
    }

    public function toTwilio($notifiable)
    {
        return (new TwilioSmsMessage())
            ->content("Your {$notifiable->service} account was approved!");
    }
}

You can also send an MMS:

use NotificationChannels\Twilio\TwilioChannel;
use NotificationChannels\Twilio\TwilioMmsMessage;
use Illuminate\Notifications\Notification;

class AccountApproved extends Notification
{
    public function via($notifiable)
    {
        return [TwilioChannel::class];
    }

    public function toTwilio($notifiable)
    {
        return (new TwilioMmsMessage())
            ->content("Your {$notifiable->service} account was approved!")
            ->mediaUrl("https://picsum.photos/300");
    }
}

Or create a Twilio call:

use NotificationChannels\Twilio\TwilioChannel;
use NotificationChannels\Twilio\TwilioCallMessage;
use Illuminate\Notifications\Notification;

class AccountApproved extends Notification
{
    public function via($notifiable)
    {
        return [TwilioChannel::class];
    }

    public function toTwilio($notifiable)
    {
        return (new TwilioCallMessage())
            ->url("http://example.com/your-twiml-url");
    }
}

In order to let your Notification know which phone are you sending/calling to, the channel will look for the phone_number attribute of the Notifiable model. If you want to override this behaviour, add the routeNotificationForTwilio method to your Notifiable model.

public function routeNotificationForTwilio()
{
    return '+1234567890';
}

Available Message methods

TwilioSmsMessage

  • from(''): Accepts a phone to use as the notification sender.
  • content(''): Accepts a string value for the notification body.
  • messagingServiceSid(''): Accepts a messaging service SID to handle configuration.

TwilioCallMessage

  • from(''): Accepts a phone to use as the notification sender.
  • url(''): Accepts an url for the call TwiML.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

twilio's People

Contributors

alexpotter avatar atymic avatar casperboone avatar cmgmyr avatar freekmurze avatar fwartner avatar gregoriohc avatar hameesakhan avatar harlan-zw avatar jbajou avatar klimov-paul avatar laravel-shift avatar lnpbk avatar marcroberts avatar mikemclin avatar miken32 avatar mpociot avatar oyed avatar pederytter avatar rebelinblue avatar reinink avatar seagyn avatar skybitbbsr avatar themsaid avatar ziming avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

twilio's Issues

can not install on L5.7.9

I have conflict dependencies issue

Problem 1
    - Installation request for laravel-notification-channels/twilio ^2.0.7 -> satisfiable by laravel-notification-channels/twilio[2.0.7].
    - Conclusion: remove twilio/sdk 4.12.1
    - Conclusion: don't install twilio/sdk 4.12.1
    - laravel-notification-channels/twilio 2.0.7 requires twilio/sdk ~5.16 -> satisfiable by twilio/sdk[5.16.0, 5.16.1, 5.16.2, 5.16.3, 5.16.4, 5.16.5, 5.16.6, 5.16.7, 5.17.0, 5.17.1, 5.18.0, 5.19.0, 5.19.1, 5.19.2, 5.19.3, 5.19.4, 5.19.5, 5.19.6, 5.19.7, 5.20.0, 5.21.0, 5.21.1, 5.21.2, 5.21.3, 5.21.4, 5.22.0, 5.23.0, 5.23.1, 5.24.0, 5.24.1, 5.24.2].
    - Can only install one of: twilio/sdk[5.16.0, 4.12.1].
    - Can only install one of: twilio/sdk[5.16.1, 4.12.1].
    - Can only install one of: twilio/sdk[5.16.2, 4.12.1].
    - Can only install one of: twilio/sdk[5.16.3, 4.12.1].
    - Can only install one of: twilio/sdk[5.16.4, 4.12.1].
    - Can only install one of: twilio/sdk[5.16.5, 4.12.1].

Update packagist notification

Github no longer supports the Github Services - which is how Packagist gets notified of new releases. You have to convert it to a webhook. Please update the notification process and also publish 2.0.8+ to packagist.

Support for Laravel 5.6

Just tried to update a project to Laravel 5.6 and am getting a compatibility error. Given the change log for 5.6, I'm guessing that there are not any breaking changes and 5.6 can be added to the requirement composer.json file.

400 Error Laravel 7.4

I don't know what the deal is with this package so I went ahead and made a custom channel instead.

It is trying to use the "From" number instead of the model-defined phone number.

[HTTP 400] Unable to create record: The 'To' number +1[REDACTED] is not a valid phone number.

Everything is set up correctly according to the docs.

Serialization of 'Closure' is not allowed when NotificationFailed event is fired

I added NotificationFailed listener that implements ShouldQueue to log twilio errors and do some other things, but TwillioChannel is trying to send whole $exception, which causes this error on this line:

        $event = new NotificationFailed($notifiable, $notification, 'twilio', ['message' => $exception->getMessage(), 'exception' => $exception]);

If I remove 'exception' => $exception it works fine.

Twilio error I tried is: "[HTTP 400] Unable to create record: The 'To' number is not a valid phone number."

I use Laravel 5.4

HTTP 400 Problem with From number.

I get this error:

[HTTP 400] Unable to create record: The From phone number +12058988635 is not a valid, SMS-capable inbound phone number or short code for your account.

3rd party Twilio provider, multiple accounts

I would like to use this package to run multiple Twilio accounts on my website; each account is managed by one of my users. Basically I'm looking into becoming a 3rd party provider for Twilio.

How can I achieve this if the configuration gets pulled from a static .env file?

I guess I have to find a way to bypass the general booting in the TwilioProvider class

$this->app->bind(TwilioConfig::class, function () {
    return new TwilioConfig($this->app['config']['twilio-notification-channel']);
});

and rebuild the TwilioConfig for each TwilioMessage I'll be sending. Is this correct? How can I achieve this?

Whats wrong?

NotificationChannels \ SmscRu \ Exceptions \ CouldNotSendNotification
Notification was not sent. Phone number is missing.

Support for Localisation?

In Laravel, locale can be set on Notifications:

$user->notify(
    (new InvoicePaidNotification)->locale('fr')
);

https://laravel.com/docs/5.7/notifications#localizing-notifications

With the exception of using the mail channel handling the locale implementation is up to the developer as is the case with this Twilio package. So currently to make use of the locale when using this package I have done the following in my Notifications using Twilio:

  1. Using the __() helper and passing it the notification's locale:
public function toTwilio($notifiable)
{
    $content = __('welcome.message', [], $this->locale);

    return (new TwilioSmsMessage())->content($content);
}
  1. Using views and Illuminate\Support\Traits\Localizable:
public function toTwilio($notifiable)
{
    return $this->withLocale($this->locale, function() {
        $content = View::make('welcome')->render();

        return (new TwilioSmsMessage())->content($content);
    });
}

I understand that it's not a major inconvenience to either pass the __() helper the notification's locale or make use of the Localizable trait, but I was wondering if there is any scope for localisation to be baked into this package when the SMS is being sent? This package is for use with Laravel Notifications and Notifications in Laravel can have their locale set, so for me it makes complete sense and would make the code within my app a lot cleaner too without having to do my own implementation.

I am thinking it could simply work like the Mail class does with the Localizable trait, for example (a bit contrived):

public function sendMessage(TwilioMessage $message, $to, $useAlphanumericSender = false)
{
  return $this->withLocale($this->locale, function() {
    if ($message instanceof TwilioSmsMessage) {
      if ($useAlphanumericSender && $sender = $this->getAlphanumericSender()) {
        $message->from($sender);
      }

      return $this->sendSmsMessage($message, $to);
    }

    if ($message instanceof TwilioCallMessage) {
      return $this->makeCall($message, $to);
    }

    throw CouldNotSendNotification::invalidMessageObject($message);
  });
}

For the record this is what the Localizable trait does:

<?php

namespace Illuminate\Support\Traits;

use Illuminate\Container\Container;

trait Localizable
{
    /**
     * Run the callback with the given locale.
     *
     * @param  string   $locale
     * @param  \Closure $callback
     * @return mixed
     */
    public function withLocale($locale, $callback)
    {
        if (! $locale) {
            return $callback();
        }

        $app = Container::getInstance();

        $original = $app->getLocale();

        try {
            $app->setLocale($locale);

            return $callback();
        } finally {
            $app->setLocale($original);
        }
    }
}

Any thoughts? Happy to make a PR for this!

Release for Laravel 5.8

Could we get a 2.0.8 release for Laravel 5.8 since the changes are already in master pls?
Thank you

Phone Number Verification

Can this package also takes care of phone number verification or do I need to install the twilio/sdk for this ??

Credentials are required to create a Client

Using latest package 2.0 with Laravel 5.4.

.env file:

TWILIO_SID=sidherecorrectly
TWILIO_TOKEN=tokenherecorrectly
TWILIO_FROM=numberherecorrectly

config/services.php:

    'twilio' => [
        'account_sid' => env('TWILIO_SID'),
        'auth_token' => env('TWILIO_TOKEN'),
        'from' => env('TWILIO_FROM'), // optional
    ],

Error in log file:

[2017-03-30 22:35:28] development.ERROR: Twilio\Exceptions\ConfigurationException: Credentials are required to create a Client in /srv/site.com/dev/vendor/twilio/sdk/Twilio/Rest/Client.php:130
Stack trace:
#0 [internal function]: Twilio\Rest\Client->__construct(NULL, NULL, NULL, NULL, NULL, Array)
#1 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(752): ReflectionClass->newInstanceArgs(Array)
#2 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(598): Illuminate\Container\Container->build('Twilio\\Rest\\Cli...')
#3 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(567): Illuminate\Container\Container->resolve('Twilio\\Rest\\Cli...')
#4 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(708): Illuminate\Container\Container->make('Twilio\\Rest\\Cli...')
#5 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(840): Illuminate\Foundation\Application->make('Twilio\\Rest\\Cli...')
#6 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(780): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#7 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(746): Illuminate\Container\Container->resolveDependencies(Array)
#8 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(598): Illuminate\Container\Container->build('NotificationCha...')
#9 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(567): Illuminate\Container\Container->resolve('NotificationCha...')
#10 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(708): Illuminate\Container\Container->make('NotificationCha...')
#11 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(840): Illuminate\Foundation\Application->make('NotificationCha...')
#12 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(780): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#13 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(746): Illuminate\Container\Container->resolveDependencies(Array)
#14 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(598): Illuminate\Container\Container->build('NotificationCha...')
#15 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(567): Illuminate\Container\Container->resolve('NotificationCha...')
#16 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(708): Illuminate\Container\Container->make('NotificationCha...')
#17 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(137): Illuminate\Foundation\Application->make('NotificationCha...')
#18 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Support/Manager.php(63): Illuminate\Notifications\ChannelManager->createDriver('NotificationCha...')
#19 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(113): Illuminate\Support\Manager->driver('NotificationCha...')
#20 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(89): Illuminate\Notifications\NotificationSender->sendToNotifiable(Object(site\Models\User), 'e9e724bb-c203-4...', Object(site\Notifications\FHApp\BookingReminder), 'NotificationCha...')
#21 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(51): Illuminate\Notifications\NotificationSender->sendNow(Object(Illuminate\Database\Eloquent\Collection), Object(site\Notifications\FHApp\BookingReminder), Array)
#22 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/SendQueuedNotifications.php(57): Illuminate\Notifications\ChannelManager->sendNow(Object(Illuminate\Database\Eloquent\Collection), Object(site\Notifications\FHApp\BookingReminder), Array)
#23 [internal function]: Illuminate\Notifications\SendQueuedNotifications->handle(Object(Illuminate\Notifications\ChannelManager))
#24 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#25 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#26 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#27 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(531): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#28 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#29 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(114): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(Illuminate\Notifications\SendQueuedNotifications))
#30 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Notifications\SendQueuedNotifications))
#31 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#32 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(42): Illuminate\Bus\Dispatcher->dispatchNow(Object(Illuminate\Notifications\SendQueuedNotifications), false)
#33 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(69): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\SyncJob), Array)
#34 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Queue/SyncQueue.php(42): Illuminate\Queue\Jobs\Job->fire()
#35 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(184): Illuminate\Queue\SyncQueue->push(Object(Illuminate\Notifications\SendQueuedNotifications))
#36 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(159): Illuminate\Bus\Dispatcher->pushCommandToQueue(Object(Illuminate\Queue\SyncQueue), Object(Illuminate\Notifications\SendQueuedNotifications))
#37 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(73): Illuminate\Bus\Dispatcher->dispatchToQueue(Object(Illuminate\Notifications\SendQueuedNotifications))
#38 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(160): Illuminate\Bus\Dispatcher->dispatch(Object(Illuminate\Notifications\SendQueuedNotifications))
#39 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(61): Illuminate\Notifications\NotificationSender->queueNotification(Object(Illuminate\Database\Eloquent\Collection), Object(site\Notifications\FHApp\BookingReminder))
#40 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(36): Illuminate\Notifications\NotificationSender->send(Object(Illuminate\Database\Eloquent\Collection), Object(site\Notifications\FHApp\BookingReminder))
#41 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php(18): Illuminate\Notifications\ChannelManager->send(Object(site\Models\User), Object(site\Notifications\FHApp\BookingReminder))
#42 /srv/site.com/dev/app/Console/Commands/SendReminders.php(53): site\Models\User->notify(Object(site\Notifications\FHApp\BookingReminder))
#43 [internal function]: site\Console\Commands\SendReminders->handle()
#44 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#45 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#46 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#47 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Container/Container.php(531): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#48 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Console/Command.php(182): Illuminate\Container\Container->call(Array)
#49 /srv/site.com/dev/vendor/symfony/console/Command/Command.php(262): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#50 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Console/Command.php(167): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#51 /srv/site.com/dev/vendor/symfony/console/Application.php(864): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#52 /srv/site.com/dev/vendor/symfony/console/Application.php(216): Symfony\Component\Console\Application->doRunCommand(Object(site\Console\Commands\SendReminders), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#53 /srv/site.com/dev/vendor/symfony/console/Application.php(124): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#54 /srv/site.com/dev/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(123): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#55 /srv/site.com/dev/artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#56 {main}  

Messaging Services

Looking around in the source and the docs it doesn't appear to be supported, but wanted to be sure: is it possible to use messaging services with this channel? Specifically, using the messagingServiceSid parameter instead of the from parameter when creating a Twilio message.

SMS Notifications Are Not Working on Laravel 5.5

I am trying to use the release 2.0.6 with a laravel 5.5 app I get no exceptions but the SMS was not sent

service.php

'twilio' => [
    'auth_token' => env('TWILIO_TOKEN'),
    'account_sid' => env('TWILIO_SID'),
    'from' => env('TWILIO_NUMBER')
]

Notification Class

namespace App\Notifications;

use Illuminate\Notifications\Notification;
use NotificationChannels\Twilio\TwilioChannel;
use NotificationChannels\Twilio\TwilioSmsMessage;

class ReservationMade extends Notification Implements
{
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [TwilioChannel::class];
    }

    public function toTwilio($notifiable)
    {
        return (new TwilioSmsMessage())
                    ->content('bla');
    }
}

In User.php

public function routeNotificationForTwilio()
{
    return $this->phone;
}

Unresolvable dependency resolving [Parameter #0 [ <required> $sid ]] in class Services_Twilio

Posting again as the original Laravel issue has been closed.

Laravel 5.4
"laravel-notification-channels/twilio": "^1.0"
Config file (services) is fine, as is .env.

Error:

[Illuminate\Contracts\Container\BindingResolutionException]                                    
Unresolvable dependency resolving [Parameter #0 [ <required> $sid ]] in class Services_Twilio

Stack Trace:

[2017-03-15 22:13:57] local.ERROR: Illuminate\Contracts\Container\BindingResolutionException: Unresolvable dependency resolving [Parameter #0 [ <required> $sid ]] in class Services_Twilio in /Users/Alex/WEBHOSTS/FHMatchL5/vendor/laravel/framework/src/Illuminate/Container/Container.php:888

Stack trace:

[2017-03-15 22:13:57] local.ERROR: Illuminate\Contracts\Container\BindingResolutionException: Unresolvable dependency resolving [Parameter #0 [ <required> $sid ]] in class Services_Twilio in /L5/vendor/laravel/framework/src/Illuminate/Container/Container.php:888

#0 /L5/vendor/laravel/framework/src/Illuminate/Container/Container.php(826): Illuminate\Container\Container->unresolvablePrimitive(Object(ReflectionParameter))
#1 /L5/vendor/laravel/framework/src/Illuminate/Container/Container.php(779): Illuminate\Container\Container->resolvePrimitive(Object(ReflectionParameter))
#2 /L5/vendor/laravel/framework/src/Illuminate/Container/Container.php(746): Illuminate\Container\Container->resolveDependencies(Array)
#3 /L5/vendor/laravel/framework/src/Illuminate/Container/Container.php(598): Illuminate\Container\Container->build('Services_Twilio')
#4 /L5/vendor/laravel/framework/src/Illuminate/Container/Container.php(567): Illuminate\Container\Container->resolve('Services_Twilio')
#5 /L5/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(702): Illuminate\Container\Container->make('Services_Twilio')
#6 /L5/vendor/laravel/framework/src/Illuminate/Container/Container.php(840): Illuminate\Foundation\Application->make('Services_Twilio')

InvalidArgumentException: Driver [NotificationChannels\Twilio\TwilioChannel] not supported in Laravel 5.8

Since we updated to Laravel 5.8 SMS notifications are not sent anymore in Queued notifications and we receive this error: "InvalidArgumentException: Driver [NotificationChannels\Twilio\TwilioChannel] not supported"

Using: Laravel 5.8.10
Twilio/Sdk: 5.31
laravel-notifications-twilio: 2.0.10

We have a general purpose notifications class that sends both emails and SMS messages. This worked fine before migrating to Laravel 5.8 and updating the twilio packages, but now only the emails are sent.

The constructor for our notification class:

    public function __construct($locale, $view, $subject, $options = [], $smsContent = '')
    {
        $this->locale     = $locale;
        $this->view       = $view;
        $this->subject    = $subject;
        $this->options    = $options;
        $this->smsContent = $smsContent;
    }

Here is how we set the via method in our GeneralNotification class:

use NotificationChannels\Twilio\TwilioChannel;
use NotificationChannels\Twilio\TwilioSmsMessage;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed $notifiable
     *
     * @return array
     */
    public function via($notifiable)
    {
        $channels = [];
        if (isset($notifiable->routes['mail'])) {
            array_push($channels, 'mail');
        }
        if (isset($notifiable->routes['twilio'])) {
            array_push($channels, TwilioChannel::class);
        }

        return $channels;
    }

and the toTwilio call:

    /**
     * Send SMS message notifications
     *
     * @param $notifiable
     *
     * @return TwilioSmsMessage
     */
    public function toTwilio($notifiable)
    {
        app()->setLocale($this->locale);
        // grab the SMS recipient

        $notifiable->routes['twilio'] = format_phone($notifiable->routes['twilio'], true);
        $to = $notifiable->routes['twilio'];

        // remove HTML tags just in case we use the same translated text as in the email
        $smsMessage = strip_tags(__($this->smsContent, $this->options));
        Log::channel('notification_sms')->info("Sending SMS '$smsMessage' to: '$to'");
        return (new TwilioSmsMessage())
            ->from(config('app.twilio_from'))
            ->content($smsMessage);
    }

and this is how initiating this notification (GeneralNotification) would look like in code:

                                Notification::route('mail', '[email protected]')
                                    ->route('twilio', '0790865237')
                                    ->notify(new GeneralNotification(
                                        'fr',
                                        'agent_reminder_agent_evaluation',
                                        'Meeting reminder',
                                        $options,
                                        'Reminder: you have a valuation visit scheduled tomorrow at for property in.'
                                    ));

Anyone having issues with this on Laravel 5.8? The notification implements ShouldQueue

Thanks

Need instance notification for routeNotificationForTwilio

At the moment, the function receiving the number does not pass to the instance.

protected function getTo($notifiable)
{
if ($notifiable->routeNotificationFor('twilio')) {
return $notifiable->routeNotificationFor('twilio');
}
if (isset($notifiable->phone_number)) {
return $notifiable->phone_number;
}
throw CouldNotSendNotification::invalidReceiver();
}

In some cases, it is necessary to obtain instance notifications.

return $notifiable->routeNotificationFor('twilio', $notifiable);

 protected function getTo($notifiable) 
 { 
     if ($notifiable->routeNotificationFor('twilio')) { 
         return $notifiable->routeNotificationFor('twilio', $notifiable); 
     } 
     if (isset($notifiable->phone_number)) { 
         return $notifiable->phone_number; 
     } 

     throw CouldNotSendNotification::invalidReceiver(); 
 } 

Config file not passing to class

Argument 1 passed to NotificationChannels\Twilio\TwilioConfig::__construct() must be of the type array, null given, called in \vendor\laravel-notification-channels\twilio\src\TwilioProvider.php on line 33

Stack trace shows this is the point of failure
$this->app->bind(TwilioConfig::class, function () { return new TwilioConfig($this->app['config']['twilio-notification-channel']); });

I did run php artisan vendor:publish --provider="NotificationChannels\Twilio\TwilioProvider" and fill out the .env variables.

Is there something I'm missing?

NotificationFailed flow not ideal

When a queued SMS notification fails to send, a NotificationFailed event is fired. Currently, the NotificationSent event is still fired and all looks green in Telescope. Could the TwilioChannel be made a bit more verbose and mark the queued job as failed?

Aside: Would be nice if the documentation would cover catching NotificationFailed events.

[Request] For FailedNotification to have twilio exception error code

Currently, only the error message is passed back when twilio fails to send. It would be cool to be able to get the twilio error code (or whole exception) for more consistent handling: https://www.twilio.com/docs/api/errors/reference

This is how the event is currently fired:
https://github.com/laravel-notification-channels/twilio/blob/master/src/TwilioChannel.php#L58-L62

} catch (Exception $exception) {
    $this->events->fire(
        new NotificationFailed($notifiable, $notification, 'twilio', ['message' => $exception->getMessage()])
     );
}

5.8 Support (still not available)

Last version is 2.0.7 when using composer and it is over 10 days ago. Cannot install Laravel 5.8.

Problem 1
    - The requested package laravel-notification-channels/twilio 2.0.10 exists as laravel-notification-channels/twilio[1.0.2, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.0.6, 2.0.7, dev-analysis-XW071e, dev-analysis-XZmBBR, dev-master, v0.0.1, v0.0.2, v1.0.0, v1.0.1] but these are rejected by your constraint.

Better support for messagingServiceSid

Overall there needs to be better support for messagingServiceSid sending.

Currently within the code the from string is required for any SMS. This is an issue if you're sending just using the messaging service, since no number is required for that.

Also it would be good to be able to configure messagingServiceSid per message, instead of one global value.

See the example here: https://www.twilio.com/docs/sms/services

Make `TwilioProvider` deferrable

TwilioProvider should be deferrable, allowing its lazy load during application execution.

It is unlikely every project page requires an SMS sending, thus loading service provider for it all the time is unefficient.

Illuminate\Contracts\Support\DeferrableProvider interface should be used.

Driver Not Supported

Using Laravel 5.5.1, I get the following error when trying to use the Twilio Notification channel.

InvalidArgumentException: Driver [NotificationChannels\Twilio\TwilioChannel] not supported. in /home/vagrant/Code/projectname/vendor/laravel/framework/src/Illuminate/Support/Manager.php:91

Following psr-4 autoloading standard?

on composer 2.0

Deprecation Notice: Class Twilio\TwiML\Voice\Echo_ located in ./vendor/twilio/sdk/src/Twilio/TwiML/Voice/Echo.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201

Laravel 5.6 release

Is there a laravel 5.6 release scheduled at the moment? Master seems to work right now, but it would be nice to have an official release.

NotificationFailed is not fired when used in Lumen

If sending a twilio message results in an exception, this is how the current code triggers event dispatching:

$this->events->fire(
                new NotificationFailed($notifiable, $notification, 'twilio', ['message' => $exception->getMessage()])
            );

This doesn't seem actually fire an event when the package is used in Lumen (my guess is that it's because unlike Laravel, Lumen uses Laravel\Lumen\Providers\EventServiceProvider)

When I replace the event firing with this event(new NotificationFailed($notifiable, $notification, 'twilio', ['message' => $exception->getMessage()])); - it starts working as expected. Any ideas/recommendations?

Remove usage of `NotificationFailed`

Relates to #60.

I suppose usage of Illuminate\Notifications\Events\NotificationFailed event serves no purpose.
It complicates the source code without any significant outcome.

Class NotificationFailed is never used inside the Laravel Framework itself, despite it declares it.
It would be more consistent to drop its usage around this library.

Local Development Support

There should be better support for local development in the same way Laravel provide for mail.

  • It would be nice to be able writing SMS content into a log file instead of actually sending them to Twilio. So actual SMS content can be viewed, URLs picker up and so on.

  • It would be nice to have a setting for the universal receiver - a single phone number, which should receive all notifications. This is a crucial feature for the project QA.

Compatibility with laravel 5.4

Just want to find out if this package is compatible with laravel 5.4 because i followed the readme instructions to the letter and still didn't get any results.

Fails to send SMS with `messagingServiceSid`

A message fails to send when using a messagingServiceSid in a notification instead of from

This occurs because of this line: https://github.com/laravel-notification-channels/twilio/blob/master/src/TwilioConfig.php#L69

The getFrom errors as the from is not set within the config object. Instead, the function call should be

    /**
     * Get the default from address.
     *
     * @return string
     */
    public function getFrom()
    {
        if (isset($this->config['from'])) {
            return $this->config['from'];
        }
    }

On demand notifications doesn't work

On-demand notifications (as documented here) does not seem to be working with this channel:

\Notification::route(TwilioChannel::class, $phoneNumber)->notify(new MyNotification($data));

Typical notifications with notifiable model work as expected:

$user->notify(new MyNotification($data));

Note: I am using a service_sid and not a from number in config. My laravel version is 5.6

Any ideas?

UPDATE

It works when i use "twilio" instead of class name:

\Notification::route("twilio", $phoneNumber)->notify(new MyNotification($data));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.