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/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 new file mode 100644 index 00000000..9d7c7063 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,35 @@ +name: Tests + +on: + - push + - pull_request + +jobs: + tests: + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + php: [7.4, 8.0, 8.1] + + name: Tests on PHP ${{ matrix.php }} - ${{ matrix.stability }} + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + tools: composer:v2, phpstan + coverage: none + + - name: Install dependencies + run: composer update --prefer-source --no-interaction --no-progress + + - name: Execute tests + run: vendor/bin/phpunit --verbose + + - name: Run PHPStan + run: phpstan analyse src --level=5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..f8835213 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/vendor +build +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 new file mode 100644 index 00000000..055db6a8 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,41 @@ +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' => true, + '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, + 'phpdoc_summary' => true, + ]) + ->setFinder($finder); \ No newline at end of file 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..6945f184 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,161 @@ -# New Notification Channels -### Suggesting a new channel -Have a suggestion or working on a new channel? Please create a new issue for that service. +# WhatsApp notification channel for Laravel -### 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. +[![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) -## Workflow for new channels +This package makes it easy to send notifications using [WhatsApp Cloud API](https://developers.facebook.com/docs/whatsapp/cloud-api/) with Laravel. -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. +## Contents -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](#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) + + +## Installation + +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'), + ], + +]; +``` + +## Usage + +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. + +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). + +### WhatsApp templates sections + +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. + +### 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 + +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 hola@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..84a17014 --- /dev/null +++ b/composer.json @@ -0,0 +1,57 @@ +{ + "name": "laravel-notification-channels/whatsapp", + "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", + "email": "alex@netflie.es", + "homepage": "https://www.netflie.es", + "role": "Developer" + } + ], + "require": { + "php": ">=7.4", + "illuminate/notifications": "~8.0 || ~9.0", + "illuminate/support": "~8.0 || ~9.0", + "netflie/whatsapp-cloud-api": "^1.3.1" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "phpstan/phpstan": "^1.9", + "phpunit/phpunit": "^9.0" + }, + "autoload": { + "psr-4": { + "NotificationChannels\\WhatsApp\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "NotificationChannels\\WhatsApp\\Test\\": "tests" + } + }, + "extra": { + "laravel": { + "providers": [ + "NotificationChannels\\WhatsApp\\WhatsAppServiceProvider" + ] + } + }, + "scripts": { + "test": "phpunit", + "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 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/Component.php b/src/Component.php new file mode 100644 index 00000000..36e37d16 --- /dev/null +++ b/src/Component.php @@ -0,0 +1,39 @@ +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..c6a27a37 --- /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..4712a748 --- /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..2e6537a6 --- /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/CouldNotSendNotification.php b/src/Exceptions/CouldNotSendNotification.php new file mode 100644 index 00000000..375a4dbf --- /dev/null +++ b/src/Exceptions/CouldNotSendNotification.php @@ -0,0 +1,11 @@ +whatsapp = $whatsapp; + } + + /** + * Send the given notification. + */ + public function send($notifiable, Notification $notification): ?Response + { + // @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); + } + + 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/src/WhatsAppServiceProvider.php b/src/WhatsAppServiceProvider.php new file mode 100644 index 00000000..028b6a35 --- /dev/null +++ b/src/WhatsAppServiceProvider.php @@ -0,0 +1,24 @@ + $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)); + } +} diff --git a/src/WhatsAppTemplate.php b/src/WhatsAppTemplate.php new file mode 100644 index 00000000..6375c84b --- /dev/null +++ b/src/WhatsAppTemplate.php @@ -0,0 +1,112 @@ +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/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()); + } +} diff --git a/tests/ComponentTest.php b/tests/ComponentTest.php new file mode 100644 index 00000000..7dd1abc2 --- /dev/null +++ b/tests/ComponentTest.php @@ -0,0 +1,57 @@ +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); + } +} 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); + } +} 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()); + } +}