核心的 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"
}
}
}
}
}