我以前使用过FCM的旧协议,但是找不到任何关于如何在php中使用新的FCM HTTP v1 API的具体文档。
我已成功将Google API Client Library导入到我的项目中,但是找不到有关如何获取FCM消息所需范围的访问令牌的文档或教程。
我以前使用过FCM的旧协议,但是找不到任何关于如何在php中使用新的FCM HTTP v1 API的具体文档。
我已成功将Google API Client Library导入到我的项目中,但是找不到有关如何获取FCM消息所需范围的访问令牌的文档或教程。
public function configureClient()
{
$client = new Google_Client();
try {
$client->setAuthConfig("include_your_private_json_key_path_here");
$client->addScope(Google_Service_FirebaseCloudMessaging::CLOUD_PLATFORM);
// retrieve the saved oauth token if it exists, you can save it on your database or in a secure place on your server
$savedTokenJson = $this->readFile();
if ($savedTokenJson != null) {
// the token exists, set it to the client and check if it's still valid
$client->setAccessToken($savedTokenJson);
if ($client->isAccessTokenExpired()) {
// the token is expired, generate a new token and set it to the client
$accessToken = $this->generateToken($client);
$client->setAccessToken($accessToken);
}
} else {
// the token doesn't exist, generate a new token and set it to the client
$accessToken = $this->generateToken($client);
$client->setAccessToken($accessToken);
}
$oauthToken = $accessToken["access_token"];
// the client is configured, now you can send the push notification using the $oauthToken.
} catch (Google_Exception $e) {
// handle exception
}
}
private function generateToken($client)
{
$client->fetchAccessTokenWithAssertion();
$accessToken = $client->getAccessToken();
// save the oauth token json on your database or in a secure place on your server
$tokenJson = json_encode($accessToken);
$this->saveFile($tokenJson);
return $accessToken;
}
saveFile()
和readFile()
方法应根据您的喜好实现以存储和检索oath token json。按照迁移指南中的有效负载结构操作。2023年7月更新
批量消息端点已被弃用,并将于2024年7月移除。建议通过迭代令牌使用标准的v1 API发送方法:https://firebase.google.com/docs/cloud-messaging/send-message#send-a-batch-of-messages
以下是向单个设备发送通知的示例:
<?php
require_once '<Path_to_google-api-php-client>/vendor/autoload.php';
function getOATHToken()
{
$client = new Google_Client();
try {
$client->setAuthConfig("<path_to_your_private_json_key.json>");
$client->addScope(Google_Service_FirebaseCloudMessaging::CLOUD_PLATFORM);
$savedTokenJson = readSavedToken();
if ($savedTokenJson) {
// the token exists, set it to the client and check if it's still valid
$client->setAccessToken($savedTokenJson);
$accessToken = $savedTokenJson;
if ($client->isAccessTokenExpired()) {
// the token is expired, generate a new token and set it to the client
$accessToken = generateToken($client);
$client->setAccessToken($accessToken);
}
} else {
// the token doesn't exist, generate a new token and set it to the client
$accessToken = generateToken($client);
$client->setAccessToken($accessToken);
}
$oauthToken = $accessToken["access_token"];
return $oauthToken;
} catch (Google_Exception $e) {}
return false;
}
//Using a simple file to cache and read the toke, can store it in a databse also
function readSavedToken() {
$tk = @file_get_contents('token.cache');
if ($tk) return json_decode($tk, true); else return false;
}
function writeToken($tk) {
file_put_contents("token.cache",$tk);
}
function generateToken($client)
{
$client->fetchAccessTokenWithAssertion();
$accessToken = $client->getAccessToken();
$tokenJson = json_encode($accessToken);
writeToken($tokenJson);
return $accessToken;
}
// Finally
function sendNotification($token, $title, $body, $accessToken) {
$payload = ["message" => ["token" => $token, "notification"=>["title" => $title, "body"=> $body]]];
$postdata = json_encode($payload);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json' . "\r\nAuthorization: Bearer $accessToken",
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://fcm.googleapis.com/v1/projects/<your_firebase_project_id>/messages:send', false, $context);
echo "\n\n======RESPONSE======\n\n";
echo $result;
}
$token = "token-1"; //FCM Device token
$title = "Test from PHP";
$body = "This is a test from PHP";
sendNotification($token, $title, $body, getOATHToken());
?>
批量发送示例(现已弃用)
以下是使用Google API PHP Client和FCM HTTP v1 api的完整示例,演示如何向多个令牌发送推送通知,具体步骤请参考FCM文档。
<?php
require_once '<Path_to_google-api-php-client>/vendor/autoload.php';
function getOATHToken()
{
$client = new Google_Client();
try {
$client->setAuthConfig("<path_to_your_private_json_key.json>");
$client->addScope(Google_Service_FirebaseCloudMessaging::CLOUD_PLATFORM);
$savedTokenJson = readSavedToken();
if ($savedTokenJson) {
// the token exists, set it to the client and check if it's still valid
$client->setAccessToken($savedTokenJson);
$accessToken = $savedTokenJson;
if ($client->isAccessTokenExpired()) {
// the token is expired, generate a new token and set it to the client
$accessToken = generateToken($client);
$client->setAccessToken($accessToken);
}
} else {
// the token doesn't exist, generate a new token and set it to the client
$accessToken = generateToken($client);
$client->setAccessToken($accessToken);
}
$oauthToken = $accessToken["access_token"];
return $oauthToken;
} catch (Google_Exception $e) {}
return false;
}
//Using a simple file to cache and read the toke, can store it in a databse also
function readSavedToken() {
$tk = @file_get_contents('token.cache');
if ($tk) return json_decode($tk, true); else return false;
}
function writeToken($tk) {
file_put_contents("token.cache",$tk);
}
function generateToken($client)
{
$client->fetchAccessTokenWithAssertion();
$accessToken = $client->getAccessToken();
$tokenJson = json_encode($accessToken);
writeToken($tokenJson);
return $accessToken;
}
// Finally
function sendNotification($tokens, $title, $body, $accessToken) {
$boundary = "--subrequest_boundary";
$multiPayload = $boundary;
foreach ($tokens as $token) {
$head = "Content-Type: application/http\r\n".
"Content-Transfer-Encoding: binary\r\n\r\n".
"POST /v1/projects/<your_firebase_project_name>/messages:send\r\n".
"Content-Type: application/json\r\n".
"accept: application/json\r\n\r\n";
$payload = ["message" => ["token" => $token, "notification"=>["title" => $title, "body"=> $body]]];
$postdata = json_encode($payload);
$multiPayload .= "\r\n".$head.$postdata."\r\n".$boundary;
}
$multiPayload .= "--";
//Uncomment for debugging
//echo "\n\n==== POST DATA====\n\n";
//echo $multiPayload;
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: multipart/mixed; boundary="subrequest_boundary"' . "\r\nAuthorization: Bearer $accessToken",
'content' => $multiPayload
)
);
//Uncomment for debugging
//echo "\n\n==== HTTP OPTIONS====\n\n";
//var_dump($opts);
$context = stream_context_create($opts);
// This is the path for sending push multiple tokens (upto 500 as per the docs)
$result = file_get_contents('https://fcm.googleapis.com/batch', false, $context);
echo "\n\n======RESPONSE======\n\n";
echo $result;
}
$tokens = ["token-1","token-2"]; //FCM Device tokens as array
$title = "Test from PHP";
$body = "This is a test from PHP";
sendNotification($tokens, $title, $body, getOATHToken());
?>
https://firebase-php.readthedocs.io/en/latest/cloud-messaging.html
如果您不需要它,您至少可以从源代码中提取与PHP连接到FCM REST API的连接。简而言之,这是https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages的实现。