public function fcm_command($token,$command){
$path_to_fcm = 'https://fcm.googleapis.com/v1/projects/projects/messages:send';
//Taglock Server Key
$server_key = "";
$headers = array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);
$fields = array('to'=>$token,'data'=>array('command'=>$command));
$payload = json_encode($fields);
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$res = curl_exec($curl_session);
curl_close($curl_session);
return array('status'=>REST_Controller::HTTP_OK,'message'=> 'Command sent to device');
}
我正在使用旧的 $server_key 并且仅更新了
$path_to_fcm = 'https://fcm.googleapis.com/v1/projects/projects/messages:send';
,但没有收到通知。我需要生成新的服务器密钥还是需要旧的?
v1 API 的身份验证/授权不再使用服务器密钥。我建议您阅读有关授权发送请求的文档以查找当前选项,还可以查看:
v1 API 不再有效,您必须迁移到 HTTP v1 https://firebase.google.com/docs/cloud-messaging/migrate-v1
库 Google Api 客户端 https://github.com/googleapis/google-api-php-client/releases
从 Firebase“管理服务帐户”获取 JSON。
可以查看这个代码示例:
require_once '/google-api-php-client/vendor/autoload.php';
function notification($notifications){
$serviceAccountPath = 'service-account-file.json';
// Your Firebase project ID
$projectId = 'xxxxxx';
// Example message payload
$message = [
'token' => 'deviceToken',
'notification' => [
'title' => $title,
'body' => $msg,
],
];
$accessToken = getAccessToken($serviceAccountPath);
$response = sendMessage($accessToken, $projectId, $message);
}
function getAccessToken($serviceAccountPath) {
$client = new Client();
$client->setAuthConfig($serviceAccountPath);
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->useApplicationDefaultCredentials();
$token = $client->fetchAccessTokenWithAssertion();
return $token['access_token'];
}
function sendMessage($accessToken, $projectId, $message) {
$url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';
$headers = [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}