diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..e507026d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +All notable changes to `Zenvia` will be documented in this file + +## 1.0.0 - 2023-08-19 + +- initial release + +## 1.0.1 - 2023-08-21 + +- First stable version diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..4da74e3f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code +held within. They make the code freely available in the hope that it will be of use to other developers. It would be +extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the +world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient +quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open +source projects are used by many developers, who may have entirely different needs to your own. Think about +whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +If the project maintainer has any additional requirements, you will find them listed here. + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..8bc4a36c --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) :author_name <:author_email> + +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. diff --git a/README.md b/README.md index fa8362b7..32131290 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,115 @@ -# New Notification Channels +# Zenvia notifications channel for Laravel -### Suggesting a new channel -Have a suggestion or working on a new channel? Please create a new issue for that service. +[![Latest Version on Packagist](https://img.shields.io/packagist/v/guiigaspar/laravel-zenvia-channel.svg?style=flat-square)](https://packagist.org/packages/guiigaspar/laravel-zenvia-channel) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Total Downloads](https://img.shields.io/packagist/dt/guiigaspar/laravel-zenvia-channel.svg?style=flat-square)](https://packagist.org/packages/guiigaspar/laravel-zenvia-channel) -### I'm working on a new channel -Please create an issue for it if it does not already exist, then PR you code for review. +This package makes it easy to send notifications using [Zenvia](https://zenviasms.docs.apiary.io) with Laravel 7.x, 8.x, 9.x, 10.x -## Workflow for new channels +## Contents -1) Head over to the [skeleton repo](https://github.com/laravel-notification-channels/skeleton) download a ZIP copy. This is important, to ensure you start from a fresh commit history. -2) Use find/replace to replace all of the placeholders with the correct values (package name, author name, email, etc). -3) Implement to logic for the channel & add tests. -4) Fork this repo, add it as a remote and push your new channel to a branch. -5) Submit a new PR against this repo for review. +- [Installation](#installation) + - [Configuration](#configuration) + - [Advanced Configuration](#advanced-configuration) +- [Usage](#usage) + - [Available Message methods](#available-message-methods) +- [Changelog](#changelog) +- [Testing](#testing) +- [Security](#security) +- [Contributing](#contributing) +- [Credits](#credits) +- [License](#license) -Take a look at our [FAQ](http://laravel-notification-channels.com/) to see our small list of rules, to provide top-notch notification channels. + +## Installation + +You can install the package via composer: + +``` bash +composer require guiigaspar/laravel-zenvia-channel +``` + +### Configuration + +Add your Zenvia Account, Password, and From Name (optional) to your `.env`: + +```dotenv +ZENVIA_ACCOUNT=XYZ +ZENVIA_PASSWORD=XYZ +ZENVIA_FROM=XYZ # optional +``` + +### Advanced Configuration + +Run `php artisan vendor:publish --provider="NotificationChannels\LaravelZenviaChannel\ZenviaServiceProvider"` +``` +/config/zenvia-notification-channel.php +``` + +## Usage + +Now you can use the channel in your `via()` method inside the notification: + +``` php +use NotificationChannels\LaravelZenviaChannel\ZenviaChannel; +use NotificationChannels\LaravelZenviaChannel\ZenviaSmsMessage; +use Illuminate\Notifications\Notification; + +class AccountApproved extends Notification +{ + public function via($notifiable) + { + return [ZenviaChannel::class]; + } + + public function toZenvia($notifiable) + { + return (new ZenviaSmsMessage()) + ->content("Your order {$notifiable->orderId} was approved!"); + } +} +``` + +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 `routeNotificationForZenvia` method to your Notifiable model. + +```php +public function routeNotificationForZenvia() +{ + return '+5511912345678'; +} +``` + +### Available Message methods + +#### ZenviaSmsMessage + +- `id('')`: Accepts a ID to use as the notification identifier. +- `content('')`: Accepts a string value for the notification body. +- `schedule('')`: Accepts a string value for the notification schedule. + +## Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. + +## Testing + +``` bash +$ composer test +``` + +## Security + +If you discover any security related issues, please email guiigaspar@live.com instead of using the issue tracker. + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) for details. + +## Credits + +- [Guilherme Gaspar](https://github.com/guiigaspar) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..9360d79d --- /dev/null +++ b/composer.json @@ -0,0 +1,55 @@ +{ + "name": "guiigaspar/laravel-zenvia-channel", + "description": "Provides Zenvia notification channel for Laravel", + "keywords": [ + "laravel", + "zenvia", + "notification", + "sms" + ], + "homepage": "https://github.com/guiigaspar/laravel-zenvia-channel", + "license": "MIT", + "authors": [ + { + "name": "Guilherme Gaspar", + "email": "guiigaspar@live.com", + "homepage": "https://github.com/guiigaspar", + "role": "Developer" + } + ], + "require": { + "php": "^8.1", + "guzzlehttp/guzzle": "^7.0", + "illuminate/notifications": "^7.0 || ^8.0 || ^9.0 || ^10.0", + "illuminate/support": "^7.0 || ^8.0 || ^9.0 || ^10.0" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "phpunit/phpunit": "^9.0", + "orchestra/testbench": "^5.0 || ^6.0 || ^7.0 || ^8.0" + }, + "autoload": { + "psr-4": { + "NotificationChannels\\LaravelZenviaChannel\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "NotificationChannels\\LaravelZenviaChannel\\Test\\": "tests" + } + }, + "scripts": { + "test": "phpunit", + "test:coverage": "phpunit --coverage-text --coverage-clover=coverage.clover" + }, + "config": { + "sort-packages": true + }, + "extra": { + "laravel": { + "providers": [ + "NotificationChannels\\LaravelZenviaChannel\\ZenviaServiceProvider" + ] + } + } +} diff --git a/config/zenvia-notification-channel.php b/config/zenvia-notification-channel.php new file mode 100644 index 00000000..0a974742 --- /dev/null +++ b/config/zenvia-notification-channel.php @@ -0,0 +1,7 @@ + env('ZENVIA_ACCOUNT'), + 'password' => env('ZENVIA_PASSWORD'), + 'from' => env('ZENVIA_FROM'), +]; diff --git a/src/Enums/CallbackOptionEnum.php b/src/Enums/CallbackOptionEnum.php new file mode 100644 index 00000000..c843da50 --- /dev/null +++ b/src/Enums/CallbackOptionEnum.php @@ -0,0 +1,10 @@ +getResponse()->getStatusCode(); + $description = 'no description given'; + + if ($result = json_decode($exception->getResponse()->getBody())) { + $description = $result->description ?: $description; + } + + return new static( + "Zenvia responded with an error `{$statusCode} - {$description}`" + ); + } +} diff --git a/src/Exceptions/InvalidConfigException.php b/src/Exceptions/InvalidConfigException.php new file mode 100644 index 00000000..3e9df850 --- /dev/null +++ b/src/Exceptions/InvalidConfigException.php @@ -0,0 +1,13 @@ +zenviaService = $zenviaService; + $this->config = $config; + } + + /** + * Send a ZenviaMessage to the a phone number. + * + * @param ZenviaMessage $message + * @param string|null $to + * + * @throws CouldNotSendNotification + * + * @return mixed + */ + public function sendMessage(ZenviaMessage $message, ?string $to) + { + if ($message instanceof ZenviaSmsMessage) { + return $this->sendSmsMessage($message, $to); + } + + throw CouldNotSendNotification::invalidMessageObject($message); + } + + protected function sendSmsMessage(ZenviaSmsMessage $message, ?string $to): ZenviaServiceResponse + { + if (empty($message->content)) { + throw CouldNotSendNotification::contentNotProvided(); + } + + $data = [ + 'sendSmsRequest' => [ + 'from' => $this->config->getFrom() ?? '', + 'to' => $to, + 'msg' => Str::limit($message->content, 160), + 'id' => $message->id, + 'schedule' => $message->schedule ?? '', + 'callbackOption' => $message->callbackOption ?? CallbackOptionEnum::OPTION_NONE, + 'aggregateId' => $message->aggregateId ?? '', + 'flashSms' => $message->flashSms ?? false, + ], + ]; + + return $this->zenviaService->post('/services/send-sms', ['json' => $data]); + } +} diff --git a/src/ZenviaChannel.php b/src/ZenviaChannel.php new file mode 100644 index 00000000..1f96b55b --- /dev/null +++ b/src/ZenviaChannel.php @@ -0,0 +1,113 @@ +zenvia = $zenvia; + $this->events = $events; + } + + /** + * Send the given notification. + * + * @param mixed $notifiable + * @param Notification $notification + * + * @throws Exception + * + * @return mixed + */ + public function send($notifiable, Notification $notification) + { + try { + $to = $this->getTo($notifiable, $notification); + $message = $notification->toZenvia($notifiable); + + if (is_string($message)) { + $message = new ZenviaSmsMessage($message); + } + + if (!$message instanceof ZenviaMessage) { + throw CouldNotSendNotification::invalidMessageObject($message); + } + + return $this->zenvia->sendMessage($message, $to); + } catch(ConnectException $exception) { + $this->notificationEventFailed($notifiable, $notification, $exception); + + throw CouldNotSendNotification::serviceConnectionError(); + } catch(ClientException $exception) { + $this->notificationEventFailed($notifiable, $notification, $exception); + + throw CouldNotSendNotification::serviceRespondedWithAnError($exception); + } catch(Exception $exception) { + $this->notificationEventFailed($notifiable, $notification, $exception); + + throw $exception; + } + } + + /** + * Get the address to send a notification to. + * + * @param mixed $notifiable + * @param Notification|null $notification + * + * @throws CouldNotSendNotification + * + * @return mixed + */ + protected function getTo($notifiable, $notification = null) + { + if ($notifiable->routeNotificationFor(self::class, $notification)) { + return $notifiable->routeNotificationFor(self::class, $notification); + } + if ($notifiable->routeNotificationFor('zenvia', $notification)) { + return $notifiable->routeNotificationFor('zenvia', $notification); + } + if (isset($notifiable->phone_number)) { + return $notifiable->phone_number; + } + + throw CouldNotSendNotification::invalidReceiver(); + } + + protected function notificationEventFailed($notifiable, Notification $notification, Exception $exception) + { + $event = new NotificationFailed( + $notifiable, + $notification, + 'zenvia', + ['message' => $exception->getMessage(), 'exception' => $exception] + ); + + $this->events->dispatch($event); + } +} diff --git a/src/ZenviaConfig.php b/src/ZenviaConfig.php new file mode 100644 index 00000000..bf535457 --- /dev/null +++ b/src/ZenviaConfig.php @@ -0,0 +1,37 @@ +config = $config; + } + + public function usingAccountPasswordAuth(): bool + { + return $this->getAccount() !== null && $this->getPassword() !== null; + } + + public function getAccount(): ?string + { + return $this->config['account'] ?? null; + } + + public function getPassword(): ?string + { + return $this->config['password'] ?? null; + } + + public function getFrom(): ?string + { + return $this->config['from'] ?? null; + } +} diff --git a/src/ZenviaMessage.php b/src/ZenviaMessage.php new file mode 100644 index 00000000..18caef4a --- /dev/null +++ b/src/ZenviaMessage.php @@ -0,0 +1,47 @@ +content($content); + } + + /** + * Set the message content. + * + * @param string $content + * + * @return $this + */ + public function content(string $content): self + { + $this->content = $content; + + return $this; + } +} diff --git a/src/ZenviaServiceProvider.php b/src/ZenviaServiceProvider.php new file mode 100644 index 00000000..a279f36c --- /dev/null +++ b/src/ZenviaServiceProvider.php @@ -0,0 +1,82 @@ +mergeConfigFrom(__DIR__.'/../config/zenvia-notification-channel.php', 'zenvia-notification-channel'); + + $this->publishes([ + __DIR__.'/../config/zenvia-notification-channel.php' => config_path('zenvia-notification-channel.php'), + ]); + + $this->app->bind(ZenviaConfig::class, function () { + return new ZenviaConfig($this->app['config']['zenvia-notification-channel']); + }); + + $this->app->singleton(ZenviaService::class, function (Application $app) { + /** @var ZenviaConfig $config */ + $config = $app->make(ZenviaConfig::class); + + if ($config->usingAccountPasswordAuth()) { + return new ZenviaService([ + 'base_uri' => 'https://api-rest.zenvia.com', + 'headers' => [ + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + 'Authorization' => 'Basic '.base64_encode($config->getAccount().':'.$config->getPassword()), + ], + ]); + } + + throw InvalidConfigException::missingConfig(); + }); + + $this->app->singleton(Zenvia::class, function (Application $app) { + return new Zenvia( + $app->make(ZenviaService::class), + $app->make(ZenviaConfig::class) + ); + }); + + $this->app->singleton(ZenviaChannel::class, function (Application $app) { + return new ZenviaChannel( + $app->make(Zenvia::class), + $app->make(Dispatcher::class) + ); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides(): array + { + return [ + ZenviaConfig::class, + ZenviaService::class, + ZenviaChannel::class, + ]; + } +} diff --git a/src/ZenviaSmsMessage.php b/src/ZenviaSmsMessage.php new file mode 100644 index 00000000..798707bd --- /dev/null +++ b/src/ZenviaSmsMessage.php @@ -0,0 +1,103 @@ +schedule = $schedule; + + return $this; + } + + /** + * Set the message callback option. + * + * @param string $callbackOption + * + * @return $this + */ + public function callbackOption(CallbackOptionEnum $callbackOption): self + { + $this->callbackOption = $callbackOption; + + return $this; + } + + /** + * Set the message ID. + * + * @param string $id + * + * @return $this + */ + public function id(string $id): self + { + $this->id = $id; + + return $this; + } + + /** + * Set the message aggregate ID. + * + * @param string $aggregateId + * + * @return $this + */ + public function aggregateId(string $aggregateId): self + { + $this->aggregateId = $aggregateId; + + return $this; + } + + /** + * Set the message flash sms service use. + * + * @param bool $flashSms + * + * @return $this + */ + public function flashSms(bool $flashSms): self + { + $this->flashSms = $flashSms; + + return $this; + } +} diff --git a/tests/Integration/BaseIntegrationTest.php b/tests/Integration/BaseIntegrationTest.php new file mode 100644 index 00000000..484694c1 --- /dev/null +++ b/tests/Integration/BaseIntegrationTest.php @@ -0,0 +1,16 @@ +expectException(InvalidConfigException::class); + + $this->app->get(ZenviaChannel::class); + } + + public function testThatApplicationCreatesChannelWithConfig() + { + $this->app['config']->set('zenvia-notification-channel.account', 'test'); + $this->app['config']->set('zenvia-notification-channel.password', 'password'); + + $this->assertInstanceOf(ZenviaChannel::class, $this->app->get(ZenviaChannel::class)); + } +} diff --git a/tests/Unit/ZenviaChannelTest.php b/tests/Unit/ZenviaChannelTest.php new file mode 100644 index 00000000..c0fe1211 --- /dev/null +++ b/tests/Unit/ZenviaChannelTest.php @@ -0,0 +1,92 @@ +zenvia = Mockery::mock(Zenvia::class); + $this->dispatcher = Mockery::mock(Dispatcher::class); + + $this->channel = new ZenviaChannel($this->zenvia, $this->dispatcher); + } + + /** @test */ + public function it_will_not_send_a_message_without_known_receiver() + { + $notifiable = new Notifiable(); + $notification = Mockery::mock(Notification::class); + + $this->zenvia->config = new ZenviaConfig([]); + + $this->dispatcher->shouldReceive('dispatch') + ->atLeast()->once() + ->with(Mockery::type(NotificationFailed::class)); + + $this->expectException(CouldNotSendNotification::class); + + $result = $this->channel->send($notifiable, $notification); + + $this->assertNull($result); + } + + /** @test */ + public function it_will_fire_an_event_in_case_of_an_invalid_message() + { + $notifiable = new NotifiableWithAttribute(); + $notification = Mockery::mock(Notification::class); + + $this->zenvia->config = new ZenviaConfig([]); + + // Invalid message + $notification->shouldReceive('toZenvia')->andReturn(-1); + + $this->dispatcher->shouldReceive('dispatch') + ->atLeast()->once() + ->with(Mockery::type(NotificationFailed::class)); + + $this->expectException(CouldNotSendNotification::class); + + $this->channel->send($notifiable, $notification); + } +} + +class Notifiable +{ + public $phone_number = null; + + public function routeNotificationFor() + { + } +} + +class NotifiableWithAttribute +{ + public $phone_number = '+22222222222'; + + public function routeNotificationFor() + { + } +} diff --git a/tests/Unit/ZenviaSmsMessageTest.php b/tests/Unit/ZenviaSmsMessageTest.php new file mode 100644 index 00000000..699c8e6a --- /dev/null +++ b/tests/Unit/ZenviaSmsMessageTest.php @@ -0,0 +1,51 @@ +message = new ZenviaSmsMessage(); + } + + /** @test */ + public function it_can_accept_a_message_when_constructing_a_message() + { + $message = new ZenviaSmsMessage('myMessage'); + + $this->assertEquals('myMessage', $message->content); + } + + /** @test */ + public function it_provides_a_create_method() + { + $message = ZenviaSmsMessage::create('myMessage'); + + $this->assertEquals('myMessage', $message->content); + } + + /** @test */ + public function it_can_set_optional_parameters() + { + $message = ZenviaSmsMessage::create('myMessage'); + $message->schedule('2023-08-20T02:01:23'); + $message->callbackOption(CallbackOptionEnum::OPTION_ALL); + $message->id('1234'); + $message->aggregateId('ABCD1234'); + $message->flashSms(true); + + $this->assertEquals('2023-08-20T02:01:23', $message->schedule); + $this->assertEquals(CallbackOptionEnum::OPTION_ALL, $message->callbackOption); + $this->assertEquals('1234', $message->id); + $this->assertEquals('ABCD1234', $message->aggregateId); + $this->assertEquals(true, $message->flashSms); + } +}