簡體   English   中英

Google My Business API - 我設法顯示所有評論

[英]Google My Business API - I managed to display all reviews

經過大量的研究和實驗,我能夠在我的網站上顯示所有的谷歌評論,在這里發布這個問題的原因是,我第一次玩 API,我的想法很少。 我不確定我的方法是否正確還是可以進一步改進? 代碼在安全方面是否也是安全的。

采取了以下步驟,您可能知道,我們必須做一些先決條件,我做到了。

  1. 獲得批准后,我通過 Google Oauth Playground 測試了 API 並設法獲得了accoundIdlocationId ( https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}/reviews )

  2. 為了在網站上實施評論,我使用了 Google PHP 客戶端庫 ( https://github.com/googleapis/google-api-php-client )。

現在讓我們進入主要部分,為了獲取我們需要在 URL 末尾添加“訪問令牌”的所有結果。 https://mybusiness.googleapis.com/v4/accounts/102xxxxxxx/locations/733xxxxxxx/reviews?access_token=xxxxxxxxxx

現在,問題是訪問令牌在一個小時后過期,為了解決這個問題,我生成了一個刷新令牌並使用以下代碼。 雖然我不確定,刷新令牌是否會過期?

<?php
// include your composer dependencies
require_once 'GoogleClientApi/vendor/autoload.php'; // or wherever autoload.php is located

$refreshToken = 'xxxxxxxxxxxx'; // generrated from https://developers.google.com/oauthplayground/
$name = "accounts/xxxxxxx/locations/xxxxxxxx"; // generrated from https://developers.google.com/oauthplayground/

//PHP Client Library 
$client = new Google_Client();

$client->setClientId("xxxxxx"); // generated from Google Cloud Platform
$client->setClientSecret("xxxxx");  // generated from Google Cloud Platform
$client->refreshToken($refreshToken); // as set above in variable.

//Authorization Scopes
//$client->addScope("https://www.googleapis.com/auth/business.manage"); // Not needed probably.

$access_token = $client->getAccessToken(); // confused here...
$client->setAccessToken($access_token); // confused here..

$token = $access_token['access_token'];

$jsonDoc = file_get_contents("https://mybusiness.googleapis.com/v4/accounts/xxxxx/locations/xxxx/reviews?access_token=$token");

$array = json_decode($jsonDoc, true); // when true works as assoc array ?>

print_r($array) // output the JSON formatted reviews.

現在,我想到的問題是:

  1. 我通過 Googe OAuth playground 生成的刷新令牌會過期嗎? 如果是,我是否必須通過 Playground 再次重新生成令牌並每次在文件中手動添加代碼?
  2. 這兩行我很困惑。 以下代碼在每次頁面刷新時生成一個新的訪問令牌,這是正常流程嗎? 還是違反了任何 Google 政策,或者我只是想多了?
$access_token = $client->getAccessToken(); // confused here...
$client->setAccessToken($access_token); // confused here..
  1. 我是否需要將刷新令牌或訪問令牌存儲在任何文件或數據庫中?

使用此代碼將遇到的問題是,每次刷新令牌到期時,您都需要再次對其進行授權。

如果您使用的是 oauth2 playground,則刷新令牌可能會經常過期。 由於 Playground 僅用於測試目的。

您應該考慮做的是創建一個單用戶系統。 代碼被授權,然后刷新令牌存儲在以下示例中名為 token.json 的文件中

您需要授權一次,然后它會通過使用 token.json 文件中的刷新令牌請求一個新的來加載訪問令牌。

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('PHP Quickstart');
    $client->setScopes(Google_Service_Drive::BUSINESS.MANAGE);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');


    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

我的一些筆記。

此代碼將像在 Web 瀏覽器中而不是在 Web 瀏覽器中一樣運行命令。 我建議您將您期望從 API 獲得的響應緩存到數據庫中。 然后向用戶顯示來自數據庫的響應。 如果您願意,您可以將此代碼設置為每小時運行一次 cron 作業,但實際上沒有理由讓它為每個用戶實時運行。 如果您嘗試這樣做,您可能會用完報價。 緩存它是一個更好的選擇。

由於谷歌最近進行了一些更改,如果您的應用程序處於測試階段並且尚未經過驗證,您的刷新令牌最多只能使用兩周。 之后,用戶同意將被撤銷,刷新令牌將過期,您需要再次對其進行授權。 因此,在使用此產品進行生產之前,請務必申請驗證。 當你去谷歌時向谷歌解釋它是一個單用戶腳本。

在此處輸入圖片說明

我有一個關於驗證過程的視頻,可能會有所幫助。 您需要了解的有關 2021 年 Google 驗證的信息。

需要刷新令牌才能再次重新生成訪問令牌。 所以你必須存儲刷新令牌。 訪問令牌在一小時后過期,而刷新令牌永不過期,您可以在需要時從刷新令牌中檢索訪問令牌。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM