After lots of research and experiments, I was able to display all Google Reviews on my website, the reason to post this question here is, I played with API for the first time, and I have few questions raising on my mind. I am not sure whether my approach is correct or it can be improved further? Whether the code is safe in terms of security-wise too.
The following steps were taken, you might know, we have to do some Prerequisites, which I did.
After getting approval, I tested the API through Google Oauth Playground and managed to get
accoundId
andlocationId
. (https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}/reviews)To implement the reviews on the website, I used the Google PHP Client Library (https://github.com/googleapis/google-api-php-client).
Now let's come on to the main part, to fetch all results we need to add "Access token" at the end of the URL. (https://mybusiness.googleapis.com/v4/accounts/102xxxxxxx/locations/733xxxxxxx/reviews?access_token=xxxxxxxxxx)
Now, the problem was access token gets expired after an hour, to overcome this I generated a refresh token and use the following code. Although I am not sure, whether the refresh token ever gets expired?
<?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.
Now, the questions raised on my mind:
- The refresh token which I generated through Googe OAuth playground can get expire? If yes do I have to regenerate the token again through Playground and manually add the codes every time in the file?
- These two lines I am confused with. The following code generates a new access token on each page refresh is this normal flow? or is it against any Google Policies or I am just overthinking?
$access_token = $client->getAccessToken(); // confused here...
$client->setAccessToken($access_token); // confused here..
- Do I need to store the refresh token or access token in any file or database?