nylo/laravel-fcm-channel

从Laravel发送Firebase云消息(FCM)通知。

v1.0.5 2024-06-12 12:02 UTC

This package is auto-updated.

Last update: 2024-09-12 12:31:25 UTC


README

Laravel FCM Channel

使用Laravel FCM Channel轻松管理FCM通知。

内容

该包旨在使发送FCM消息变得更容易。

还有一个Flutter ,可以帮助您在移动开发中节省时间。

概述

  • 将多个(FCM)设备添加到Laravel模型中
  • 添加新设备到模型的API路由
  • 使用Laravel Notification中的新“fcm_channel”发送FCM通知
  • Flutter移动包,可帮助您加快通知开发

安装

首先,通过composer安装包

composer require nylo/laravel-fcm-channel

该包将自动注册自己。

配置

运行install命令。

php artisan laravelfcm:install

这将添加一个(laravelfcm.php)配置文件

ServiceProvider到您的app.php: App\Providers\FcmAppServiceProvider::class

然后,询问您是否要运行迁移。

以下是将迁移的表

  • fcm_devices

将您的Google服务帐户添加到config/firebase_service_account_json

<?php

return '{
    "type": "service_account",
    "project_id": "123456789-me908",
    "private_key_id": "123456789",
    "private_key": "-----BEGIN PRIVATE KEY-----\123456789\n-----END PRIVATE KEY-----\n",
    "client_email": "firebase-adminsdk-9p9z7@123456789-me908.iam.gserviceaccount.com",
    "client_id": "123456789",
    "auth_uri": "https://#/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-9p9z7%123456789-me908.iam.gserviceaccount.com",
    "universe_domain": "googleapis.com"
  }';

您可以在Firebase项目设置 > 服务帐户 > 管理服务帐户权限 > "操作(三个点)- 管理密钥" > 添加密钥 > 创建新密钥中下载您的Google服务帐户。

然后,将JSON粘贴到上面的示例中的firebase_service_account_json文件中。

注意:最好将密钥值保存在.env文件中。不要将JSON文件提交到您的仓库。

您可以在config/laravelfcm.php中配置此包。

配置您的模型

HasFcmDevices特质添加到您的User模型中。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Nylo\LaravelFCM\Traits\HasFcmDevices; // Use HasFcmDevices trait
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, HasFcmDevices; // Add it to your model
    
    ...
}

此包使用laravel/sanctum作为您模型的默认中间件。

但是,如果您想使用不同的中间件进行认证,您可以在config/laravelfcm.php文件中更新middleware键。

API端点

此包向您的路由器添加API端点,以便您的应用程序可以存储设备。

Postman收集示例

存储设备

默认端点:/api/fcm/device

方法:PUT

授权:“Bearer {{Sanctum Token}}”

添加此头部键:X-DMeta

{
    "uuid": "12992", // required, a uuid which should be from the device.
    "model": "iPhone", // optional
    "version":" 12", // optional
    "display_name": "Tim's iPhone", // optional
    "platform": "IOS" // optional
}

有效负载正文

{
    "is_active": 1, // optional, use this key to define if a device is active or not
    "fcm_token": "kjnsdmnsdc0sdco23" // optional, when you have an FCM token for the device, use this key in the payload
}

这将为用户添加一个新的FCM设备。如果您在有效负载中提供fcm_token,则用户将能够接收推送通知。

用法

发送通知

要使用FCMChannel发送通知,请首先在您的Laravel项目中创建一个通知。

php artisan make:notification ParcelDispatchedNotification

创建您的通知后,将以下数组中的fcm_channel添加。

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [
            'mail',
            'fcm_channel', // add this
        ];
    }

然后,将以下片段添加到您的通知类中。

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toFcm($notifiable)
    {

        return (new FcmMessage)
            ->title('Parcel Dispatched')
            ->body('Your parcel has been dispatched');

        // or like this

        return [
            'title' => config('app.name'), // Title of the notification
            'body' => $title, // Body of the notification
        ];
    }

发送通知

$user->notify(new ParcelDispatchedNotification($order));

这将向用户的设备发送通知。

控制是否应发送FCM通知

在某些场景中,您可能只想根据条件通知用户。

在您的User模型类中添加以下片段。

<?php
...
class User {

    use HasFcmDevices;

    /**
     * Determines if the devices can be notified.
     *
     * @return bool
     */
    public function canSendNotification($notification) : bool
    {
        // $notification - Will return the type of Notification you are trying to send.
        // E.g. $user->notify(new NewsLetterNotification($order));
        // $notification = 'App\Notifications\NewsLetterNotification';
        //
        // The canSendNotification method will be called before dispatching the fcm notification. 
        // If you return True, it will send. If you return False, it will not send.

        if ($notification  == 'App\Notifications\NewsLetterNotification') {
            return ($this->receives_news_letters == true); // example condition
        }
    	return true;
    }
}

默认情况下,canSendNotification方法将返回true

通知对象

以下是可以分配给FcmMessage的属性。

$notification = new FcmMessage();

$notification->title('My App'); // Title of the notification
$notification->body('Hello, World!'); // Body of the notification
$notification->image('https://example.com/image.jpg'); // Image URL
$notification->badge(1); // Badge number
$notification->sound('custom_sound'); // Sound to play (by default it will play the 'default' sound)
$notification->data(['key' => 'value']); // Custom data
$notification->withoutDefaultSound(); // Disable the default sound
$notification->priorityHighest(); // Set the priority to 'high'
$notification->priorityLowest(); // Set the priority to 'low'

关系

当您的模型使用HasFcmDevices特性时,您可以调用以下方法。

<?php

$user = User::first();

$user->fcmDevices;// Returns all the FCM Devices that the user owns

// send notification
$fcmDevice = $user->fcmDevices->first(); 
$message = (new FcmMessage)
                    ->title('My App')
                    ->body('Hello, World!');
$fcmDevice->sendFcmMessage($message);

// or like this

$fcmDevice->sendFcmMessage([
    'title' => 'My App',
    'body' => 'Hello, World!'
]);

Flutter 插件

需要向 Flutter 应用发送通知吗?

请查看该项目的官方仓库这里

变更日志

请查看变更日志以了解最近的变化。

安全性

如果您发现任何安全问题,请发送电子邮件至hello@Nylo.com,而不是使用问题跟踪器。

贡献

有关详细信息,请查看贡献指南

鸣谢

许可

MIT 许可证 (MIT)。请查看我们的许可文件以获取更多信息。