├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json └── src ├── FcmChannel.php ├── FcmMessage.php └── Resources ├── FcmResource.php └── Notification.php /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes will be documented in this file 4 | 5 | ## 4.0.0 - 2023-10-28 6 | 7 | This version is a pretty substantial rewrite that removes a lot of complexity from the library, makes some features more consistent and increases test coverage. 8 | 9 | * Requires PHP 8.2+, and Laravel 10.x, 10 | * The constructor for `FcmMessage` and `FcmNotification` have changed to use named arguments, 11 | * The custom resource objects have been removed, 12 | * The ability to use a custom client has been standardised. 13 | 14 | ### Re-write your message 15 | 16 | Many of the `set*` methods have been removed and replaced with public properties. The basics you can still use with ease - setting the properties of an `FcmNotification` and setting additional data. If you want to set more explicit options (iOS or Android configuration for example) you will use the `custom` method. 17 | 18 | ```php 19 | return new FcmMessage(notification: new FcmNotification( 20 | title: 'Account Activated', 21 | body: 'Your account has been activated.', 22 | image: 'http://example.com/url-to-image-here.png' 23 | )) 24 | ->data(['data1' => 'value', 'data2' => 'value2']) 25 | ->custom([ 26 | 'android' => [ 27 | 'notification' => [ 28 | 'color' => '#0A0A0A', 29 | ], 30 | 'fcm_options' => [ 31 | 'analytics_label' => 'analytics', 32 | ], 33 | ], 34 | 'apns' => [ 35 | 'fcm_options' => [ 36 | 'analytics_label' => 'analytics', 37 | ], 38 | ], 39 | ]); 40 | ``` 41 | 42 | ### Use a custom client 43 | 44 | The way to change the FCM configuration on the fly now requires passing in an instance of `Kreait\Firebase\Contract\Messaging`. Set it up with your credentials and pass it into a message with `usingClient`. 45 | 46 | ```php 47 | public function toFcm(mixed $notifiable) 48 | { 49 | $client = app(\Kreait\Firebase\Contract\Messaging::class); 50 | 51 | return FcmMessage::create()->usingClient($client); 52 | } 53 | ``` 54 | 55 | ### Handling failures 56 | 57 | Listen to the `Illuminate\Notifications\Events\NotificationFailed` event which will include each individual failure for report you to handle as you need. 58 | 59 | Please re-review the documentation when upgrading to the latest version and make the changes necessary for your app. -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | 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. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[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). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **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. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | 3 | Copyright (c) Chris Bautista 4 | 5 | > Permission is hereby granted, free of charge, to any person obtaining a copy 6 | > of this software and associated documentation files (the "Software"), to deal 7 | > in the Software without restriction, including without limitation the rights 8 | > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | > copies of the Software, and to permit persons to whom the Software is 10 | > furnished to do so, subject to the following conditions: 11 | > 12 | > The above copyright notice and this permission notice shall be included in 13 | > all copies or substantial portions of the Software. 14 | > 15 | > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | > THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel FCM (Firebase Cloud Messaging) Notification Channel 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/laravel-notification-channels/fcm.svg?style=flat-square)](https://packagist.org/packages/coreproc/laravel-notification-channel-fcm) 4 | [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) 5 | [![StyleCI](https://styleci.io/repos/209406724/shield)](https://styleci.io/repos/209406724) 6 | [![Quality Score](https://img.shields.io/scrutinizer/g/laravel-notification-channels/fcm.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/fcm) 7 | [![Total Downloads](https://img.shields.io/packagist/dt/laravel-notification-channels/fcm.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/fcm) 8 | 9 | This package makes it easy to send notifications using [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/) (FCM) with Laravel. 10 | 11 | ## Contents 12 | 13 | - [Installation](#installation) 14 | - [Setting up the FCM service](#setting-up-the-fcm-service) 15 | - [Usage](#usage) 16 | - [Available message methods](#available-message-methods) 17 | - [Custom clients](#custom-clients) 18 | - [Handling errors](#handling-errors) 19 | - [Changelog](#changelog) 20 | - [Testing](#testing) 21 | - [Security](#security) 22 | - [Contributing](#contributing) 23 | - [Credits](#credits) 24 | - [License](#license) 25 | 26 | 27 | ## Installation 28 | 29 | Install this package with Composer: 30 | 31 | ```bash 32 | composer require laravel-notification-channels/fcm 33 | ``` 34 | 35 | ### Setting up the FCM service 36 | 37 | This package now uses the [laravel-firebase](https://github.com/kreait/laravel-firebase) library to authenticate and 38 | make the API calls to Firebase. Follow the [configuration](https://github.com/kreait/laravel-firebase#configuration) 39 | steps specified in their readme before using this. 40 | 41 | After following their configuration steps, make sure that you've specified your `FIREBASE_CREDENTIALS` in your .env 42 | file. 43 | 44 | ## Usage 45 | 46 | After setting up your Firebase credentials, you can now send notifications via FCM by a Notification class and sending 47 | it via the `FcmChannel::class`. Here is an example: 48 | 49 | ```php 50 | use Illuminate\Notifications\Notification; 51 | use NotificationChannels\Fcm\FcmChannel; 52 | use NotificationChannels\Fcm\FcmMessage; 53 | use NotificationChannels\Fcm\Resources\Notification as FcmNotification; 54 | 55 | class AccountActivated extends Notification 56 | { 57 | public function via($notifiable) 58 | { 59 | return [FcmChannel::class]; 60 | } 61 | 62 | public function toFcm($notifiable): FcmMessage 63 | { 64 | return (new FcmMessage(notification: new FcmNotification( 65 | title: 'Account Activated', 66 | body: 'Your account has been activated.', 67 | image: 'http://example.com/url-to-image-here.png' 68 | ))) 69 | ->data(['data1' => 'value', 'data2' => 'value2']) 70 | ->custom([ 71 | 'android' => [ 72 | 'notification' => [ 73 | 'color' => '#0A0A0A', 74 | 'sound' => 'default', 75 | ], 76 | 'fcm_options' => [ 77 | 'analytics_label' => 'analytics', 78 | ], 79 | ], 80 | 'apns' => [ 81 | 'payload' => [ 82 | 'aps' => [ 83 | 'sound' => 'default' 84 | ], 85 | ], 86 | 'fcm_options' => [ 87 | 'analytics_label' => 'analytics', 88 | ], 89 | ], 90 | ]); 91 | } 92 | } 93 | ``` 94 | 95 | You will have to set a `routeNotificationForFcm()` method in your notifiable model. 96 | This method should return the user's FCM token(s) from storage. 97 | For example: 98 | 99 | ```php 100 | class User extends Authenticatable 101 | { 102 | use Notifiable; 103 | 104 | ... 105 | 106 | /** 107 | * Specifies the user's FCM token 108 | * 109 | * @return string|array 110 | */ 111 | public function routeNotificationForFcm() 112 | { 113 | return $this->fcm_token; 114 | } 115 | } 116 | ``` 117 | 118 | You can also return an array of tokens to send notifications via multicast to different user devices. 119 | 120 | ```php 121 | class User extends Authenticatable 122 | { 123 | use Notifiable; 124 | 125 | ... 126 | 127 | /** 128 | * Specifies the user's FCM tokens 129 | * 130 | * @return string|array 131 | */ 132 | public function routeNotificationForFcm() 133 | { 134 | return $this->getDeviceTokens(); 135 | } 136 | } 137 | ``` 138 | 139 | Once you have that in place, you can simply send a notification to the user by doing the following: 140 | 141 | ```php 142 | $user->notify(new AccountActivated); 143 | ``` 144 | 145 | ### Available Message methods 146 | 147 | View the `FcmMessage` source for the complete list of options. 148 | 149 | ```php 150 | FcmMessage::create() 151 | ->name('name') 152 | ->token('token') 153 | ->topic('topic') 154 | ->condition('condition') 155 | ->data(['a' => 'b']) 156 | ->custom(['notification' => []]); 157 | ``` 158 | 159 | ## Custom clients 160 | 161 | You can change the underlying Firebase Messaging client on the fly if required. Provide an instance of `Kreait\Firebase\Contract\Messaging` to your FCM message and it will be used in place of the default client. 162 | 163 | ```php 164 | public function toFcm(mixed $notifiable): FcmMessage 165 | { 166 | $client = app(\Kreait\Firebase\Contract\Messaging::class); 167 | 168 | return FcmMessage::create()->usingClient($client); 169 | } 170 | ``` 171 | 172 | ## Handling errors 173 | 174 | When a notification fails it will dispatch an `Illuminate\Notifications\Events\NotificationFailed` event. You can listen for this event and choose to handle these notifications as appropriate. For example, you may choose to delete expired notification tokens from your database. 175 | 176 | ```php 177 | data, 'report'); 192 | 193 | $target = $report->target(); 194 | 195 | $event->notifiable->notificationTokens() 196 | ->where('push_token', $target->value()) 197 | ->delete(); 198 | } 199 | } 200 | ``` 201 | 202 | Remember to register your event listeners in the event service provider. 203 | 204 | ```php 205 | /** 206 | * The event listener mappings for the application. 207 | * 208 | * @var array 209 | */ 210 | protected $listen = [ 211 | \Illuminate\Notifications\Events\NotificationFailed::class => [ 212 | \App\Listeners\DeleteExpiredNotificationTokens::class, 213 | ], 214 | ]; 215 | ``` 216 | 217 | ## Changelog 218 | 219 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 220 | 221 | ## Testing 222 | 223 | ``` bash 224 | composer test 225 | ``` 226 | 227 | ## Security 228 | 229 | If you discover any security related issues, please email chrisbjr@gmail.com instead of using the issue tracker. 230 | 231 | ## Contributing 232 | 233 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 234 | 235 | ## Credits 236 | 237 | - [Chris Bautista](https://github.com/chrisbjr) 238 | - [All Contributors](../../contributors) 239 | 240 | ## License 241 | 242 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 243 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "laravel-notification-channels/fcm", 3 | "description": "FCM (Firebase Cloud Messaging) Notifications Driver for Laravel", 4 | "homepage": "https://github.com/laravel-notification-channels/fcm", 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Chris Bautista", 9 | "email": "chris.bautista@coreproc.ph", 10 | "homepage": "https://coreproc.com", 11 | "role": "Developer" 12 | } 13 | ], 14 | "require": { 15 | "php": "^8.2", 16 | "guzzlehttp/guzzle": "^7.0", 17 | "illuminate/notifications": "^11.0|^12.0", 18 | "illuminate/support": "^11.0|^12.0", 19 | "kreait/laravel-firebase": "^6.0" 20 | }, 21 | "require-dev": { 22 | "mockery/mockery": "^1.6.0", 23 | "phpunit/phpunit": "^11.0" 24 | }, 25 | "autoload": { 26 | "psr-4": { 27 | "NotificationChannels\\Fcm\\": "src" 28 | } 29 | }, 30 | "autoload-dev": { 31 | "psr-4": { 32 | "NotificationChannels\\Fcm\\Test\\": "tests" 33 | } 34 | }, 35 | "scripts": { 36 | "test": "vendor/bin/phpunit" 37 | }, 38 | "config": { 39 | "sort-packages": true 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/FcmChannel.php: -------------------------------------------------------------------------------- 1 | routeNotificationFor('fcm', $notification)); 37 | 38 | if (empty($tokens)) { 39 | return null; 40 | } 41 | 42 | $fcmMessage = $notification->toFcm($notifiable); 43 | 44 | return Collection::make($tokens) 45 | ->chunk(self::TOKENS_PER_REQUEST) 46 | ->map(fn ($tokens) => ($fcmMessage->client ?? $this->client)->sendMulticast($fcmMessage, $tokens->all())) 47 | ->map(fn (MulticastSendReport $report) => $this->checkReportForFailures($notifiable, $notification, $report)); 48 | } 49 | 50 | /** 51 | * Handle the report for the notification and dispatch any failed notifications. 52 | */ 53 | protected function checkReportForFailures(mixed $notifiable, Notification $notification, MulticastSendReport $report): MulticastSendReport 54 | { 55 | Collection::make($report->getItems()) 56 | ->filter(fn (SendReport $report) => $report->isFailure()) 57 | ->each(fn (SendReport $report) => $this->dispatchFailedNotification($notifiable, $notification, $report)); 58 | 59 | return $report; 60 | } 61 | 62 | /** 63 | * Dispatch failed event. 64 | */ 65 | protected function dispatchFailedNotification(mixed $notifiable, Notification $notification, SendReport $report): void 66 | { 67 | $this->events->dispatch(new NotificationFailed($notifiable, $notification, self::class, [ 68 | 'report' => $report, 69 | ])); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/FcmMessage.php: -------------------------------------------------------------------------------- 1 | name = $name; 45 | 46 | return $this; 47 | } 48 | 49 | /** 50 | * Set the message token. 51 | */ 52 | public function token(?string $token): self 53 | { 54 | $this->token = $token; 55 | 56 | return $this; 57 | } 58 | 59 | /** 60 | * Set the message topic.s 61 | */ 62 | public function topic(?string $topic): self 63 | { 64 | $this->topic = $topic; 65 | 66 | return $this; 67 | } 68 | 69 | /** 70 | * Set the message condition. 71 | */ 72 | public function condition(?string $condition): self 73 | { 74 | $this->condition = $condition; 75 | 76 | return $this; 77 | } 78 | 79 | /** 80 | * Set the message data, or throw exception if data is not an array of strings. 81 | */ 82 | public function data(?array $data): self 83 | { 84 | if (! empty(array_filter($data, fn ($value) => ! is_string($value)))) { 85 | throw new InvalidArgumentException('Data values must be strings.'); 86 | } 87 | 88 | $this->data = $data; 89 | 90 | return $this; 91 | } 92 | 93 | /** 94 | * Set additional custom message data. 95 | */ 96 | public function custom(?array $custom): self 97 | { 98 | $this->custom = $custom; 99 | 100 | return $this; 101 | } 102 | 103 | /** 104 | * Set the message notification. 105 | */ 106 | public function notification(Notification $notification): self 107 | { 108 | $this->notification = $notification; 109 | 110 | return $this; 111 | } 112 | 113 | /** 114 | * Set the message Firebase Messaging client instance. 115 | */ 116 | public function usingClient(Messaging $client): self 117 | { 118 | $this->client = $client; 119 | 120 | return $this; 121 | } 122 | 123 | public function toArray() 124 | { 125 | return array_filter([ 126 | 'name' => $this->name, 127 | 'data' => $this->data, 128 | 'token' => $this->token, 129 | 'topic' => $this->topic, 130 | 'condition' => $this->condition, 131 | 'notification' => $this->notification?->toArray(), 132 | ...$this->custom, 133 | ]); 134 | } 135 | 136 | /** 137 | * @return mixed 138 | */ 139 | #[\ReturnTypeWillChange] 140 | public function jsonSerialize() 141 | { 142 | return $this->toArray(); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/Resources/FcmResource.php: -------------------------------------------------------------------------------- 1 | title = $title; 24 | 25 | return $this; 26 | } 27 | 28 | /** 29 | * Set the notification body. 30 | */ 31 | public function body(?string $body): self 32 | { 33 | $this->body = $body; 34 | 35 | return $this; 36 | } 37 | 38 | /** 39 | * Set the notification image. 40 | */ 41 | public function image(?string $image): self 42 | { 43 | $this->image = $image; 44 | 45 | return $this; 46 | } 47 | 48 | /** 49 | * Map the resource to an array. 50 | */ 51 | public function toArray(): array 52 | { 53 | return array_filter([ 54 | 'title' => $this->title, 55 | 'body' => $this->body, 56 | 'image' => $this->image, 57 | ]); 58 | } 59 | } 60 | --------------------------------------------------------------------------------