我正在开发一个项目,使用Android和iOS作为前端,Laravel API作为后端。当出现某些事件,如新的优惠或新库存可用时,我希望向所有用户(包括Android / iOS)发送通知。因此,我进行了一些谷歌搜索,并最终得知curl方法似乎已经过时了。那么有没有更好的方式将Firebase FCM集成到我的Laravel项目中呢?如果有,该怎么做?我希望有人能回答这个问题。先行谢过!
我正在开发一个项目,使用Android和iOS作为前端,Laravel API作为后端。当出现某些事件,如新的优惠或新库存可用时,我希望向所有用户(包括Android / iOS)发送通知。因此,我进行了一些谷歌搜索,并最终得知curl方法似乎已经过时了。那么有没有更好的方式将Firebase FCM集成到我的Laravel项目中呢?如果有,该怎么做?我希望有人能回答这个问题。先行谢过!
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"
}
}
}
}
}
尝试使用Laravel FCM包
为了方便起见,在这里列出编写步骤...
设置
Installation (terminal)
composer require brozot/laravel-fcm
config/app.php
providers
'providers' => [
// ...
LaravelFCM\FCMServiceProvider::class,
]
aliases
'aliases' => [
...
'FCM' => LaravelFCM\Facades\FCM::class,
]
Publish the package config file (terminal)
php artisan vendor:publish --provider="LaravelFCM\FCMServiceProvider"
使用方法
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();