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

 ̄綄美尐妖づ 提交于 2020-01-20 06:05:59

问题


I am facing an issue with quickstart php script here: https://developers.google.com/drive/v2/web/quickstart/php

When I run the script first time, it executes perfectly and the access token is stored in a file called: drive-php-quickstart.json

When I run the script second time, it gives me the error:

Error start:

Notice: Undefined index: expires_in in \google-api-php-client\src\Google\Client.php on line 485

Fatal error: Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in

Error end:

My assumption is that access token been saved in the file is not in the right format.

Current format:

ya29.CODE-oN_Bearer36001/_ANOTHER-CODE-ANOTHER_ANOTHER_CODE

As you can see, it does not contain the variable "expires_in"

Any suggestions where I am going wrong ? I am running the script as it is, with no modifications.


回答1:


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());
}



回答2:


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()));
}


来源:https://stackoverflow.com/questions/34384222/issue-with-google-api-php-client-getting-error-when-running-the-quick-start-scr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!