williamcruzme/laravel-fcm

一个强大的 Laravel 包,用于发送推送通知

v1.0.11 2021-07-11 23:50 UTC

This package is auto-updated.

Last update: 2024-09-06 23:01:49 UTC


README

Laravel GitHub


laravel-fcm 是一个强大的 Laravel 包,用于向一个或多个用户的所有设备发送 推送通知。作为基于通道的包,你只需要在 Laravel 的 通知 中指定 channel

功能

  • 易于集成
  • 与任何版本的 Laravel 兼容
  • 同时向一个或多个用户的全部设备发送通知
  • 批量发送数百万条通知
  • 完全可定制和适应
  • 队列支持

📄 内容

💿 安装

composer require williamcruzme/laravel-fcm

1. 配置环境

获取服务账户并粘贴到你的 .env 文件
(gear-next-to-project-name) > 项目设置 > 云消息

FIREBASE_CREDENTIALS=/path/to/service-account.json

2. 添加特质

在你的 App\Models\User 模型中添加 HasDevices 特质

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Williamcruzme\Fcm\HasDevices;

class User extends Authenticatable
{
    use Notifiable, HasDevices;
}

记住,你不仅限于在 App\Models\User 模型中包含特质。

3. 运行迁移

php artisan migrate

(可选) 有时你可能需要自定义迁移。使用 vendor:publish 命令可以导出迁移

php artisan vendor:publish --tag=migrations

4. 添加路由

在你的 routes/api.php 中添加路由,使用 Device 门面,这是用于管理设备

Route::middleware('auth')->group(function () {
    Device::routes();
});

⚡ 创建通知

1. 创建通知

php artisan make:notification InvoicePaid

2. 添加投递通道

每个通知类都有一个 via 方法,用于确定通知将在哪些通道上投递。将 fcm 添加为投递通道

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

3. 格式化通知

notification 方法支持 Firebase 负载

/**
 * Get the Firebase Message representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Williamcruzme\Fcm\Messages\FcmMessage
 */
public function toFcm($notifiable)
{
    return (new FcmMessage)
                ->notification([
                    'title' => 'Happy Code!',
                    'body' => 'This is a test',
                ]);
}

4. 发送通知

FcmMessage 自动获取通知实体的所有设备;你只需要发送通知。通知可以通过两种方式发送:使用 Notifiable 特质的 notify 方法或使用 Notification 门面。首先,让我们来看看如何使用特质

使用 Notifiable 特质

此特质由默认的 App\User 模型使用,并包含一个可以用来发送通知的方法:notifynotify 方法期望接收一个通知实例

use App\Notifications\InvoicePaid;

$user->notify(new InvoicePaid($invoice));

记住,你可以在任何模型上使用 Illuminate\Notifications\Notifiable 特质。你不仅限于仅在 App\User 模型上包含它。

使用 Notification 门面

或者,你也可以通过 Notification 门面发送通知。这主要在你需要向多个通知实体发送通知时很有用,例如用户集合。要使用门面发送通知,将所有通知实体和通知实例传递给 send 方法

use App\Notifications\InvoicePaid;
use Illuminate\Support\Facades\Notification;

Notification::send($users, new InvoicePaid($invoice));

🌐 路由

这些路由是自动生成的,一旦你在任何地方添加了 Device::routes();

添加设备

请求体参数

{
    "token": "fxssWy2Lgtk:APA91bFXy79AmofgTnBm5CfBpyeEFJsSHq0Xcdk..."
}

移除设备

请求体参数

{
    "token": "fxssWy2Lgtk:APA91bFXy79AmofgTnBm5CfBpyeEFJsSHq0Xcdk..."
}

🎨 自定义通知

发送数据

使用 data 方法,你可以指定通知负载的定制键值对

/**
 * Get the Firebase Message representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Williamcruzme\Fcm\Messages\FcmMessage
 */
public function toFcm($notifiable)
{
    return (new FcmMessage)
                ->notification([
                    'title' => 'Happy Code!',
                    'body' => 'This is a test',
                ])
                ->data([
                    'type' => 'banner',
                    'link' => 'https://github.com/',
                ]);
}

添加条件

使用 condition 方法,你可以指定一个布尔表达式来发送通知

/**
 * Get the Firebase Message representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Williamcruzme\Fcm\Messages\FcmMessage
 */
public function toFcm($notifiable)
{
    return (new FcmMessage)
                ->condition("'stock-GOOG' in topics || 'industry-tech' in topics")
                ->notification([
                    'title' => 'Happy Code!',
                    'body' => 'This is a test',
                ]);
}

设置优先级

使用 priority 方法,你可以指定通知的优先级。默认是 normal

/**
 * Get the Firebase Message representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Williamcruzme\Fcm\Messages\FcmMessage
 */
public function toFcm($notifiable)
{
    return (new FcmMessage)
                ->priority('high')
                ->notification([
                    'title' => 'Happy Code!',
                    'body' => 'This is a test',
                ]);
}

自定义有效负载

使用 payload 方法,您可以指定自定义的有效负载到通知

/**
 * Get the Firebase Message representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Williamcruzme\Fcm\Messages\FcmMessage
 */
public function toFcm($notifiable)
{
    return (new FcmMessage)
                ->notification([
                    'title' => 'Happy Code!',
                    'body' => 'This is a test',
                ])
                ->payload([
                    'android_channel_id' => '500'
                ]);
}

🎨 自定义控制器

首先,创建自己的 DeviceController 控制器并添加 ManageDevices 特性。

其次,修改 Device 门面路由的命名空间为

Device::routes('App\Http\Controllers');

自定义请求验证

DeviceController 中的 createRulesdeleteRulesvalidationErrorMessages 方法允许您覆盖默认请求验证

<?php

namespace App\Http\Controllers;

use Williamcruzme\Fcm\Traits\ManageDevices;

class DeviceController extends Controller
{
    use ManageDevices;
    
    /**
     * Get the validation rules that apply to the create a device.
     *
     * @return array
     */
    protected function createRules()
    {
        return [
            'token' => ['required', 'string'],
        ];
    }

    /**
     * Get the validation rules that apply to the delete a device.
     *
     * @return array
     */
    protected function deleteRules()
    {
        return [
            'token' => ['required', 'string', 'exists:devices,token'],
        ];
    }

    /**
     * Get the device management validation error messages.
     *
     * @return array
     */
    protected function validationErrorMessages()
    {
        return [];
    }
}

自定义响应

DeviceController 中的 sendResponsesendDestroyResponse 方法允许您覆盖默认响应

<?php

namespace App\Http\Controllers;

use Williamcruzme\Fcm\Traits\ManageDevices;

class DeviceController extends Controller
{
    use ManageDevices;
    
    /**
     * Get the response for a successful storing device.
     *
     * @param  Williamcruzme\Fcm\Device  $model
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendResponse($model)
    {
        return response()->json($model);
    }

    /**
     * Get the response for a successful deleting device.
     *
     * @param  Williamcruzme\Fcm\Device  $model
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendDestroyResponse($model)
    {
        return response()->json('', 204);
    }
}

自定义守卫

DeviceController 中的 guard 方法允许您覆盖默认守卫

<?php

namespace App\Http\Controllers;

use Williamcruzme\Fcm\Traits\ManageDevices;

class DeviceController extends Controller
{
    use ManageDevices;
    
    /**
     * Get the guard to be used during device management.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return auth('admin')->guard();
    }
}

🚸 贡献

欢迎您为此项目做出贡献,但在您这么做之前,请确保您已经阅读了贡献指南

🔒 许可证

MIT