├── src ├── Resources │ ├── FcmResource.php │ └── Notification.php ├── FcmTopicChannel.php ├── FcmChannel.php └── FcmMessage.php ├── LICENSE.md ├── composer.json ├── CHANGELOG.md ├── CONTRIBUTING.md └── README.md /src/Resources/FcmResource.php: -------------------------------------------------------------------------------- 1 | 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 | -------------------------------------------------------------------------------- /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.3", 16 | "guzzlehttp/guzzle": "^7.0", 17 | "illuminate/notifications": "^12.0", 18 | "illuminate/support": "^12.0", 19 | "kreait/laravel-firebase": "^6.0" 20 | }, 21 | "require-dev": { 22 | "laravel/pint": "^1.25", 23 | "mockery/mockery": "^1.6.0", 24 | "phpunit/phpunit": "^12.0" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "NotificationChannels\\Fcm\\": "src" 29 | } 30 | }, 31 | "autoload-dev": { 32 | "psr-4": { 33 | "NotificationChannels\\Fcm\\Test\\": "tests" 34 | } 35 | }, 36 | "scripts": { 37 | "test": "vendor/bin/phpunit" 38 | }, 39 | "config": { 40 | "sort-packages": true 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Resources/Notification.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 | -------------------------------------------------------------------------------- /src/FcmTopicChannel.php: -------------------------------------------------------------------------------- 1 | toFcm($notifiable); 28 | 29 | $topic = $notifiable instanceof AnonymousNotifiable 30 | ? $notifiable->routeNotificationFor('fcm-topic') 31 | : $message->topic; 32 | 33 | if (empty($topic)) { 34 | return null; 35 | } 36 | 37 | $message->topic($topic); 38 | 39 | $client = $message->client ?? $this->client; 40 | 41 | try { 42 | return $client->send($message); 43 | } catch (MessagingException $e) { 44 | $this->dispatchFailedNotification($notifiable, $notification, $e); 45 | 46 | return null; 47 | } 48 | } 49 | 50 | /** 51 | * Dispatch failed event. 52 | */ 53 | protected function dispatchFailedNotification(mixed $notifiable, Notification $notification, MessagingException $exception): void 54 | { 55 | $this->events->dispatch(new NotificationFailed($notifiable, $notification, self::class, [ 56 | 'exception' => $exception, 57 | ])); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /src/FcmChannel.php: -------------------------------------------------------------------------------- 1 | routeNotificationFor('fcm', $notification)); 35 | 36 | if (empty($tokens)) { 37 | return null; 38 | } 39 | 40 | $message = $notification->toFcm($notifiable); 41 | 42 | $client = $message->client ?? $this->client; 43 | 44 | return Collection::make($tokens) 45 | ->chunk(self::TOKENS_PER_REQUEST) 46 | ->map(fn ($tokens) => $client->sendMulticast($message, $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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. 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. 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 the message custom options. 95 | */ 96 | public function custom(?array $custom = []): self 97 | { 98 | $this->custom = $custom; 99 | 100 | return $this; 101 | } 102 | 103 | /** 104 | * Set Aandroid specific custom options. 105 | */ 106 | public function android(?array $options = []): self 107 | { 108 | $this->custom([...$this->custom, 'android' => $options]); 109 | 110 | return $this; 111 | } 112 | 113 | /** 114 | * Set APNs-specific custom options. 115 | */ 116 | public function ios(?array $options = []): self 117 | { 118 | $this->custom([...$this->custom, 'apns' => $options]); 119 | 120 | return $this; 121 | } 122 | 123 | /** 124 | * Set the message notification. 125 | */ 126 | public function notification(Notification $notification): self 127 | { 128 | $this->notification = $notification; 129 | 130 | return $this; 131 | } 132 | 133 | /** 134 | * Set the client to use for the message. 135 | */ 136 | public function usingClient(Messaging $client): self 137 | { 138 | $this->client = $client; 139 | 140 | return $this; 141 | } 142 | 143 | /** 144 | * Get the array represenation of the message. 145 | */ 146 | public function toArray(): array 147 | { 148 | return array_filter([ 149 | 'name' => $this->name, 150 | 'data' => $this->data, 151 | 'token' => $this->token, 152 | 'topic' => $this->topic, 153 | 'condition' => $this->condition, 154 | 'notification' => $this->notification?->toArray(), 155 | ...$this->custom, 156 | ]); 157 | } 158 | 159 | /** 160 | * @return mixed 161 | */ 162 | #[\ReturnTypeWillChange] 163 | public function jsonSerialize() 164 | { 165 | return $this->toArray(); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /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 | - [Topic notifications](#topic-notifications) 18 | - [Custom clients](#custom-clients) 19 | - [Handling errors](#handling-errors) 20 | - [Changelog](#changelog) 21 | - [Testing](#testing) 22 | - [Security](#security) 23 | - [Contributing](#contributing) 24 | - [Credits](#credits) 25 | - [License](#license) 26 | 27 | 28 | ## Installation 29 | 30 | Install this package with Composer: 31 | 32 | ```bash 33 | composer require laravel-notification-channels/fcm 34 | ``` 35 | 36 | ### Setting up the FCM service 37 | 38 | This package now uses the [laravel-firebase](https://github.com/kreait/laravel-firebase) library to authenticate and 39 | make the API calls to Firebase. Follow the [configuration](https://github.com/kreait/laravel-firebase#configuration) 40 | steps specified in their readme before using this. 41 | 42 | After following their configuration steps, make sure that you've specified your `FIREBASE_CREDENTIALS` in your .env 43 | file. 44 | 45 | ## Usage 46 | 47 | After setting up your Firebase credentials, you can now send notifications via FCM by a Notification class and sending 48 | it via the `FcmChannel::class`. Here is an example: 49 | 50 | ```php 51 | use Illuminate\Notifications\Notification; 52 | use NotificationChannels\Fcm\FcmChannel; 53 | use NotificationChannels\Fcm\FcmMessage; 54 | use NotificationChannels\Fcm\Resources\Notification as FcmNotification; 55 | 56 | class AccountActivated extends Notification 57 | { 58 | public function via($notifiable) 59 | { 60 | return [FcmChannel::class]; 61 | } 62 | 63 | public function toFcm($notifiable): FcmMessage 64 | { 65 | return (new FcmMessage(notification: new FcmNotification( 66 | title: 'Account Activated', 67 | body: 'Your account has been activated.', 68 | image: 'http://example.com/url-to-image-here.png' 69 | ))) 70 | ->data(['data1' => 'value', 'data2' => 'value2']) 71 | ->custom([ 72 | 'android' => [ 73 | 'notification' => [ 74 | 'color' => '#0A0A0A', 75 | 'sound' => 'default', 76 | ], 77 | 'fcm_options' => [ 78 | 'analytics_label' => 'analytics', 79 | ], 80 | ], 81 | 'apns' => [ 82 | 'payload' => [ 83 | 'aps' => [ 84 | 'sound' => 'default' 85 | ], 86 | ], 87 | 'fcm_options' => [ 88 | 'analytics_label' => 'analytics', 89 | ], 90 | ], 91 | ]); 92 | } 93 | } 94 | ``` 95 | 96 | You will have to set a `routeNotificationForFcm()` method in your notifiable model. 97 | This method should return the user's FCM token(s) from storage. 98 | For example: 99 | 100 | ```php 101 | class User extends Authenticatable 102 | { 103 | use Notifiable; 104 | 105 | ... 106 | 107 | /** 108 | * Specifies the user's FCM token 109 | * 110 | * @return string|array 111 | */ 112 | public function routeNotificationForFcm() 113 | { 114 | return $this->fcm_token; 115 | } 116 | } 117 | ``` 118 | 119 | You can also return an array of tokens to send notifications via multicast to different user devices. 120 | 121 | ```php 122 | class User extends Authenticatable 123 | { 124 | use Notifiable; 125 | 126 | ... 127 | 128 | /** 129 | * Specifies the user's FCM tokens 130 | * 131 | * @return string|array 132 | */ 133 | public function routeNotificationForFcm() 134 | { 135 | return $this->getDeviceTokens(); 136 | } 137 | } 138 | ``` 139 | 140 | Once you have that in place, you can simply send a notification to the user by doing the following: 141 | 142 | ```php 143 | $user->notify(new AccountActivated); 144 | ``` 145 | 146 | ### Available Message methods 147 | 148 | View the `FcmMessage` source for the complete list of options. 149 | 150 | ```php 151 | FcmMessage::create() 152 | ->name('name') 153 | ->token('token') 154 | ->topic('topic') 155 | ->condition('condition') 156 | ->data(['a' => 'b']) 157 | ->custom(['notification' => []]); 158 | ``` 159 | 160 | ## Topic notifications 161 | 162 | You can also send FCM notifications to topics with the `FcmTopicChannel`. Use an on-demand notification to to route the notification to the topic, or you can set the topic on the message itself in the `toFcm` method. 163 | 164 | ```php 165 | use NotificationChannels\Fcm\FcmTopicChannel; 166 | 167 | Notification::route(FcmTopicChannel::class, 'news') 168 | ->notify(new BlogCreated($blog)); 169 | ``` 170 | 171 | ## Custom clients 172 | 173 | 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. 174 | 175 | ```php 176 | public function toFcm(mixed $notifiable): FcmMessage 177 | { 178 | $client = app(\Kreait\Firebase\Contract\Messaging::class); 179 | 180 | return FcmMessage::create()->usingClient($client); 181 | } 182 | ``` 183 | 184 | ## Handling errors 185 | 186 | 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. 187 | 188 | ```php 189 | channel == FcmChannel::class) { 204 | 205 | $report = Arr::get($event->data, 'report'); 206 | 207 | $target = $report->target(); 208 | 209 | $event->notifiable->notificationTokens() 210 | ->where('push_token', $target->value()) 211 | ->delete(); 212 | } 213 | } 214 | } 215 | ``` 216 | 217 | Remember to register your event listeners in the event service provider. 218 | 219 | ```php 220 | /** 221 | * The event listener mappings for the application. 222 | * 223 | * @var array 224 | */ 225 | protected $listen = [ 226 | \Illuminate\Notifications\Events\NotificationFailed::class => [ 227 | \App\Listeners\DeleteExpiredNotificationTokens::class, 228 | ], 229 | ]; 230 | ``` 231 | 232 | ## Changelog 233 | 234 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 235 | 236 | ## Testing 237 | 238 | ``` bash 239 | composer test 240 | ``` 241 | 242 | ## Security 243 | 244 | If you discover any security related issues, please email chrisbjr@gmail.com instead of using the issue tracker. 245 | 246 | ## Contributing 247 | 248 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 249 | 250 | ## Credits 251 | 252 | - [Chris Bautista](https://github.com/chrisbjr) 253 | - [All Contributors](../../contributors) 254 | 255 | ## License 256 | 257 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 258 | --------------------------------------------------------------------------------