FCM (Firebase Cloud Messaging) 通知驱动程序,用于Laravel

4.3.0 2024-03-13 02:21 UTC

README

Latest Version on Packagist Software License StyleCI Quality Score Total Downloads

此包使得使用Firebase Cloud Messaging (FCM)通过Laravel发送通知变得简单。

内容

安装

使用Composer安装此包

composer require laravel-notification-channels/fcm

设置FCM服务

此包现在使用laravel-firebase库进行身份验证并调用Firebase的API。在使用此包之前,请按照他们readme中指定的配置步骤进行。

按照他们的配置步骤之后,请确保你在.env文件中指定了你的

使用方法

设置好Firebase凭证后,你现在可以通过Notification类和通过FcmChannel::class发送来发送通知。以下是一个示例

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',
                    ],
                ],
            ]);
    }
}

你需要在你的可通知模型中设置一个routeNotificationForFcm()方法。该方法应从存储中返回用户的FCM令牌。例如

class User extends Authenticatable
{
    use Notifiable;

    ...

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

你也可以返回一个令牌数组,以便通过多播向不同用户的设备发送通知。

class User extends Authenticatable
{
    use Notifiable;

    ...

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

一旦设置好,你可以通过以下方式向用户发送通知

$user->notify(new AccountActivated);

可用的消息方法

查看FcmMessage源代码以获取完整的选项列表。

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

自定义客户端

如果需要,你可以实时更改底层Firebase Messaging客户端。提供一个Kreait\Firebase\Contract\Messaging实例到你的FCM消息中,它将替换默认客户端。

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

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

处理错误

当通知失败时,将触发一个Illuminate\Notifications\Events\NotificationFailed事件。你可以监听此事件并根据需要处理这些通知。例如,你可以选择从数据库中删除过期的通知令牌。

<?php

namespace App\Listeners;

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

class DeleteExpiredNotificationTokens
{
    /**
     * Handle the event.
     */
    public function handle(NotificationFailed $event): void
    {
        $report = Arr::get($event->data, 'report');

        $target = $report->target();

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

请记住在事件服务提供程序中注册你的事件监听器。

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

变更日志

有关最近更改的更多信息,请参阅变更日志

测试

composer test

安全性

如果您发现任何与安全相关的问题,请通过chrisbjr@gmail.com发送电子邮件,而不是使用问题跟踪器。

贡献

有关详细信息,请参阅贡献指南

鸣谢

许可

MIT许可证(MIT)。有关更多信息,请参阅许可证文件