Google Drive API - oAuth 2 - 下载文件 - PHP.



我正在尝试使用Google Drive API及其PHP库从我的Google云端硬盘下载文件,但是我无法检索文件内容。

/*
 * 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_IO_Abstract::executeRequest(Google_Http_Request)应该返回Google_Http_Request(根据类文档和Google的示例 https://developers.google.com/drive/web/examples/php),但是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 helper 方法检索文件内容

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


编辑:

文档必须已过时。authenticatedRequestGoogle_Auth_Abstract类中,而不是在Google_IO_Abstract中.我认为代码应该是:

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

我找到了解决方案。

首先,您需要登录到Google中的开发人员控制台。转到 API 和身份验证 -> 凭据并确保您拥有服务帐户。如果没有,请单击"创建新的客户端 ID"->"服务帐户"。

在那里,您将收到一个 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) {
...

其余的像往常一样。

相关内容

  • 没有找到相关文章

最新更新