使用Firebase FCM向Android和iOS客户端应用程序发送通知的Laravel API

4

我正在开发一个项目,使用Android和iOS作为前端,Laravel API作为后端。当出现某些事件,如新的优惠或新库存可用时,我希望向所有用户(包括Android / iOS)发送通知。因此,我进行了一些谷歌搜索,并最终得知curl方法似乎已经过时了。那么有没有更好的方式将Firebase FCM集成到我的Laravel项目中呢?如果有,该怎么做?我希望有人能回答这个问题。先行谢过!


https://github.com/brozot/Laravel-FCM - TalESid
你看过它了吗? - TalESid
2个回答

3

Fcm已经在这里为core提供了答案如何从php发送通知到Android? 所以在laravel中,你可以

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

 <?php

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

并在 env 文件中

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
1
@jej 你需要使用分块。例如,如果您的数据库中有 5000 个用户,您可以使用每1000个一组的分块。因此,在循环内部,您可以调用 $this->firebaseNotification($fcmNotification)。 - John Lobo
1
是的..谢谢@John - JEJ
需要更改什么才能发送群组消息?https://firebase.google.com/docs/cloud-messaging/migrate-v1 - JEJ
@JEJ,感谢您的提醒。如果新版本有任何问题,请告诉我,我稍后会检查并更新帖子。 - John Lobo
显示剩余3条评论

2

尝试使用Laravel FCM包

为了方便起见,在这里列出编写步骤...

设置

  1. Installation (terminal)

    composer require brozot/laravel-fcm
    
  2. config/app.php

    • providers

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

      'aliases' => [
          ...
      
          'FCM'      => LaravelFCM\Facades\FCM::class,
      ]
      
  3. Publish the package config file (terminal)

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

使用方法

  1. In your Controller,

    • import libraries

      use LaravelFCM\Message\OptionsBuilder;
      use LaravelFCM\Message\PayloadDataBuilder;
      use LaravelFCM\Message\PayloadNotificationBuilder;
      use FCM;
      
    • sending Downstream Message to device(s)

      $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();
      

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接