Skip to content
This repository has been archived by the owner on Sep 19, 2023. It is now read-only.

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
KolyaSirik committed Jun 15, 2021
1 parent d619013 commit bea53b7
Show file tree
Hide file tree
Showing 14 changed files with 1,137 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
159 changes: 158 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,158 @@
# laravel-notification-channel-twilio
# Twilio notifications channel for Laravel

## Contents

- [Installation](#installation)
- [Usage](#usage)
- [Available Message methods](#available-message-methods)

## Installation

You can install the package via composer:

``` bash
composer require justcoded/laravel-notification-channel-twilio
```

### Configuration

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

```dotenv
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
```

### Advanced configuration

Run `php artisan vendor:publish --provider="Justcoded\NotificationChannelTwilio\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](https://www.twilio.com/docs/api/errors).

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](https://www.twilio.com/docs/sms/services) 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](https://www.twilio.com/docs/sms/services/services-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:

``` php
use Justcoded\NotificationChannelTwilio\TwilioChannel;
use Justcoded\NotificationChannelTwilio\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:

``` php
use Justcoded\NotificationChannelTwilio\TwilioChannel;
use Justcoded\NotificationChannelTwilio\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:

``` php
use Justcoded\NotificationChannelTwilio\TwilioChannel;
use Justcoded\NotificationChannelTwilio\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.

```php
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.
34 changes: 34 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "justcoded/laravel-notification-channel-twilio",
"description": "Provides Twilio notification channel for Laravel",
"keywords": ["laravel", "twilio", "notification", "sms", "call", "mms"],
"authors": [
{
"name": "JustCoded Team",
"email": "[email protected]"
}
],
"require": {
"php": ">=7.2",
"twilio/sdk": "~6.0",
"illuminate/notifications": "^5.8 || ^6.0 || ^7.0 || ^8.0",
"illuminate/support": "^5.8 || ^6.0 || ^7.0 || ^8.0",
"illuminate/events": "^5.8 || ^6.0 || ^7.0 || ^8.0",
"illuminate/queue": "^5.8 || ^6.0 || ^7.0 || ^8.0"
},
"autoload": {
"psr-4": {
"NotificationChannels\\Twilio\\": "src"
}
},
"config": {
"sort-packages": true
},
"extra": {
"laravel": {
"providers": [
"NotificationChannels\\Twilio\\TwilioProvider"
]
}
}
}
36 changes: 36 additions & 0 deletions config/twilio-notification-channel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

return [
'username' => env('TWILIO_USERNAME'), // optional when using auth token
'password' => env('TWILIO_PASSWORD'), // optional when using auth token
'auth_token' => env('TWILIO_AUTH_TOKEN'), // optional when using username and password
'account_sid' => env('TWILIO_ACCOUNT_SID'),

'from' => env('TWILIO_FROM'), // optional
'alphanumeric_sender' => env('TWILIO_ALPHA_SENDER'),

/**
* See https://www.twilio.com/docs/sms/services.
*/
'sms_service_sid' => env('TWILIO_SMS_SERVICE_SID'),

/**
* Specify a number where all calls/messages should be routed. This can be used in development/staging environments
* for testing.
*/
'debug_to' => env('TWILIO_DEBUG_TO'),

/**
* If an exception is thrown with one of these error codes, it will be caught & suppressed.
* To replicate the 2.x behaviour, specify '*' in the array, which will cause all exceptions to be suppressed.
* Suppressed errors will not be logged or reported, but the `NotificationFailed` event will be emitted.
*
* @see https://www.twilio.com/docs/api/errors
*/
'ignored_error_codes' => [
21608, // The 'to' phone number provided is not yet verified for this account.
21211, // Invalid 'To' Phone Number
21614, // 'To' number is not a valid mobile number
21408, // Permission to send an SMS has not been enabled for the region indicated by the 'To' number
],
];
40 changes: 40 additions & 0 deletions src/Exceptions/CouldNotSendNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace NotificationChannels\Twilio\Exceptions;

use NotificationChannels\Twilio\TwilioCallMessage;
use NotificationChannels\Twilio\TwilioSmsMessage;

class CouldNotSendNotification extends \Exception
{
public static function invalidMessageObject($message): self
{
$className = is_object($message) ? get_class($message) : 'Unknown';

return new static(
"Notification was not sent. Message object class `{$className}` is invalid. It should
be either `".TwilioSmsMessage::class.'` or `'.TwilioCallMessage::class.'`');
}

public static function missingFrom(): self
{
return new static('Notification was not sent. Missing `from` number.');
}

public static function invalidReceiver(): self
{
return new static(
'The notifiable did not have a receiving phone number. Add a routeNotificationForTwilio
method or a phone_number attribute to your notifiable.'
);
}

public static function missingAlphaNumericSender(): self
{
return new static(
'Notification was not sent. Missing `alphanumeric_sender` in config'
);
}
}
13 changes: 13 additions & 0 deletions src/Exceptions/InvalidConfigException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace NotificationChannels\Twilio\Exceptions;

class InvalidConfigException extends \Exception
{
public static function missingConfig(): self
{
return new self('Missing config. You must set either the username & password or SID and auth token');
}
}
Loading

0 comments on commit bea53b7

Please sign in to comment.