GoogleDriveAPI-OAuth2-下载文件-PHP

GoogleDriveAPI-OAuth2-下载文件-PHP,php,google-api,google-drive-api,google-oauth,Php,Google Api,Google Drive Api,Google Oauth,我试图使用GoogleDriveAPI和它的PHP库从我的GoogleDrive下载一个文件,但是我在检索文件内容时遇到了障碍 /* * Initialize Google Client */ $client = new \Google_Client(); $client->setClientId(CLIENT_ID); $client->setClientSecret(CLIENT_SECRET); $client->setRedirectUri(REDIRECT_URI

我试图使用GoogleDriveAPI和它的PHP库从我的GoogleDrive下载一个文件,但是我在检索文件内容时遇到了障碍

/*
 * Initialize Google Client
 */
$client = new \Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

/*
 * Set access token (yes, it's valid)
 */
$client->setAccessToken(ACCESS_TOKEN);

$service = new \Google_Service_Drive($client);

/*
 * Find the certain file
 */
foreach ($service->files->listFiles()->getItems() as $item) {
    /**
     * @var \Google_Service_Drive_DriveFile $item
     */

    if ($item->getTitle() == 'test.txt') {
        $sUrl = $item->getDownloadUrl();

        /*
         * Do a request
         */
        $request = new \Google_Http_Request($sUrl, 'GET', null, null);
        $httpRequest = $client->getIo()->executeRequest($request);

        if ($httpRequest->getResponseHttpCode() == 200) {
            echo $httpRequest->getResponseBody();

            exit();
        } else {
            /*
             * Something went wrong
             */
            return null;
        }
    }
}
首先要注意的是,根据类文档和Google的示例,Google_IO_Abstract::executeRequestGoogle_Http_请求应该返回Google_Http_请求,但是id不返回。它返回这个关联数组

array(3) {
  [0]=>
  bool(false)
  [1]=>
  array(12) {
    ["access-control-allow-origin"]=>
    string(1) "*"
    ["access-control-allow-credentials"]=>
    string(5) "false"
    ["access-control-allow-headers"]=>
    string(1000) "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, Date, GData-Version, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, X-ClientDetails, X-GData-Client, X-GData-Key, X-Goog-AuthUser, X-Goog-PageId, X-Goog-Encode-Response-If-Executable, X-Goog-Correlation-Id, X-Goog-Request-Info, X-Goog-Experiments, x-goog-iam-role, x-goog-iam-authorization-token, X-Goog-Spatula, X-Goog-Upload-Command, X-Goog-Upload-Content-Disposition, X-Goog-Upload-Content-Length, X-Goog-Upload-Content-Type, X-Goog-Upload-File-Name, X-Goog-Upload-Offset, X-Goog-Upload-Protocol, X-Goog-Visitor-Id, X-HTTP-Method-Override, X-JavaScript-User-Agent, X-Pan-Versionid, X-Origin, X-Referer, X-Upload-Content-Length, X-Upload-Content-Type, X-Use-HTTP-Status-Code-Override, X-YouTube-VVT, X-YouTube-Page-CL, X-YouTube-Page-Timestamp"
    ["access-control-allow-methods"]=>
    string(11) "GET,OPTIONS"
    ["www-authenticate"]=>
    string(50) "GoogleLogin realm="http://www.google.com/accounts""
    ["date"]=>
    string(29) "Wed, 24 Dec 2014 11:23:16 GMT"
    ["expires"]=>
    string(29) "Wed, 24 Dec 2014 11:23:16 GMT"
    ["cache-control"]=>
    string(18) "private, max-age=0"
    ["server"]=>
    string(59) "UploadServer ("Built on Dec 19 2014 10:24:45 (1419013485)")"
    ["content-length"]=>
    string(1) "0"
    ["content-type"]=>
    string(24) "text/html; charset=UTF-8"
    ["alternate-protocol"]=>
    string(15) "443:quic,p=0.02"
  }
  [2]=>
  int(401)
}
从这个数组中,我们可以看到内容长度为0,这表明出现了问题

如果我直接从浏览器调用文件的下载URL,它会返回401个未经授权的错误,这可能是正确的,因为我的浏览器的请求未经授权,但这意味着文件确实存在,下载URL是正确的,我应该能够通过API下载它


对如何访问文件内容有何建议?

请参阅您参考的文档:

使用PHP客户端库的$client->getIo->authenticatedRequest助手方法检索文件内容

请注意,这是一个经过身份验证的请求。也许是你的问题,希望对你有所帮助

编辑:

文件必须是过时的。authenticatedRequest在Google_Auth_抽象类中,而不是在Google_IO_抽象中。我认为守则应该是:

$client->getAuth()->authenticatedRequest($request);

我找到了解决办法

首先,您需要登录到谷歌的开发者控制台。 转到API&auth->Credentials 并确保你有一个服务帐户。如果没有,请单击创建新客户ID->Service account

在那里你会收到一个P12文件和一封电子邮件

现在,回到代码

    $downloadURL = $item->getDownloadUrl();
    $key = file_get_contents("WHERE YOUR GOOGLE KEY FILE IS.p12");
    if (!$key)
        return null;
    $email = "WHAT IS THE EMAIL PROVIDED BY GOOGLE";
    $cred = new Google_Auth_AssertionCredentials($email, array(Google_Service_Drive::DRIVE), $key);
    $this->client->setAssertionCredentials($cred);
    $cred->sub = $email;

    $request = new Google_Http_Request($downloadURL, 'GET', null, null);
    $httpRequest = $this->client->getAuth()->authenticatedRequest($request);
    if ($httpRequest->getResponseHttpCode() == 200) {
...

其余的和往常一样。

谢谢,但是在Google\u IO\u Abstract class@user10099中没有authenticatedRequest方法。你说得对。我更新了答案,我相信这是正确的代码。我希望能成功。你成功了吗?如果您能发回有效的源代码,我将不胜感激。如下所述,文档API完全过时了……是的,我已经过时了,我会尽快发布解决方案。是的,这是因为过时的谷歌文档和GitHub上过时的资源。。