Google Drive API - 获取共享文件下载链接 [英] Google Drive API - Fetch Shared Files Download Links
问题描述
我是Google云端硬盘新手,上传了许多文件。如果下载链接已知,我已经更改了要共享的所有文件的状态。
我想使用PHP来生成文件的所有直接下载链接的列表。 PHP脚本在我的本地主机上运行,我只需要将该数组保存到稍后使用的文本文件中。
我试图让Oauth工作非常困难,但遇到了这个看起来像我需要的脚本。我建立了我的服务帐户,并有我的服务帐户电子邮件和.p12文件。
我下载了Google PHP客户端代码库并在我的本地主机上设置了一个测试脚本。这是我的
require_onceGoogle / Client.php;
require_onceGoogle / Service / Drive.php;
require_onceGoogle / Service / Oauth2.php;
require_onceGoogle / Auth / AssertionCredentials.php;
session_start();
函数buildService($ userEmail){
$ SERVICE_ACCOUNT_EMAIL ='12345@developer.gserviceaccount.com';
$ SERVICE_ACCOUNT_PKCS12_FILE_PATH ='12345-privatekey.p12';
$ key = file_get_contents($ SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$ auth = new Google_AssertionCredentials(
$ SERVICE_ACCOUNT_EMAIL,
array('https://www.googleapis.com/auth/drive'),
$ key);
$ auth-> sub = $ userEmail;
$ client = new Google_Client();
$ client-> setUseObjects(true);
$ client-> setAssertionCredentials($ auth);
返回新的Google_DriveService($ client);
}
// ...函数retrieveAllFiles($ service)
$ service = buildService(myemail@gmail.com);
$ allFiles = retrieveAllFiles($ service);
print_r($ allFiles);
我正在处理这个例子
http://stackoverflow.com/questions/21046631/google-drive-api-php-cant-list-files
和这个
https://developers.google.com/ drive / web / delegation#instantiate_a_drive_service_object
我不确定要做什么,我添加了所需的库,但是PHP脚本中未知的以下函数即将发布
Google_AssertionCredentials
setUseObjects
Google_DriveService
$ b $ retrieveAllFiles
我错过了一个明显的库?在这个例子中,它们的命名方式不同,但我猜测基础名称在更新后发生了变化......我花了很多时间阅读Google Drive和Oauth,但没有任何运气。我用这个脚本的唯一目标是获得直接下载链接的列表。我可以手动执行,但文件太多。
任何帮助都会很棒。
谢谢。
*编辑:*
hr>所以我这就是我试图获得我的令牌:
我遵循以下快速入门指南: / p>
https://developers.google.com/drive/web/quickstart/quickstart-php
$ b这是我的代码
< ;?php
require_once'Google / client.php';
require_once'Google / Service / drive.php';
defined('STDIN')或define('STDIN',fopen('php:// stdin','r')); //我必须添加这部分,因为我得到一个未定义的错误STDIN
$ client = new Google_Client();
//从控制台获取您的凭证
$ client-> setClientId('xxx.apps.googleusercontent.com');
$ client-> setClientSecret('xxx');
$ client-> setRedirectUri('http://localhost/test/fetch.php'); //与注册的相同
$ client-> setScopes(array('https://www.googleapis.com/auth/drive'));
$ service = new Google_Service_Drive($ client);
$ authUrl = $ client-> createAuthUrl();
//请求授权
打印请访问:\ $ $ authUrl\\\
\\\
;
print请输入验证码:\\\
;
$ authCode = trim(fgets(STDIN));
//访问令牌的交换授权码
$ accessToken = $ client-> authenticate($ authCode);
$ client-> setAccessToken($ accessToken);
这会导致错误
致命错误:在C:\Apache24\htdocs\test\Google\Auth\OAuth2.php:95堆栈跟踪:#中带有'无效代码'消息的未捕获异常'Google_Auth_Exception' 0 C:\Apache24\htdocs\test\Google\Client.php(135):Google_Auth_OAuth2-> authenticate('')#1 C:\Apache24\htdocs\test\\\
ew。 php(26):Google_Client-> authenticate('')#2 {main}抛出C:\Apache24\htdocs\test\Google\Auth\OAuth2.php 95行
有什么想法?
谢谢。
另一个编辑
由于新的Drive PHP库没有文档或示例,因此我已恢复到旧的Drive PHP库。
这是我尝试获取令牌并获取直接下载文件的链接。
require_once'google-old / google-api-php-client / src / Google_Client.php';
require_once'google-old / google-api-php-client / src / contrib / Google_DriveService.php';
$ client = new Google_Client();
//从控制台获取您的凭证
$ client-> setClientId('xx.apps.googleusercontent.com');
$ client-> setClientSecret('xx');
$ client-> setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$ client-> setScopes(array('https://www.googleapis.com/auth/drive'));
$ service = new Google_DriveService($ client);
$ authUrl = $ client-> createAuthUrl();
//请求授权
打印请访问:\ $ $ authUrl\\\
\\\
;
print请输入验证码:\\\
;
$ authCode = trim(fgets(STDIN));
//访问令牌的交换授权码
$ accessToken = $ client-> authenticate($ authCode);
$ client-> setAccessToken($ accessToken);
$ getAll = retrieveAllFiles($ service);
print< pre>;
print_r($ getAll);
打印< / pre>;
/ **
*检索文件资源列表。
*
* @param Google_DriveService $ service Drive API服务实例。
* @return Array Google_DriveFile资源的列表。
* /
函数retrieveAllFiles($ service){
$ result = array();
$ pageToken = NULL;
do {
try {
$ parameters = array();
if($ pageToken){
$ parameters ['pageToken'] = $ pageToken;
}
$ files = $ service-> files-> listFiles($ parameters);
$ result = array_merge($ result,$ files-> getItems());
$ pageToken = $ files-> getNextPageToken();
} catch(Exception $ e){
print发生错误:。 $ E->的getMessage();
$ pageToken = NULL;
}
} while($ pageToken);
返回$ result;
}
我现在面临的问题是我被困在粘贴代码进入你的应用程序部分。
$ p
$ b$ authCode = trim (与fgets(STDIN));
似乎不想执行。
另外我相信文件抓取代码只会抓取文件名,而不是直接下载链接。我找不到这样的例子。
任何建议将不胜感激。
谢谢。
我在本地主机上测试了这个。
解决方案替换STDIN的东西。
if(!isset($ _ GET ['code'])){
print请访问:\ N $ authUrl\\\
\\\
;
print请输入验证码:\\\
;
} else {$ authCode =''; }
// $ authCode = trim(fgets(STDIN));
$ authCode = $ _GET ['code'];
Google的代码在他们的方面有问题。完成后,我得到了文件创建(它仍然在输出一个错误,但是它产生了这些文件)。
将file_get_contents行替换为:
$ data ='blahblah blah'; // file_get_contents('document.txt');
然后你就去了。
I am new to Google Drive and have uploaded many files. I have changed the status of all files to be shared if the download link is known.
I would like to use PHP to generate a list of all of the direct download links for the files. The PHP script is run on my localhost and I just need the array to be saved to a text file to be used later.
I have had a very hard time trying to get Oauth working but came across this script that looks like what I need. I set up my service account and have my service account email and .p12 file.
I downloaded the Google PHP client code base and set up a test script on my localhost. This is what I have
require_once "Google/Client.php"; require_once "Google/Service/Drive.php"; require_once "Google/Service/Oauth2.php"; require_once "Google/Auth/AssertionCredentials.php"; session_start(); function buildService($userEmail) { $SERVICE_ACCOUNT_EMAIL = '12345@developer.gserviceaccount.com'; $SERVICE_ACCOUNT_PKCS12_FILE_PATH = '12345-privatekey.p12'; $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH); $auth = new Google_AssertionCredentials( $SERVICE_ACCOUNT_EMAIL, array('https://www.googleapis.com/auth/drive'), $key); $auth->sub = $userEmail; $client = new Google_Client(); $client->setUseObjects(true); $client->setAssertionCredentials($auth); return new Google_DriveService($client); } //... function retrieveAllFiles($service) $service = buildService("myemail@gmail.com"); $allFiles = retrieveAllFiles($service); print_r($allFiles);
I am working off of this example
http://stackoverflow.com/questions/21046631/google-drive-api-php-cant-list-files
and this
https://developers.google.com/drive/web/delegation#instantiate_a_drive_service_object
I am unsure what to do, I have added the required libraries but the following functions are coming up as being unknown in the PHP script
Google_AssertionCredentials setUseObjects Google_DriveService retrieveAllFiles
Am I missing an obvious library? They are named different in the example but I'm guessing the base names have changed since there were updates... I have spent a lot of time reading up on Google Drive and Oauth without any luck. My only goal with this script is to get a list of the direct download links. I can do it manually but there are too many files.
Any help would be great.
Thanks.
* EDIT: *
So I this is what I have tried to obtain my token:
I am following this quick start guide:
https://developers.google.com/drive/web/quickstart/quickstart-php
Here is my code
<?php require_once 'Google/client.php'; require_once 'Google/Service/drive.php'; defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); //I had to add this part as I was getting an undefined error for STDIN $client = new Google_Client(); // Get your credentials from the console $client->setClientId('xxx.apps.googleusercontent.com'); $client->setClientSecret('xxx'); $client->setRedirectUri('http://localhost/test/fetch.php'); //same as registered one $client->setScopes(array('https://www.googleapis.com/auth/drive')); $service = new Google_Service_Drive($client); $authUrl = $client->createAuthUrl(); //Request authorization print "Please visit:\n$authUrl\n\n"; print "Please enter the auth code:\n"; $authCode = trim(fgets(STDIN)); // Exchange authorization code for access token $accessToken = $client->authenticate($authCode); $client->setAccessToken($accessToken);
This results in error
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Invalid code' in C:\Apache24\htdocs\test\Google\Auth\OAuth2.php:95 Stack trace: #0 C:\Apache24\htdocs\test\Google\Client.php(135): Google_Auth_OAuth2->authenticate('') #1 C:\Apache24\htdocs\test\new.php(26): Google_Client->authenticate('') #2 {main} thrown in C:\Apache24\htdocs\test\Google\Auth\OAuth2.php on line 95
Any thoughts ?
Thanks.
ANOTHER EDIT
So I have reverted to the old Drive PHP library as the new Drive PHP library has no documentation or examples.
This is my attempt to obtain a token and fetch the direct download file links
require_once 'google-old/google-api-php-client/src/Google_Client.php'; require_once 'google-old/google-api-php-client/src/contrib/Google_DriveService.php'; $client = new Google_Client(); // Get your credentials from the console $client->setClientId('xx.apps.googleusercontent.com'); $client->setClientSecret('xx'); $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob'); $client->setScopes(array('https://www.googleapis.com/auth/drive')); $service = new Google_DriveService($client); $authUrl = $client->createAuthUrl(); //Request authorization print "Please visit:\n$authUrl\n\n"; print "Please enter the auth code:\n"; $authCode = trim(fgets(STDIN)); // Exchange authorization code for access token $accessToken = $client->authenticate($authCode); $client->setAccessToken($accessToken); $getAll = retrieveAllFiles($service); print "<pre>"; print_r($getAll); print "</pre>"; /** * Retrieve a list of File resources. * * @param Google_DriveService $service Drive API service instance. * @return Array List of Google_DriveFile resources. */ function retrieveAllFiles($service) { $result = array(); $pageToken = NULL; do { try { $parameters = array(); if ($pageToken) { $parameters['pageToken'] = $pageToken; } $files = $service->files->listFiles($parameters); $result = array_merge($result, $files->getItems()); $pageToken = $files->getNextPageToken(); } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); $pageToken = NULL; } } while ($pageToken); return $result; }
The problem I now face is that I am stuck at the "Paste the code into your app" part.
The
$authCode = trim(fgets(STDIN));
doesn't seem to want to execute.
Also I believe the file fetching code will just fetch the file names, and not the direct download links. I could not find an example for this.
Any suggestions would be much appreciated.
Thanks.
I am testing this on my localhost.
解决方案Replace the STDIN stuff.
put this in instead:
if (!isset($_GET['code'])) { print "Please visit:\n$authUrl\n\n"; print "Please enter the auth code:\n"; } else { $authCode = ''; } //$authCode = trim(fgets(STDIN)); $authCode = $_GET['code'];
Google's code is buggy in terms of their thing. Having done so I'm getting file creation (it's still pumping out an error but it's producing the files).
replace their file_get_contents line with:
$data = 'blahblah blah';//file_get_contents('document.txt');
and there you go.
这篇关于Google Drive API - 获取共享文件下载链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!