定制 laravel-notification-channels/fcm 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

laravel-notification-channels/fcm

Composer 安装命令:

composer require laravel-notification-channels/fcm

包简介

FCM (Firebase Cloud Messaging) Notifications Driver for Laravel

README 文档

README

Latest Version on Packagist Software License StyleCI Quality Score Total Downloads

This package makes it easy to send notifications using Firebase Cloud Messaging (FCM) with Laravel.

Contents

Installation

Install this package with Composer:

composer require laravel-notification-channels/fcm

Setting up the FCM service

This package now uses the laravel-firebase library to authenticate and make the API calls to Firebase. Follow the configuration steps specified in their readme before using this.

After following their configuration steps, make sure that you've specified your FIREBASE_CREDENTIALS in your .env file.

Usage

After setting up your Firebase credentials, you can now send notifications via FCM by a Notification class and sending it via the FcmChannel::class. Here is an example:

use Illuminate\Notifications\Notification;
use NotificationChannels\Fcm\FcmChannel;
use NotificationChannels\Fcm\FcmMessage;
use NotificationChannels\Fcm\Resources\Notification as FcmNotification;

class AccountActivated extends Notification
{
    public function via($notifiable)
    {
        return [FcmChannel::class];
    }

    public function toFcm($notifiable): FcmMessage
    {
        return (new FcmMessage(notification: new FcmNotification(
                title: 'Account Activated',
                body: 'Your account has been activated.',
                image: 'http://example.com/url-to-image-here.png'
            )))
            ->data(['data1' => 'value', 'data2' => 'value2'])
            ->custom([
                'android' => [
                    'notification' => [
                        'color' => '#0A0A0A',
                        'sound' => 'default',
                    ],
                    'fcm_options' => [
                        'analytics_label' => 'analytics',
                    ],
                ],
                'apns' => [
                    'payload' => [
                        'aps' => [
                            'sound' => 'default'
                        ],
                    ],
                    'fcm_options' => [
                        'analytics_label' => 'analytics',
                    ],
                ],
            ]);
    }
}

You will have to set a routeNotificationForFcm() method in your notifiable model. This method should return the user's FCM token(s) from storage. For example:

class User extends Authenticatable
{
    use Notifiable;

    ...

    /**
     * Specifies the user's FCM token
     *
     * @return string|array
     */
    public function routeNotificationForFcm()
    {
        return $this->fcm_token;
    }
}

You can also return an array of tokens to send notifications via multicast to different user devices.

class User extends Authenticatable
{
    use Notifiable;

    ...

    /**
     * Specifies the user's FCM tokens
     *
     * @return string|array
     */
    public function routeNotificationForFcm()
    {
        return $this->getDeviceTokens();
    }
}

Once you have that in place, you can simply send a notification to the user by doing the following:

$user->notify(new AccountActivated);

Available Message methods

View the FcmMessage source for the complete list of options.

FcmMessage::create()
    ->name('name')
    ->token('token')
    ->topic('topic')
    ->condition('condition')
    ->data(['a' => 'b'])
    ->custom(['notification' => []]);

Topic notifications

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.

use NotificationChannels\Fcm\FcmTopicChannel;

Notification::route(FcmTopicChannel::class, 'news')
    ->notify(new BlogCreated($blog));

Custom clients

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.

public function toFcm(mixed $notifiable): FcmMessage
{
    $client = app(\Kreait\Firebase\Contract\Messaging::class);

    return FcmMessage::create()->usingClient($client);
}

Handling errors

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.

<?php

namespace App\Listeners;

use Illuminate\Notifications\Events\NotificationFailed;
use Illuminate\Support\Arr;

class DeleteExpiredNotificationTokens
{
    /**
     * Handle the event.
     */
    public function handle(NotificationFailed $event): void
    {
        if ($event->channel == FcmChannel::class) {

            $report = Arr::get($event->data, 'report');

            $target = $report->target();

            $event->notifiable->notificationTokens()
                ->where('push_token', $target->value())
                ->delete();
        }
    }
}

Remember to register your event listeners in the event service provider.

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    \Illuminate\Notifications\Events\NotificationFailed::class => [
        \App\Listeners\DeleteExpiredNotificationTokens::class,
    ],
];

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Security

If you discover any security related issues, please email chrisbjr@gmail.com instead of using the issue tracker.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-notification-channels/fcm 适用场景与选型建议

laravel-notification-channels/fcm 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 7.84M 次下载、GitHub Stars 达 597, 最近一次更新时间为 2020 年 01 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 laravel-notification-channels/fcm 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 laravel-notification-channels/fcm 我们能提供哪些服务?
定制开发 / 二次开发

基于 laravel-notification-channels/fcm 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 7.84M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 598
  • 点击次数: 32
  • 依赖项目数: 23
  • 推荐数: 1

GitHub 信息

  • Stars: 597
  • Watchers: 11
  • Forks: 136
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-01-25