PHP Firebase HTTP v1 API 新版推送

PHP Firebase HTTP v1 API  新版推送

//最近一个公司项目需要对接firebase推送,官方文档就是谢特,再网上找了很多大神的资料,还是有很多坑,把自己踩的坑记录一下,平时都是伸手党,这次回馈一下
use GoogleClient;
/**
* 注意需要准备vpn
* 1.安装sdk composer require google/apiclient:^2.12.1
* 2.firebase推送,如要本地调试需找到vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php 中 applyHandlerOptions 方法,设置$options["verify"] = false;
* @param $param ["title"=>推送标题,"body"=>推送信息]
* @param $token 设备token
* @return bool|string
*/
public function send($param, $token)
{
$client = new Client();
$client->useApplicationDefaultCredentials();
$client->setAuthConfig($this->app->getRootPath() . "public/path/to/xxxx-xxxx-3f599409d1e3.json");//引入json秘钥
$client->setScopes("https://www.googleapis.com/auth/firebase.messaging"); # 授予访问 FCM 的权限
// 你的 Firebase 项目 ID
$project = "firebase-aca99";
$send_url = "https://fcm.googleapis.com/v1/projects/{$project}/messages:send";
$access_token = $client->fetchAccessTokenWithAssertion();//获取秘钥
if (!isset($access_token["access_token"])) {
Log::error("推送失败,未获取到秘钥");
return false;
}
$accessToken = $access_token["access_token"];//秘钥
//推送参数
$params = [
"message" => [
"token" => $token, //需要发送的设备号
"notification" => $param
]
];
//header请求头,$accessToken 就是你上面获取的令牌
$header = [
"Content-Type: application/json",
"Authorization: Bearer " . $accessToken,
];
$response = http_post($send_url, json_encode($params), ["headers" => $header]);
$response = json_decode($response,true);
if(isset($response["name"])){
return true;
}elseif(isset($response["error"])){
Log::error("推送失败:{$response["error"]["code"]},{$response["error"]["message"]}");
return false;
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » PHP Firebase HTTP v1 API 新版推送