Issue with Google-API-PHP Client, getting error when running the quick start script

老子叫甜甜 提交于 2019-11-29 10:47:29

I've debugged it.... The person who wrote it made a mistake by not calling json_encode before writing the auth result to the token.json file.

You can fix it by adding json_encode on line 45.

So...

file_put_contents($credentialsPath, $accessToken);

...should be:

file_put_contents($credentialsPath, json_encode($accessToken));

I've submitted feedback so hopefully it'll be fixed.

edit: same issue happens for the token refresh call in that same method

edit2: Here's my related comment in a Github discussion and an answer from Google: https://github.com/google/google-api-php-client/issues/263#issuecomment-186557360

I suggested something along the following lines:

if ($client->isAccessTokenExpired()) {
    $refreshToken = $client->getRefreshToken();
    $client->refreshToken($refreshToken);
    $newAccessToken = $client->getAccessToken();
    $newAccessToken['refresh_token'] = $refreshToken;
    file_put_contents($credentialsPath, json_encode($newAccessToken));
}

Instead of:

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $client->refreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, $client->getAccessToken());
}

Google has updated their PHP Quickstart, with an improved method to handle this:

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

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!