[英]How to use the FCM HTTP v1 API with php
我已經將 FCM 與舊協議一起使用,但找不到任何具體的文檔來將新的 FCM HTTP v1 API 與 php 結合使用。
我已設法將Google API 客戶端庫導入到我的項目中,但找不到有關如何獲取 fcm 消息所需范圍的訪問令牌的任何文檔或教程。
可能有點晚了,但這是檢索要與 FCM HTTP v1 API 一起使用的誓言令牌的方法。
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()
方法,因為您更喜歡存儲和檢索誓言令牌 json。 遵循有效負載結構的遷移指南。
如果您願意使用現有的庫而不是自己實現它,您可以考慮查看https://github.com/kreait/firebase-php/ ,它今天剛剛獲得了對 FCM 的支持。
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的實現。
在作者的帶領下,這里有一個使用 FCM HTTP v1 API 的示例 php 項目:
回購: https : //github.com/jeromegamez/firebase-php-examples
包文檔: https : //firebase-php.readthedocs.io/en/latest/cloud-messaging.html
包倉庫: https : //github.com/kreait/firebase-php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.