aristosya/larafirebase

Laravel Firebase Cloud Messaging。包含 SendAll() 方法

dev-main 2024-09-12 15:52 UTC

This package is auto-updated.

Last update: 2024-09-12 15:52:28 UTC


README

这是 https://github.com/gg-innovative/larafirebase 的修改版本。仅限个人使用。我并不声称任何权利

简介

Larafirebase 是一个提供通过 Firebase 在 Laravel 中发送推送通知的包。

Firebase Cloud Messaging (FCM) 是一个跨平台的消息解决方案,让您免费可靠地传递消息。

对于即时消息等用例,消息可以传输最多 4KB 的有效负载到客户端应用程序。

安装

按照以下步骤安装此包。

通过 Composer 安装

composer require aristosya/larafirebase:dev-main

复制配置

运行以下命令以发布 larafirebase.php 配置文件

php artisan vendor:publish --provider="GGInnovative\Larafirebase\Providers\LarafirebaseServiceProvider"

根据需要配置 larafirebase.php

打开您刚刚发布的 larafirebase.php 配置文件,并根据需要设置以下值

  • project_id:替换为您的实际 Firebase 项目 ID。 (获取项目 ID,请访问 https://console.firebase.google.com/ -> 选择您的项目 -> 在“项目设置”(在侧边栏中点击齿轮) -> 在“常规”选项卡中复制您的“项目 ID”)。顺便说一句,它必须是一个字符串。
  • firebase_credentials:这指的是 Firebase 项目的 JSON 凭据文件。确保它指向您的项目中正确的位置。此 JSON 文件包含 Firebase 项目的身份验证信息,允许您的 Laravel 应用程序与 Firebase 服务交互。您可以在 Firebase 控制台中生成此 JSON 文件。一旦您有了它,请指定其路径在此配置中。(获取项目 JSON 凭据文件,请访问 https://console.firebase.google.com/ -> 选择您的项目 -> 在“项目设置”(在侧边栏中点击齿轮) -> 在“服务帐户”选项卡中选择 Firebase Admin SDK -> 生成新私钥 -> 下载文件并将其放入您的应用程序中)。顺便说一句,对于 'firebase_credentials' => public_path('firebase_credentials.json'),文件必须位于 {project-folder}/public/ 中,并且文件名必须是:"firebase_credentials.json"。

配置前端应用程序以使用 sendNotificationAll() 方法

如果您将使用发送通知给所有用户,您应该在您的客户端应用程序中将所有 devise tokens 初始化到“all”主题中(不适用于 Laravel)。例如 Flutter

import 'dart:convert';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';

import '../routes/app_routes.dart';


void onDidReceiveNotificationResponse(
    NotificationResponse notificationResponse) async {
  final payload =
      RemoteMessage.fromMap(jsonDecode(notificationResponse.payload ?? ""));
  if (notificationResponse.payload != null) {
    debugPrint('notification payload: $payload');
  }
  await Get.toNamed(Routes.testNotification, arguments: {"message": payload});
}

class FirebaseApi {
  final _firebaseMessaging = FirebaseMessaging.instance;

  final _androidChannel = const AndroidNotificationChannel(
      'high_importance_channel', 'High importance notifications',
      description: 'This channel is used for ipmortant notications',
      importance: Importance.defaultImportance);

  final _localNotifications = FlutterLocalNotificationsPlugin();

  Future<void> initNotifications() async {
    await _firebaseMessaging.requestPermission();
    final fcmToken = await _firebaseMessaging.getToken();

// NEXT LINE MUST BE ADDED 
    _firebaseMessaging.subscribeToTopic('all');  
    debugPrint('FireBase Cloud Messaging Token == $fcmToken');
    initPushNotifications();
    initLocalNotifications();
  }

  // function to handle received message
  void handleMessage(RemoteMessage? message) async {
    if (message == null) {
      return;
    }
    await Get.toNamed(Routes.testNotification, arguments: {"message": message});
  }

  Future initLocalNotifications() async {
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    final InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
    );
    await _localNotifications.initialize(initializationSettings,
        onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);
    final _platform = _localNotifications.resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>();
    await _platform?.createNotificationChannel(_androidChannel);
  }

  //function to init bg settings
  Future initPushNotifications() async {
    // handle when the app was terminated and it opeened now
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
            alert: true, badge: true, sound: true);
    await FirebaseMessaging.instance.getInitialMessage().then(handleMessage);
    // attach an event listener
    FirebaseMessaging.onMessageOpenedApp.listen(handleMessage);
    FirebaseMessaging.onMessage.listen((message) {
      final notification = message.notification;
      if (notification == null) return;
      _localNotifications.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
              android: AndroidNotificationDetails(
                  _androidChannel.id, _androidChannel.name,
                  channelDescription: _androidChannel.description,
                  icon: '@mipmap/ic_launcher')),
          payload: jsonEncode(message.toMap()));
    });
  }
}

如果我没有弄错,对于 JAVA

    FirebaseMessaging.getInstance().subscribeToTopic("TopicName");

配置前端应用程序以使用 sendNotificationUser()/sendNotificationUsers() 方法

如果您将使用通过其 id 发送通知给特定用户/用户,您应在登录或注册后在您的客户端应用程序中将所有 devise tokens 初始化到“user_ID”主题中,在注销后也从该主题中删除 deviceId!(不适用于 Laravel)。

例如 Flutter

void login(){
    final _firebaseMessaging = FirebaseMessaging.instance;
    _firebaseMessaging.subscribeToTopic('user_$id');
}
void logout(){
    final _firebaseMessaging = FirebaseMessaging.instance;
    _firebaseMessaging.unsubscribeFromTopic('user_$id');
}
    login => FirebaseMessaging.getInstance().subscribeToTopic("user_" + id);
    logout=> FirebaseMessaging.getInstance().unsubscribeFromTopic("user_" + id);

用法

按照以下步骤查找如何使用此包。

控制器/服务 或任何类中的示例用法

use GGInnovative\Larafirebase\Facades\Larafirebase;

class MyController
{
public function sendNotification()
    {
        return Larafirebase::withTitle('Test Title')
            ->withBody('Test body')
            ->withImage('https://firebase.google.com/images/social.png')
            ->withAdditionalData([
                'name' => 'wrench',
                'mass' => '1.3kg',
                'count' => '3'
            ])
            ->withToken('TOKEN_HERE') // You can use also withTopic
            ->sendNotification();
    }


public function sendNotificationAll()
            {
                return Larafirebase::withTitle('Test Title')
                    ->withBody('Test body')
                    ->withImage('https://firebase.google.com/images/social.png')
                    ->withAdditionalData([
                        'name' => 'wrench',
                        'mass' => '1.3kg',
                        'count' => '3'
                    ])
                    ->sendNotificationAll();
                
        }



public function sendNotificationUser()
    {
        return Larafirebase::withTitle('Test Title')
            ->withBody('Test body')
            ->withImage('https://firebase.google.com/images/social.png')
            ->withAdditionalData([
                'name' => 'Some Name',
                'product_id' => '123',
                'user_id' => '3'
            ])
//            id of One user
            ->sendNotificationUser(1);
    }


public function sendNotificationUsers()
    {
        return Larafirebase::withTitle('Test Title')
            ->withBody('Test body')
            ->withImage('https://firebase.google.com/images/social.png')
            ->withAdditionalData([
                'name' => 'Some Name',
                'product_id' => '123',
                'user_id' => '3'
            ])
//            array of users ids
            ->sendNotificationUsers([0,2,1,4]);
    }