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

前端 未结 2 1170
我寻月下人不归
我寻月下人不归 2020-12-19 08:17

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 perfect

相关标签:
2条回答
  • 2020-12-19 08:44

    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()));
    }
    
    0 讨论(0)
  • 2020-12-19 08:57

    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());
    }
    
    0 讨论(0)
提交回复
热议问题