From 649983e3c7acaf4900968cf39c9fcf7a485f951c Mon Sep 17 00:00:00 2001 From: NETFLIE Date: Sat, 10 Sep 2022 21:17:44 +0200 Subject: [PATCH 01/12] Initial commit --- .editorconfig | 15 +++++ .gitattributes | 10 +++ .github/workflows/tests.yml | 32 +++++++++ .gitignore | 6 ++ .scrutinizer.yml | 21 ++++++ .styleci.yml | 1 + CHANGELOG.md | 7 ++ CONTRIBUTING.md | 55 +++++++++++++++ LICENSE.md | 21 ++++++ README.md | 75 +++++++++++++++++---- composer.json | 40 +++++++++++ phpunit.xml.dist | 29 ++++++++ src/Exceptions/CouldNotSendNotification.php | 11 +++ src/WhatsAppChannel.php | 31 +++++++++ src/WhatsAppMessage.php | 10 +++ src/WhatsAppServiceProvider.php | 40 +++++++++++ 16 files changed, 392 insertions(+), 12 deletions(-) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/workflows/tests.yml create mode 100644 .gitignore create mode 100644 .scrutinizer.yml create mode 100644 .styleci.yml create mode 100755 CHANGELOG.md create mode 100755 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 composer.json create mode 100644 phpunit.xml.dist create mode 100644 src/Exceptions/CouldNotSendNotification.php create mode 100644 src/WhatsAppChannel.php create mode 100644 src/WhatsAppMessage.php create mode 100644 src/WhatsAppServiceProvider.php diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..cd8eb86e --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..b2638710 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.gitattributes export-ignore +/.gitignore export-ignore +/.travis.yml export-ignore +/phpunit.xml.dist export-ignore +/.scrutinizer.yml export-ignore +/tests export-ignore diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 00000000..f9ff88d2 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,32 @@ +name: PHPUnit tests + +on: + - push + - pull_request + +jobs: + tests: + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + php: [7.2, 7.3, 7.4, 8.0] + + name: Tests on PHP ${{ matrix.php }} - ${{ matrix.stability }} + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + tools: composer:v2 + coverage: none + + - name: Install dependencies + run: composer update --prefer-source --no-interaction --no-progress + + - name: Execute tests + run: vendor/bin/phpunit --verbose diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..616e6d3b --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/vendor +build +composer.phar +composer.lock +.DS_Store +.phpunit.result.cache diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 00000000..6fad5be9 --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,21 @@ +filter: + excluded_paths: [tests/*] + +checks: + php: + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true + +tools: + external_code_coverage: true diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 00000000..0285f179 --- /dev/null +++ b/.styleci.yml @@ -0,0 +1 @@ +preset: laravel diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100755 index 00000000..c9967d9b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +All notable changes to `whatsapp` will be documented in this file + +## 1.0.0 - 201X-XX-XX + +- initial release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100755 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..3d2f65a4 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) Álex Albarca + +> 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..f17f0047 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,68 @@ -# New Notification Channels +# WhatsApp notification 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/laravel-notification-channels/whatsapp.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/whatsapp) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/laravel-notification-channels/whatsapp/master.svg?style=flat-square)](https://travis-ci.org/laravel-notification-channels/whatsapp) +[![StyleCI](https://styleci.io/repos/535096163/shield)](https://styleci.io/repos/535096163) +[![Quality Score](https://img.shields.io/scrutinizer/g/laravel-notification-channels/whatsapp.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/whatsapp) +[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/laravel-notification-channels/whatsapp/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/whatsapp/?branch=master) +[![Total Downloads](https://img.shields.io/packagist/dt/laravel-notification-channels/whatsapp.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/whatsapp) -### 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 [WhatsApp Cloud API](https://developers.facebook.com/docs/whatsapp/cloud-api/) with Laravel. -## 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) + - [Setting up the WhatsApp service](#setting-up-the-WhatsApp-service) +- [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 + +Please also include the steps for any third-party service setup that's required for this package. + +### Setting up the WhatsApp service + +Optionally include a few steps how users can set up the service. + +## Usage + +Some code examples, make it clear how to use the package + +### Available Message methods + +A list of all available options + +## 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 alex@netflie.es instead of using the issue tracker. + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) for details. + +## Credits + +- [Álex Albarca](https://github.com/netflie) +- [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..1e0578eb --- /dev/null +++ b/composer.json @@ -0,0 +1,40 @@ +{ + "name": "laravel-notification-channels/whatsapp", + "description": "Laravel notification driver for WhatsApp", + "homepage": "https://github.com/laravel-notification-channels/whatsapp", + "license": "MIT", + "authors": [ + { + "name": "Álex Albarca", + "email": "alex@netflie.es", + "homepage": "https://www.netflie.es", + "role": "Developer" + } + ], + "require": { + "php": ">=7.2", + "illuminate/notifications": "~6.0 || ~7.0 || ~8.0", + "illuminate/support": "~6.0 || ~7.0 || ~8.0" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "phpunit/phpunit": "^9.0" + }, + "autoload": { + "psr-4": { + "NotificationChannels\\WhatsApp\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "NotificationChannels\\WhatsApp\\Test\\": "tests" + } + }, + "scripts": { + "test": "phpunit", + "test:coverage": "phpunit --coverage-text --coverage-clover=coverage.clover" + }, + "config": { + "sort-packages": true + } +} diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 00000000..2adba9e7 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,29 @@ + + + + + tests + + + + + src/ + + + + + + + + + + diff --git a/src/Exceptions/CouldNotSendNotification.php b/src/Exceptions/CouldNotSendNotification.php new file mode 100644 index 00000000..72cfceb7 --- /dev/null +++ b/src/Exceptions/CouldNotSendNotification.php @@ -0,0 +1,11 @@ +error) { // replace this by the code need to check for errors +// throw CouldNotSendNotification::serviceRespondedWithAnError($response); +// } + } +} diff --git a/src/WhatsAppMessage.php b/src/WhatsAppMessage.php new file mode 100644 index 00000000..ef482ea4 --- /dev/null +++ b/src/WhatsAppMessage.php @@ -0,0 +1,10 @@ +app->when(Channel::class) + ->needs(Pusher::class) + ->give(function () { + $pusherConfig = config('broadcasting.connections.pusher'); + + return new Pusher( + $pusherConfig['key'], + $pusherConfig['secret'], + $pusherConfig['app_id'] + ); + }); + */ + + } + + /** + * Register the application services. + */ + public function register() + { + } +} From b7aad6e19d72b8df9712b16b022c1d25e365a5a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Wed, 16 Nov 2022 18:10:26 +0100 Subject: [PATCH 02/12] add phpcs fixer config --- .php-cs-fixer.dist.php | 40 ++++++++++++++++++++++++++++++++++++++++ composer.json | 2 +- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 .php-cs-fixer.dist.php diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 00000000..b8f9f979 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,40 @@ +in([ + __DIR__ . '/src', + __DIR__ . '/tests', + ]) + ->name('*.php') + ->ignoreDotFiles(true) + ->ignoreVCS(true); +; + +return (new PhpCsFixer\Config()) + ->setRules([ + '@PSR12' => true, + 'array_syntax' => ['syntax' => 'short'], + 'ordered_imports' => ['sort_algorithm' => 'alpha'], + 'no_unused_imports' => true, + 'not_operator_with_successor_space' => false, + 'trailing_comma_in_multiline' => true, + 'phpdoc_scalar' => true, + 'unary_operator_spaces' => true, + 'binary_operator_spaces' => true, + 'blank_line_before_statement' => [ + 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], + ], + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_var_without_name' => true, + 'class_attributes_separation' => [ + 'elements' => [ + 'method' => 'one', + ], + ], + 'method_argument_space' => [ + 'on_multiline' => 'ensure_fully_multiline', + 'keep_multiple_spaces_after_comma' => true, + ], + 'single_trait_insert_per_statement' => true, + ]) + ->setFinder($finder); \ No newline at end of file diff --git a/composer.json b/composer.json index 1e0578eb..36c25b1f 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ } ], "require": { - "php": ">=7.2", + "php": ">=7.4", "illuminate/notifications": "~6.0 || ~7.0 || ~8.0", "illuminate/support": "~6.0 || ~7.0 || ~8.0" }, From e97954902e89ca36d39a4d29adab2e781fce384d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Wed, 16 Nov 2022 21:07:16 +0100 Subject: [PATCH 03/12] register WhatsAppCloudApi superclass --- composer.json | 17 ++++++++++++++++- src/WhatsAppServiceProvider.php | 34 +++++++++------------------------ 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/composer.json b/composer.json index 36c25b1f..6ca57320 100644 --- a/composer.json +++ b/composer.json @@ -3,6 +3,13 @@ "description": "Laravel notification driver for WhatsApp", "homepage": "https://github.com/laravel-notification-channels/whatsapp", "license": "MIT", + "keywords": [ + "whatsapp notification", + "laravel", + "whatsapp", + "notification", + "whatsapp notifications channel" + ], "authors": [ { "name": "Álex Albarca", @@ -14,7 +21,8 @@ "require": { "php": ">=7.4", "illuminate/notifications": "~6.0 || ~7.0 || ~8.0", - "illuminate/support": "~6.0 || ~7.0 || ~8.0" + "illuminate/support": "~6.0 || ~7.0 || ~8.0", + "netflie/whatsapp-cloud-api": "^1.3.1" }, "require-dev": { "mockery/mockery": "^1.0", @@ -30,6 +38,13 @@ "NotificationChannels\\WhatsApp\\Test\\": "tests" } }, + "extra": { + "laravel": { + "providers": [ + "NotificationChannels\\WhatsApp\\WhatsAppServiceProvider" + ] + } + }, "scripts": { "test": "phpunit", "test:coverage": "phpunit --coverage-text --coverage-clover=coverage.clover" diff --git a/src/WhatsAppServiceProvider.php b/src/WhatsAppServiceProvider.php index d96068b2..028b6a35 100644 --- a/src/WhatsAppServiceProvider.php +++ b/src/WhatsAppServiceProvider.php @@ -3,38 +3,22 @@ namespace NotificationChannels\WhatsApp; use Illuminate\Support\ServiceProvider; +use Netflie\WhatsAppCloudApi\WhatsAppCloudApi; class WhatsAppServiceProvider extends ServiceProvider { - /** - * Bootstrap the application services. - */ - public function boot() - { - // Bootstrap code here. - - /** - * Here's some example code we use for the pusher package. - - $this->app->when(Channel::class) - ->needs(Pusher::class) - ->give(function () { - $pusherConfig = config('broadcasting.connections.pusher'); - - return new Pusher( - $pusherConfig['key'], - $pusherConfig['secret'], - $pusherConfig['app_id'] - ); - }); - */ - - } - /** * Register the application services. */ public function register() { + $config = [ + 'from_phone_number_id' => $this->app->make('config')->get('services.whatsapp.from-phone-number-id'), + 'access_token' => $this->app->make('config')->get('services.whatsapp.token'), + 'graph_version' => $this->app->make('config')->get('services.whatsapp.graph_version', WhatsAppCloudApi::DEFAULT_GRAPH_VERSION), + 'timeout' => $this->app->make('config')->get('services.whatsapp.timeout'), + ]; + + $this->app->bind(WhatsAppCloudApi::class, static fn () => new WhatsAppCloudApi($config)); } } From dd9a9acaf2307a81689a8bb12b35283d54383de4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Wed, 16 Nov 2022 21:14:32 +0100 Subject: [PATCH 04/12] create whatsapp template message --- src/WhatsAppMessage.php | 10 ---- src/WhatsAppTemplate.php | 96 ++++++++++++++++++++++++++++++++++ tests/WhatsAppTemplateTest.php | 88 +++++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 10 deletions(-) delete mode 100644 src/WhatsAppMessage.php create mode 100644 src/WhatsAppTemplate.php create mode 100644 tests/WhatsAppTemplateTest.php diff --git a/src/WhatsAppMessage.php b/src/WhatsAppMessage.php deleted file mode 100644 index ef482ea4..00000000 --- a/src/WhatsAppMessage.php +++ /dev/null @@ -1,10 +0,0 @@ -to = $to; + $this->name = $name; + $this->language = $language; + $this->components = [ + 'header' => [], + 'body' => [], + ]; + } + + public static function create($to = '', $name = '', $language = 'en_US'): self + { + return new self($to, $name, $language); + } + + public function to(string $to): self + { + $this->to = $to; + + return $this; + } + + public function name(string $name): self + { + $this->name = $name; + + return $this; + } + + public function language(string $language): self + { + $this->language = $language; + + return $this; + } + + public function header(Component $component): self + { + $this->components['header'][] = $component->toArray(); + + return $this; + } + + public function body(Component $component): self + { + $this->components['body'][] = $component->toArray(); + + return $this; + } + + public function recipient(): ?string + { + return $this->to; + } + + public function configuredName(): ?string + { + return $this->name; + } + + public function configuredLanguage(): string + { + return $this->language; + } + + public function components(): CloudApiComponent + { + return new CloudApiComponent( + $this->components['header'], + $this->components['body'] + ); + } + + public function hasRecipient(): bool + { + return !empty($this->to); + } +} diff --git a/tests/WhatsAppTemplateTest.php b/tests/WhatsAppTemplateTest.php new file mode 100644 index 00000000..83e26c36 --- /dev/null +++ b/tests/WhatsAppTemplateTest.php @@ -0,0 +1,88 @@ +to('346762014584'); + + $this->assertEquals('346762014584', $message->recipient()); + } + + /** @test */ + public function the_notification_name_can_be_set() + { + $message = WhatsAppTemplate::create() + ->name('invoice_created'); + + $this->assertEquals('invoice_created', $message->configuredName()); + } + + /** @test */ + public function the_notification_language_can_be_set() + { + $message = WhatsAppTemplate::create() + ->language('es_fake'); + + $this->assertEquals('es_fake', $message->configuredLanguage()); + } + + /** @test */ + public function the_notification_component_header_can_be_set() + { + $message = WhatsAppTemplate::create() + ->header(new Currency(10, 'USD')) + ->header(new Document('https://netflie.es/document.pdf')) + ->header(new Video('https://netflie.es/video.webm')); + + $expectedHeader = [ + [ + 'type' => 'currency', + 'currency' => ['amount_1000' => 10000, 'code' => 'USD'], + ], + [ + 'type' => 'document', + 'document' => ['link' => 'https://netflie.es/document.pdf'], + ], + [ + 'type' => 'video', + 'video' => ['link' => 'https://netflie.es/video.webm'], + ], + ]; + + $this->assertEquals($expectedHeader, $message->components()->header()); + } + + /** @test */ + public function the_notification_component_body_can_be_set() + { + $message = WhatsAppTemplate::create() + ->body(new Text('Mr Jones')) + ->body(new Image('https://netflie.es/image.png')); + + $expectedHeader = [ + [ + 'type' => 'text', + 'text' => 'Mr Jones', + ], + [ + 'type' => 'image', + 'image' => ['link' => 'https://netflie.es/image.png'], + ], + ]; + + $this->assertEquals($expectedHeader, $message->components()->body()); + } +} From 9595c1a084fa3464039e941f8948a2fdfc1353b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Sat, 19 Nov 2022 23:18:51 +0100 Subject: [PATCH 05/12] add template components --- src/Component/Component.php | 8 +++++ src/Component/Currency.php | 30 +++++++++++++++++ src/Component/DateTime.php | 26 +++++++++++++++ src/Component/Document.php | 41 ++++++++++++++++++++++++ src/Component/Image.php | 26 +++++++++++++++ src/Component/Text.php | 21 ++++++++++++ src/Component/Video.php | 26 +++++++++++++++ src/Exceptions/UnsupportedMediaValue.php | 14 ++++++++ src/WhatsAppTemplate.php | 34 ++++++++++++++------ tests/Component/CurrencyTest.php | 25 +++++++++++++++ tests/Component/DateTimeTest.php | 24 ++++++++++++++ tests/Component/DocumentTest.php | 31 ++++++++++++++++++ tests/Component/ImageTest.php | 23 +++++++++++++ tests/Component/VideoTest.php | 23 +++++++++++++ 14 files changed, 343 insertions(+), 9 deletions(-) create mode 100644 src/Component/Component.php create mode 100644 src/Component/Currency.php create mode 100644 src/Component/DateTime.php create mode 100644 src/Component/Document.php create mode 100644 src/Component/Image.php create mode 100644 src/Component/Text.php create mode 100644 src/Component/Video.php create mode 100644 src/Exceptions/UnsupportedMediaValue.php create mode 100644 tests/Component/CurrencyTest.php create mode 100644 tests/Component/DateTimeTest.php create mode 100644 tests/Component/DocumentTest.php create mode 100644 tests/Component/ImageTest.php create mode 100644 tests/Component/VideoTest.php diff --git a/src/Component/Component.php b/src/Component/Component.php new file mode 100644 index 00000000..e41e0195 --- /dev/null +++ b/src/Component/Component.php @@ -0,0 +1,8 @@ +amount = $amount; + $this->code = $code; + } + + public function toArray(): array + { + return [ + 'type' => 'currency', + 'currency' => [ + 'code' => $this->code, + 'amount_1000' => (int) ($this->amount * 1000), + ], + ]; + } +} diff --git a/src/Component/DateTime.php b/src/Component/DateTime.php new file mode 100644 index 00000000..d67d23c3 --- /dev/null +++ b/src/Component/DateTime.php @@ -0,0 +1,26 @@ +dateTime = $dateTime; + $this->format = $format; + } + + public function toArray(): array + { + return [ + 'type' => 'date_time', + 'date_time' => [ + 'fallback_value' => $this->dateTime->format($this->format), + ], + ]; + } +} diff --git a/src/Component/Document.php b/src/Component/Document.php new file mode 100644 index 00000000..bf08cb77 --- /dev/null +++ b/src/Component/Document.php @@ -0,0 +1,41 @@ +link = $link; + } + + public function toArray(): array + { + return [ + 'type' => 'document', + 'document' => [ + 'link' => $this->link, + ], + ]; + } +} diff --git a/src/Component/Image.php b/src/Component/Image.php new file mode 100644 index 00000000..bece3013 --- /dev/null +++ b/src/Component/Image.php @@ -0,0 +1,26 @@ +link = $link; + } + + public function toArray(): array + { + return [ + 'type' => 'image', + 'image' => [ + 'link' => $this->link, + ], + ]; + } +} diff --git a/src/Component/Text.php b/src/Component/Text.php new file mode 100644 index 00000000..e8c20ee4 --- /dev/null +++ b/src/Component/Text.php @@ -0,0 +1,21 @@ +text = $text; + } + + public function toArray(): array + { + return [ + 'type' => 'text', + 'text' => $this->text, + ]; + } +} diff --git a/src/Component/Video.php b/src/Component/Video.php new file mode 100644 index 00000000..ebc8d5b2 --- /dev/null +++ b/src/Component/Video.php @@ -0,0 +1,26 @@ +link = $link; + } + + public function toArray(): array + { + return [ + 'type' => 'video', + 'video' => [ + 'link' => $this->link, + ], + ]; + } +} diff --git a/src/Exceptions/UnsupportedMediaValue.php b/src/Exceptions/UnsupportedMediaValue.php new file mode 100644 index 00000000..e1f4bdfb --- /dev/null +++ b/src/Exceptions/UnsupportedMediaValue.php @@ -0,0 +1,14 @@ +to = $to; $this->name = $name; diff --git a/tests/Component/CurrencyTest.php b/tests/Component/CurrencyTest.php new file mode 100644 index 00000000..1e27a7de --- /dev/null +++ b/tests/Component/CurrencyTest.php @@ -0,0 +1,25 @@ + 'currency', + 'currency' => [ + 'amount_1000' => 10250, + 'code' => 'EUR', + ], + ]; + + $this->assertEquals($expectedValue, $currency->toArray()); + } +} diff --git a/tests/Component/DateTimeTest.php b/tests/Component/DateTimeTest.php new file mode 100644 index 00000000..acadd075 --- /dev/null +++ b/tests/Component/DateTimeTest.php @@ -0,0 +1,24 @@ + 'date_time', + 'date_time' => [ + 'fallback_value' => $dateTime->format('Y-m-d H:i:s'), + ], + ]; + + $this->assertEquals($expectedValue, $currency->toArray()); + } +} diff --git a/tests/Component/DocumentTest.php b/tests/Component/DocumentTest.php new file mode 100644 index 00000000..5e886c04 --- /dev/null +++ b/tests/Component/DocumentTest.php @@ -0,0 +1,31 @@ + 'document', + 'document' => [ + 'link' => 'https://www.netflie.es/document.pdf', + ], + ]; + + $this->assertEquals($expectedValue, $document->toArray()); + } + + /** @test */ + public function the_document_link_is_a_unsupported_document() + { + $this->expectException(UnsupportedMediaValue::class); + new Document('https://www.netflie.es/document.doc'); + } +} diff --git a/tests/Component/ImageTest.php b/tests/Component/ImageTest.php new file mode 100644 index 00000000..ccf7ab19 --- /dev/null +++ b/tests/Component/ImageTest.php @@ -0,0 +1,23 @@ + 'image', + 'image' => [ + 'link' => 'https://netflie.es/image.png', + ], + ]; + + $this->assertEquals($expectedValue, $currency->toArray()); + } +} diff --git a/tests/Component/VideoTest.php b/tests/Component/VideoTest.php new file mode 100644 index 00000000..8ce3434e --- /dev/null +++ b/tests/Component/VideoTest.php @@ -0,0 +1,23 @@ + 'video', + 'video' => [ + 'link' => 'https://netflie.es/video.webm', + ], + ]; + + $this->assertEquals($expectedValue, $currency->toArray()); + } +} From eacad045381c3b3827b152f44277eb10c1d64616 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Sat, 19 Nov 2022 23:21:15 +0100 Subject: [PATCH 06/12] add Laravel Notification WhatsAppChannel --- src/Exceptions/CouldNotSendNotification.php | 6 +- src/WhatsAppChannel.php | 48 ++++-- tests/Support/DummyNotifiable.php | 13 ++ tests/Support/DummyNotification.php | 16 ++ .../DummyNotificationWithoutRecipient.php | 15 ++ tests/WhatsAppChannelTest.php | 142 ++++++++++++++++++ 6 files changed, 224 insertions(+), 16 deletions(-) create mode 100644 tests/Support/DummyNotifiable.php create mode 100644 tests/Support/DummyNotification.php create mode 100644 tests/Support/DummyNotificationWithoutRecipient.php create mode 100644 tests/WhatsAppChannelTest.php diff --git a/src/Exceptions/CouldNotSendNotification.php b/src/Exceptions/CouldNotSendNotification.php index 72cfceb7..375a4dbf 100644 --- a/src/Exceptions/CouldNotSendNotification.php +++ b/src/Exceptions/CouldNotSendNotification.php @@ -2,10 +2,10 @@ namespace NotificationChannels\WhatsApp\Exceptions; -class CouldNotSendNotification extends \Exception +final class CouldNotSendNotification extends \Exception { - public static function serviceRespondedWithAnError($response) + public static function serviceRespondedWithAnError($responseBody) { - return new static("Descriptive error message."); + return new self($responseBody); } } diff --git a/src/WhatsAppChannel.php b/src/WhatsAppChannel.php index 74fbf1a5..62f386f4 100644 --- a/src/WhatsAppChannel.php +++ b/src/WhatsAppChannel.php @@ -2,30 +2,52 @@ namespace NotificationChannels\WhatsApp; -use NotificationChannels\WhatsApp\Exceptions\CouldNotSendNotification; use Illuminate\Notifications\Notification; +use Netflie\WhatsAppCloudApi\Response; +use Netflie\WhatsAppCloudApi\Response\ResponseException; +use Netflie\WhatsAppCloudApi\WhatsAppCloudApi; +use NotificationChannels\WhatsApp\Exceptions\CouldNotSendNotification; class WhatsAppChannel { - public function __construct() + /* + * HTTP WhatsApp Cloud API wrapper + */ + private WhatsAppCloudApi $whatsapp; + + public function __construct(WhatsAppCloudApi $whatsapp) { - // Initialisation code here + $this->whatsapp = $whatsapp; } /** * Send the given notification. - * - * @param mixed $notifiable - * @param \Illuminate\Notifications\Notification $notification - * - * @throws \NotificationChannels\WhatsApp\Exceptions\CouldNotSendNotification */ - public function send($notifiable, Notification $notification) + public function send($notifiable, Notification $notification): ?Response { - //$response = [a call to the api of your notification send] + // @phpstan-ignore-next-line + $message = $notification->toWhatsApp($notifiable); + + if (!$message->hasRecipient()) { + $to = $notifiable->routeNotificationFor('whatsapp', $notification) + ?? $notifiable->routeNotificationFor(self::class, $notification); + + if (!$to) { + return null; + } + + $message->to($to); + } -// if ($response->error) { // replace this by the code need to check for errors -// throw CouldNotSendNotification::serviceRespondedWithAnError($response); -// } + try { + return $this->whatsapp->sendTemplate( + $message->recipient(), + $message->configuredName(), + $message->configuredLanguage(), + $message->components() + ); + } catch (ResponseException $e) { + throw CouldNotSendNotification::serviceRespondedWithAnError($e->response()->body()); + } } } diff --git a/tests/Support/DummyNotifiable.php b/tests/Support/DummyNotifiable.php new file mode 100644 index 00000000..097eafe7 --- /dev/null +++ b/tests/Support/DummyNotifiable.php @@ -0,0 +1,13 @@ +name('invoice_created') + ->to('34678741298'); + } +} diff --git a/tests/Support/DummyNotificationWithoutRecipient.php b/tests/Support/DummyNotificationWithoutRecipient.php new file mode 100644 index 00000000..9cf9b39c --- /dev/null +++ b/tests/Support/DummyNotificationWithoutRecipient.php @@ -0,0 +1,15 @@ +name('invoice_created'); + } +} diff --git a/tests/WhatsAppChannelTest.php b/tests/WhatsAppChannelTest.php new file mode 100644 index 00000000..d6f216af --- /dev/null +++ b/tests/WhatsAppChannelTest.php @@ -0,0 +1,142 @@ +httpClient = \Mockery::mock(ClientHandler::class); + + $this->whatsapp = new WhatsAppCloudApi([ + 'from_phone_number_id' => '34676202545', + 'access_token' => 'super-secret', + 'client_handler' => $this->httpClient, + ]); + $this->channel = new WhatsAppChannel($this->whatsapp); + } + + /** @test */ + public function it_can_send_a_notification() + { + $notifiable = $this->getMockForTrait(Notifiable::class); + $notification = new DummyNotification(); + + $body = [ + 'messaging_product' => 'whatsapp', + 'recipient_type' => 'individual', + 'to' => $notification->toWhatsApp($notifiable)->recipient(), + 'type' => 'template', + 'template' => [ + 'name' => $notification->toWhatsApp($notifiable)->configuredName(), + 'language' => ['code' => $notification->toWhatsApp($notifiable)->configuredLanguage()], + 'components' => [], + ], + ]; + $headers = [ + 'Authorization' => 'Bearer super-secret', + 'Content-Type' => 'application/json', + ]; + $expectedResponse = new RawResponse($headers, json_encode($body), 200); + + $response = $this->sendMockNotification($notifiable, $notification, $expectedResponse); + + $this->assertEquals(json_encode($body), $response->body()); + $this->assertEquals(200, $response->httpStatusCode()); + $this->assertNotEmpty($notification->toWhatsApp($notifiable)->recipient()); + $this->assertNotEmpty($notification->toWhatsApp($notifiable)->configuredName()); + $this->assertNotEmpty($notification->toWhatsApp($notifiable)->configuredLanguage()); + } + + /** @test */ + public function it_can_send_a_notification_if_notifiable_provide_a_recipient_from_route() + { + $notifiable = new DummyNotifiable(); + $notification = new DummyNotificationWithoutRecipient(); + + $body = [ + 'messaging_product' => 'whatsapp', + 'recipient_type' => 'individual', + 'to' => $notifiable->routeNotificationForWhatsApp(), + 'type' => 'template', + 'template' => [ + 'name' => $notification->toWhatsApp($notifiable)->configuredName(), + 'language' => ['code' => $notification->toWhatsApp($notifiable)->configuredLanguage()], + 'components' => [], + ], + ]; + $headers = [ + 'Authorization' => 'Bearer super-secret', + 'Content-Type' => 'application/json', + ]; + $expectedResponse = new RawResponse($headers, json_encode($body), 200); + + $response = $this->sendMockNotification($notifiable, $notification, $expectedResponse); + + $this->assertEquals(json_encode($body), $response->body()); + $this->assertEquals(200, $response->httpStatusCode()); + $this->assertNotEmpty($body['to']); + $this->assertNotEmpty($notification->toWhatsApp($notifiable)->configuredName()); + $this->assertNotEmpty($notification->toWhatsApp($notifiable)->configuredLanguage()); + } + + /** @test */ + public function it_does_not_send_a_notification_if_the_notifiable_does_not_provide_a_recipient() + { + $notifiable = $this->getMockForTrait(Notifiable::class); + $notification = new DummyNotificationWithoutRecipient(); + + $httpClient = \Mockery::mock(ClientHandler::class); + $httpClient->shouldNotHaveReceived('send'); + + $response = $this->channel->send($notifiable, $notification); + + $this->assertNull($response); + } + + /** @test */ + public function send_notification_failed() + { + $notifiable = $this->getMockForTrait(Notifiable::class); + $notification = new DummyNotification(); + $expectedResponse = new RawResponse([], json_encode(['error' => true]), 500); + + $this->expectException(CouldNotSendNotification::class); + $response = $this->sendMockNotification($notifiable, $notification, $expectedResponse); + + $this->assertNull($response); + } + + private function sendMockNotification( + $notifiable, + Notification $notification, + RawResponse $expectedResponse + ) { + $this->httpClient + ->shouldReceive('send') + ->once() + ->andReturns($expectedResponse); + + return $this->channel->send($notifiable, $notification); + } +} From 921b34ed053ab52aed96cfa87533652e9494544e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Sat, 19 Nov 2022 23:27:42 +0100 Subject: [PATCH 07/12] add phpstan --- composer.json | 4 +++- phpstan-baseline.neon | 0 phpstan.neon.dist | 9 +++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 phpstan-baseline.neon create mode 100644 phpstan.neon.dist diff --git a/composer.json b/composer.json index 6ca57320..06e466ac 100644 --- a/composer.json +++ b/composer.json @@ -26,6 +26,7 @@ }, "require-dev": { "mockery/mockery": "^1.0", + "phpstan/phpstan": "^1.9", "phpunit/phpunit": "^9.0" }, "autoload": { @@ -47,7 +48,8 @@ }, "scripts": { "test": "phpunit", - "test:coverage": "phpunit --coverage-text --coverage-clover=coverage.clover" + "test:coverage": "phpunit --coverage-text --coverage-clover=coverage.clover", + "analyse": "phpstan analyse" }, "config": { "sort-packages": true diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon new file mode 100644 index 00000000..e69de29b diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 00000000..79d7ba24 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,9 @@ +includes: + - phpstan-baseline.neon + +parameters: + level: 5 + paths: + - src + tmpDir: build/phpstan + checkMissingIterableValueType: false \ No newline at end of file From d7628ad2a01a18bf5879de4eaf5ba572cb395a9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Sun, 20 Nov 2022 00:21:18 +0100 Subject: [PATCH 08/12] add github actions --- .github/dependabot.yml | 18 ++++++++++++++++++ .github/workflows/dependency-review.yml | 20 ++++++++++++++++++++ .github/workflows/tests.yml | 11 +++++++---- 3 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/dependency-review.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..7a81a200 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,18 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "composer" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "monthly" + + - package-ecosystem: "github-actions" + # Workflow files stored in the + # default location of `.github/workflows` + directory: "/" + schedule: + interval: "monthly" \ No newline at end of file diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 00000000..f5c89e3d --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,20 @@ +# Dependency Review Action +# +# This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. +# +# Source repository: https://github.com/actions/dependency-review-action +# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement +name: 'Dependency Review' +on: [pull_request] + +permissions: + contents: read + +jobs: + dependency-review: + runs-on: ubuntu-latest + steps: + - name: 'Checkout Repository' + uses: actions/checkout@v3 + - name: 'Dependency Review' + uses: actions/dependency-review-action@v3 \ No newline at end of file diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f9ff88d2..9d7c7063 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,4 +1,4 @@ -name: PHPUnit tests +name: Tests on: - push @@ -10,19 +10,19 @@ jobs: strategy: fail-fast: true matrix: - php: [7.2, 7.3, 7.4, 8.0] + php: [7.4, 8.0, 8.1] name: Tests on PHP ${{ matrix.php }} - ${{ matrix.stability }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} - tools: composer:v2 + tools: composer:v2, phpstan coverage: none - name: Install dependencies @@ -30,3 +30,6 @@ jobs: - name: Execute tests run: vendor/bin/phpunit --verbose + + - name: Run PHPStan + run: phpstan analyse src --level=5 From 52cfa868d69655ce99e5eb852042d31d716efbbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Sun, 20 Nov 2022 00:53:38 +0100 Subject: [PATCH 09/12] set phpdoc_summary and not_operator_with_successor_space phpcs rules to true --- .gitignore | 1 + .php-cs-fixer.dist.php | 3 ++- src/Component/Document.php | 4 ++-- src/Component/Image.php | 2 +- src/Component/Video.php | 2 +- src/WhatsAppChannel.php | 4 ++-- src/WhatsAppTemplate.php | 2 +- 7 files changed, 10 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 616e6d3b..f8835213 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ composer.phar composer.lock .DS_Store .phpunit.result.cache +.php-cs-fixer.cache \ No newline at end of file diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index b8f9f979..055db6a8 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -16,7 +16,7 @@ 'array_syntax' => ['syntax' => 'short'], 'ordered_imports' => ['sort_algorithm' => 'alpha'], 'no_unused_imports' => true, - 'not_operator_with_successor_space' => false, + 'not_operator_with_successor_space' => true, 'trailing_comma_in_multiline' => true, 'phpdoc_scalar' => true, 'unary_operator_spaces' => true, @@ -36,5 +36,6 @@ 'keep_multiple_spaces_after_comma' => true, ], 'single_trait_insert_per_statement' => true, + 'phpdoc_summary' => true, ]) ->setFinder($finder); \ No newline at end of file diff --git a/src/Component/Document.php b/src/Component/Document.php index bf08cb77..c6a27a37 100644 --- a/src/Component/Document.php +++ b/src/Component/Document.php @@ -10,7 +10,7 @@ class Document extends Component /** * Link to the document; e.g. https://URL - * Only PDF documents are supported + * Only PDF documents are supported. */ protected string $link; @@ -22,7 +22,7 @@ public function __construct(string $link) $extension = pathinfo($link, PATHINFO_EXTENSION); - if (!in_array($extension, static::SUPPORTED_EXTENSIONS)) { + if (! in_array($extension, static::SUPPORTED_EXTENSIONS)) { throw new UnsupportedMediaValue($link, 'document', 'Only PDF documents are supported.'); } diff --git a/src/Component/Image.php b/src/Component/Image.php index bece3013..4712a748 100644 --- a/src/Component/Image.php +++ b/src/Component/Image.php @@ -5,7 +5,7 @@ class Image extends Component { /** - * Link to the image; e.g. https://URL + * Link to the image; e.g. https://URL. */ protected string $link; diff --git a/src/Component/Video.php b/src/Component/Video.php index ebc8d5b2..2e6537a6 100644 --- a/src/Component/Video.php +++ b/src/Component/Video.php @@ -5,7 +5,7 @@ class Video extends Component { /** - * Link to the video; e.g. https://URL + * Link to the video; e.g. https://URL. */ protected string $link; diff --git a/src/WhatsAppChannel.php b/src/WhatsAppChannel.php index 62f386f4..e18fdb11 100644 --- a/src/WhatsAppChannel.php +++ b/src/WhatsAppChannel.php @@ -28,11 +28,11 @@ public function send($notifiable, Notification $notification): ?Response // @phpstan-ignore-next-line $message = $notification->toWhatsApp($notifiable); - if (!$message->hasRecipient()) { + if (! $message->hasRecipient()) { $to = $notifiable->routeNotificationFor('whatsapp', $notification) ?? $notifiable->routeNotificationFor(self::class, $notification); - if (!$to) { + if (! $to) { return null; } diff --git a/src/WhatsAppTemplate.php b/src/WhatsAppTemplate.php index 018e328f..6375c84b 100644 --- a/src/WhatsAppTemplate.php +++ b/src/WhatsAppTemplate.php @@ -107,6 +107,6 @@ public function components(): CloudApiComponent public function hasRecipient(): bool { - return !empty($this->to); + return ! empty($this->to); } } From 6e0dd31ee3fba448515793aaa0fc880f416eafb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Tue, 29 Nov 2022 06:54:47 +0100 Subject: [PATCH 10/12] Remove support for Laravel 6.0 & 7.0 --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 06e466ac..84a17014 100644 --- a/composer.json +++ b/composer.json @@ -20,8 +20,8 @@ ], "require": { "php": ">=7.4", - "illuminate/notifications": "~6.0 || ~7.0 || ~8.0", - "illuminate/support": "~6.0 || ~7.0 || ~8.0", + "illuminate/notifications": "~8.0 || ~9.0", + "illuminate/support": "~8.0 || ~9.0", "netflie/whatsapp-cloud-api": "^1.3.1" }, "require-dev": { From f5f45aad4a024b28eb95a154d7095480bedbc5e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Thu, 8 Dec 2022 15:55:27 +0100 Subject: [PATCH 11/12] Add a component factory --- src/Component.php | 39 ++++++++++++++++++++++++++++ tests/ComponentTest.php | 57 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 src/Component.php create mode 100644 tests/ComponentTest.php diff --git a/src/Component.php b/src/Component.php new file mode 100644 index 00000000..36e37d16 --- /dev/null +++ b/src/Component.php @@ -0,0 +1,39 @@ +assertInstanceOf(Component\Currency::class, $component); + } + + /** @test */ + public function it_can_return_a_datetime_component() + { + $component = Component::dateTime(new \DateTimeImmutable()); + + $this->assertInstanceOf(Component\DateTime::class, $component); + } + + /** @test */ + public function it_can_return_a_document_component() + { + $component = Component::document('https://www.netflie.es/my_document.pdf'); + + $this->assertInstanceOf(Component\Document::class, $component); + } + + /** @test */ + public function it_can_return_an_image_component() + { + $component = Component::image('https://www.netflie.es/my_image.png'); + + $this->assertInstanceOf(Component\Image::class, $component); + } + + /** @test */ + public function it_can_return_a_text_component() + { + $component = Component::text('Hey there!'); + + $this->assertInstanceOf(Component\Text::class, $component); + } + + /** @test */ + public function it_can_return_a_vide_component() + { + $component = Component::video('https://www.netflie.es/my_image.webm'); + + $this->assertInstanceOf(Component\Video::class, $component); + } +} From faa352e1f352f927303c637948a8efdb323f336b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lex=20Albarca?= Date: Thu, 8 Dec 2022 17:37:30 +0100 Subject: [PATCH 12/12] Update Readme --- README.md | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 101 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f17f0047..6945f184 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ + # WhatsApp notification channel for Laravel [![Latest Version on Packagist](https://img.shields.io/packagist/v/laravel-notification-channels/whatsapp.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/whatsapp) @@ -26,19 +27,111 @@ This package makes it easy to send notifications using [WhatsApp Cloud API](http ## Installation -Please also include the steps for any third-party service setup that's required for this package. +You can install the package via composer: +``` +composer require laravel-notification-channels/whatsapp +``` +### Setting up the WhatsApp Cloud API + +Create a new Meta application and get your Whatsapp `application token` and `phone number id` following the ["Get Started"](https://developers.facebook.com/docs/whatsapp/cloud-api/get-started?locale=en_US#set-up-developer-assets) guide. Place them inside your `.env` file. To load them, add this to your `config/services.php` file: +```php + [ + 'from-phone-number-id' => env('WHATSAPP_FROM_PHONE_NUMBER_ID'), + 'token' => env('WHATSAPP_TOKEN'), + ], + +]; +``` -### Setting up the WhatsApp service +## Usage -Optionally include a few steps how users can set up the service. +The Whatsapp API only allows you to start conversations if you send a template message. This means that you will only be able to send template notifications from this package. -## Usage +Whatsapp forces you to configure your templates before using them. You can learn how to configure your templates by following Meta's official guide on ["How to create templates"](https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-message-templates). -Some code examples, make it clear how to use the package +### WhatsApp templates sections -### Available Message methods +A template is divided into 4 sections: header, body, footer and buttons. The header, body and buttons accept variables. The footer doesn't accept variables. You can only send variables from this package for the header and body. Support for sending variables for buttons has not yet been added. -A list of all available options +### Components + +You have available several components that can be used to add context (variables) to your templates. The different components can be created with the component factory: + +```php +name('sample_movie_ticket_confirmation') // Name of your configured template + ->header(Component::image('https://lumiere-a.akamaihd.net/v1/images/image_c671e2ee.jpeg')) + ->body(Component::text('Star Wars')) + ->body(Component::dateTime(new \DateTimeImmutable)) + ->body(Component::text('Star Wars')) + ->body(Component::text('5')) + ->to('34676010101'); + } +} +``` ## Changelog @@ -52,7 +145,7 @@ $ composer test ## Security -If you discover any security related issues, please email alex@netflie.es instead of using the issue tracker. +If you discover any security related issues, please email hola@netflie.es instead of using the issue tracker. ## Contributing