php - 如何将 FCM HTTP v1 API 与 php 结合使用

标签 php firebase firebase-cloud-messaging

我已将 FCM 与旧协议(protocol)一起使用,但找不到任何具体文档来将新的 FCM HTTP v1 API 与 php 结合使用。

我已成功导入 Google API Client Library进入我的项目,但找不到任何有关如何获取 fcm 消息所需范围的访问 token 的文档或教程。

最佳答案

也许有点晚了,但这就是如何检索要与 FCM HTTP v1 API 一起使用的誓言 token 。

  • 下载此 Google library在您的 php 代码中使用它。
  • Firebase console 生成并下载新的私钥
  • 将此 key 以 json 格式存储在服务器上的安全位置。

如何使用您的私钥配置 Google 客户端

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
    }
}

如何请求新的 oauth token

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() 方法,因为您更喜欢存储和检索誓言 token json。关注migration guide有效负载结构。

关于php - 如何将 FCM HTTP v1 API 与 php 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49782134/

相关文章:

php - 如何在 URL 中获取一组未知的 $_GET 值?

php - 如何完全刷新 CodeIgniter 中的页面?

javascript - 如何在使用 firestore 进行本地 react 时滚动到底部时获取数据?

android - 禁用 Firebase 云消息传递的分析服务

android - Android 推送通知的 FCM 限制?

java - Flutter FCM后台调用平台特定代码

php-curl_multi "Illegal characters found in URL"

javascript - 如何在给定的 JavaScript 代码中使变量动态化?

javascript - Angular Fire,嵌套 ng-repeat

firebase - Flutter-将图像上传到Firebase存储