<?php
require_once __DIR__ .'/../vendor/google-api-php-client-v2.8.0-PHP5.4/vendor/autoload.php';
use Google\Client;
$client = new Google\Client();
$client->useApplicationDefaultCredentials();
$client->setAuthConfig( __DIR__ .'/../vendor/google-api-php-client-v2.8.0-PHP5.4/upad12-xxxxxx.json');//引入json秘钥
$client->setScopes('https://www.googleapis.com/auth/firebase.messaging'); // 授予访问 FCM 的权限
$send_url = "https://fcm.googleapis.com/v1/projects/upad12-4c8c9/messages:send";
$access_token = $client->fetchAccessTokenWithAssertion();//获取秘钥
if (!isset($access_token['access_token'])) {
return json_encode(['err_no' => 1, 'msg' => '推送失败,未获取到秘钥'],JSON_UNESCAPED_UNICODE);
}
$accessToken = $access_token['access_token'];//秘钥
$params = [
"message" => [
"token" =>'設備 token',
"notification" => [
"title" => 'title',
"body" => 'body'
]
]
];
//header请求头,$accessToken 就是你上面获取的令牌
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken,
];
$params = json_encode($params);
$response = http_post($send_url, $params, $header);
$response = json_decode($response,true);
if(isset($response['name'])){
echo json_encode(['err_no' => 0, 'msg' => '推送成功',['data'=>$response]],JSON_UNESCAPED_UNICODE);
exit();
}elseif(isset($response['error'])){
echo json_encode(['err_no' => 1, 'msg' => '消息未送达',['data'=>$response]],JSON_UNESCAPED_UNICODE);
exit();
}
function http_post($send_url,$params,$headers){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $send_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $params,
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}