刷新的Google API无法获取文件列表驱动器。 Google_Service_Exception(Err 400)

时间:2018-10-10 10:20:19

标签: php google-api google-drive-api google-api-php-client

我正在尝试使用Google Drive API V2和Google的PHP客户端库("google/apiclient": "^2.0")将Web应用程序与Google Drive连接。

我的应用程序在第一个小时内可以正常工作。我可以获取文件,上传文件等,但是1小时后(当访问令牌过期且需要刷新时),随后的获取/上传会导致Google_Service_Exception (Err 400)

  

您的客户发出了格式错误或非法的请求。

enter image description here

我成功获取访问和刷新令牌:

{
 "access_token":"**********",
 "expires_in":3600,
 "refresh_token":"1/********",
 "scope":"https://www.googleapis.com/auth/drive",
 "token_type":"Bearer",
 "created":1539085127
}

我试图通过这种方式刷新令牌:

if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}

以这种方式:

if ($client->isAccessTokenExpired()) {
    $client->refreshToken($client->getRefreshToken());
}

我如何正确地将收到的凭据保存一个多小时?

2 个答案:

答案 0 :(得分:0)

客户端设置听起来有些不对劲。试试这个

function getOauth2Client() {
    try {

        $client = buildClient();

        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }

        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 

            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

Oauth2Authentication.php翻录可能也有帮助oauth2callback.php

答案 1 :(得分:0)

您可以尝试使用curl获取文件列表。

如果要从Google驱动器获取所有文件。

在curl中使用此网址:

https://www.googleapis.com/drive/v2/files

或者,如果要从特定文件夹中获取文件。

在curl中使用此网址:

https://www.googleapis.com/drive/v2/files?q='".$yourDriveFolderId."'+in+parents

Google Drive Documentation