sv1ft/laravel-fcm

发送推送通知的强大Laravel扩展包

1.0.7 2023-11-17 11:33 UTC

This package is auto-updated.

Last update: 2024-09-17 13:11:53 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