I want to get estimated earnings with the Adsense API so I used example from https://github.com/googleads/googleads-adsense-examples/tree/HEAD/v2/php.
With this example, I used OAuth to get a JSON:
{
"access_token": "ya29.a0AVAXXXXXX",
"expires_in": 3599,
"scope": "https:\\/\\/www.googleapis.com\\/auth\\/adsense.readonly",
"token_type": "Bearer",
"created": 1661430866,
"refresh_token": "ya29.a0AVA9yXXXXX"
}
With this access, I can get the report I want but the token doesn't refresh its expiration date despite using the refresh token.
Why?
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAuthConfig($CLIENT_SECRET_FILE_LOCATION);
$service = new Google_Service_Adsense($client);
$refresh_token = json_decode(file_get_contents($token_file),true);
$client->refreshToken($refresh_token);
$newToken = $client->getAccessToken();
$token = $client->setAccessToken($newToken);
file_put_contents($token_file, json_encode($newToken["refresh_token"]));
CodePudding user response:
I think you are missing the section of code which actually refreshes it when the access token is expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
}
CodePudding user response:
I change my code with DalmTo suggestion
// Set up authentication.
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAuthConfig($CLIENT_SECRET_FILE_LOCATION);
$service = new Google_Service_Adsense($client);
$refresh_token = json_decode(file_get_contents($token_file),true);
$client->refreshToken($refresh_token);
$token = $client->getAccessToken();
echo "EXPIRE IN ".($token["expires_in"]).PHP_EOL;
if ($client->isAccessTokenExpired()) {
echo "TOKEN EXPIRED".PHP_EOL;
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$newToken = $client->getAccessToken();
file_put_contents($token_file, json_encode($newToken["refresh_token"]));
echo "NEW TOKEN SAVED".PHP_EOL;
echo "EXPIRE IN ".($newToken["expires_in"]).PHP_EOL;
}
Sill not work.
Can i force a refresh token by commenting the if condition ?
if ($client->isAccessTokenExpired()) {
I'm also not sure if i'm saving the good part of the new token in my JSON file