【问题标题】:Laravel API -Send Notifications to android and iOS client apps with Firebase FCMLaravel API - 使用 Firebase FCM 向 android 和 iOS 客户端应用程序发送通知
【发布时间】:2022-01-01 14:03:36
【问题描述】:

我正在开发一个项目,它使用 android 和 iOS 作为前端,后端作为 Laravel API。 因此,我想在某些事件发生时向所有用户(包括 android/iOS)发送通知,例如 New Offer Created/New Stock available.. 所以要做到这一点,已经通过了一些谷歌搜索,最后知道 curl 方法似乎是已弃用..所以有没有更好的方法将firebase FCM集成到我的Laravel项目中..如果是这样怎么办? 我希望有人能回答这个.. 提前致谢

【问题讨论】:

标签: laravel firebase


【解决方案1】:

核心的 Fcm 已在此处回答 How to send Notification to Android from php? 所以在 laravel 你可以

config 文件夹中创建一个config file 并将其命名为firebase.php

 <?php

        return [
            'fcm_url'=>env('FCM_URL'),
            'fcm_api_key'=>env('FCM_API_KEY'),
        ];

在环境文件中

FCM_URL=https://fcm.googleapis.com/fcm/send
FCM_API_KEY=

您可以在代码中创建 Trait 类

<?php


namespace App\Traits;

use Illuminate\Support\Facades\Http;

trait Firebase
{

    public  function firebaseNotification($fcmNotification){

        $fcmUrl =config('firebase.fcm_url');

        $apiKey=config('firebase.fcm_api_key');

        $http=Http::withHeaders([
            'Authorization:key'=>$apiKey,
            'Content-Type'=>'application/json'
        ])  ->post($fcmUrl,$fcmNotification);

        return  $http->json();
    }
}

然后你可以在任何你想调用的类中包含这个特征

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Traits\Firebase;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use Firebase,AuthenticatesUsers;

    
    public function sendNotification(){
        $token="";
        $notification = [
            'title' =>'title',
            'body' => 'body of message.',
            'icon' =>'myIcon',
            'sound' => 'mySound'
        ];
        $extraNotificationData = ["message" => $notification,"moredata" =>'dd'];

        $fcmNotification = [
            //'registration_ids' => $tokenList, //multple token array
            'to'        => $token, //single token
            'notification' => $notification,
            'data' => $extraNotificationData
        ];
        
        return $this->firebaseNotification($fcmNotification); 

    }
}

另外我建议创建基于更好的代码优化的事件

另请阅读

https://firebase.google.com/docs/cloud-messaging/http-server-ref

registration_ids多个用户

此参数指定多播消息的接收者,一个 消息发送到多个注册令牌。

该值应该是要发送到的注册令牌数组 多播消息。该数组必须至少包含 1 且最多包含 1000 个注册令牌。要将消息发送到单个设备,请使用 to 参数。

组播消息只允许使用 HTTP JSON 格式。

@JEJ 评论中提到的新版本

https://firebase.google.com/docs/cloud-messaging/migrate-v1#python_1

原来如此

  $http=Http::withHeaders([
                'Authorization'=>'Bearer '.$apiKey,
                'Content-Type'=>'application/json; UTF-8'
            ])  ->post($fcmUrl,$fcmNotification);
    
            return  $http->json();

$fcmNotification 的简单通知消息

{
  "message": {
    "topic": "news",
    "notification": {
      "title": "Breaking News",
      "body": "New news story available."
    },
    "data": {
      "story_id": "story_12345"
    }
  }
}

针对多个平台

{
  "message": {
    "topic": "news",
    "notification": {
      "title": "Breaking News",
      "body": "New news story available."
    },
    "data": {
      "story_id": "story_12345"
    },
    "android": {
      "notification": {
        "click_action": "TOP_STORY_ACTIVITY"
      }
    },
    "apns": {
      "payload": {
        "aps": {
          "category" : "NEW_MESSAGE_CATEGORY"
        }
      }
    }
  }
}

【讨论】:

  • 注册令牌超过1000个怎么办?
  • @jej 你必须使用块。例如,如果你在 db 中有 5000 个用户,你可以使用 1000 个块。所以在循环内你可以调用 $this->firebaseNotification($fcmNotification)跨度>
  • 是的..谢谢@John
  • firebase.google.com/docs/cloud-messaging/migrate-v1 需要更改东西才能发送群消息?
  • @JEJ。我最近没有使用 fcm 新的变化。如果我以后有时间我会检查一下
【解决方案2】:

试试Laravel FCM package

为方便起见,请在此处编写步骤...

设置

  1. 安装(终端)

    composer require brozot/laravel-fcm
    
  2. 配置/app.php

    • 供应商

      'providers' => [
          // ...
      
          LaravelFCM\FCMServiceProvider::class,
      ]
      
    • 别名

      'aliases' => [
          ...
      
          'FCM'      => LaravelFCM\Facades\FCM::class,
      ]
      
  3. 发布包配置文件(终端)

    php artisan vendor:publish --provider="LaravelFCM\FCMServiceProvider"
    

用法

  1. 在您的控制器中,

    • 导入库

      use LaravelFCM\Message\OptionsBuilder;
      use LaravelFCM\Message\PayloadDataBuilder;
      use LaravelFCM\Message\PayloadNotificationBuilder;
      use FCM;
      
    • 向设备发送下游消息

      $optionBuilder = new OptionsBuilder();
      $optionBuilder->setTimeToLive(60*20);
      
      $notificationBuilder = new PayloadNotificationBuilder('my title');
      $notificationBuilder->setBody('Hello world')->setSound('default');
      
      $dataBuilder = new PayloadDataBuilder();
      $dataBuilder->addData(['a_data' => 'my_data']);
      
      $option = $optionBuilder->build();
      $notification = $notificationBuilder->build();
      $data = $dataBuilder->build();
      
      $token = "a_registration_from_your_database" /* OR */ [ /* Array of tokens */ ];
      
      $downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
      
      $downstreamResponse->numberSuccess();
      $downstreamResponse->numberFailure();
      $downstreamResponse->numberModification();
      
      // return Array - you must remove all this tokens in your database
      $downstreamResponse->tokensToDelete();
      
      // return Array (key : oldToken, value : new token - you must change the token in your database)
      $downstreamResponse->tokensToModify();
      
      // return Array - you should try to resend the message to the tokens in the array
      $downstreamResponse->tokensToRetry();
      
      // return Array (key:token, value:error) - in production you should remove from your database the tokens
      $downstreamResponse->tokensWithError();
      

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 2020-12-04
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    相关资源
    最近更新 更多