我跟着THIS TUTORIAL直接从远程服务器上传了一个带有php的Google Drive上的文件:所以我从Google API控制台创建新的API项目,启用Drive API和Drive SDK服务,请求OAuth客户端ID和客户端密钥,并将其写入脚本,然后将其与Google APIs Client Library for PHP文件夹一起上传到http://www.MYSERVER.com/script1.php,以检索身份验证代码:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('XXX'); // HERE I WRITE MY Client ID
$drive->setClientSecret('XXX'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$url = $drive->createAuthUrl();
$authorizationCode = trim(fgets(STDIN));
$token = $drive->authenticate($authorizationCode);
?>
当我访问http://www.MYSERVER.com/script1.php时,它运行得很好,所以我允许授权并获得我可以在第二个脚本中编写的Auth代码。然后我将其上传到http://www.MYSERVER.com/script2.php,看起来像是:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('X'); // HERE I WRITE MY Client ID
$drive->setClientSecret('X'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code']= 'X/XXX'; // HERE I WRITE AUTH CODE RETRIEVED AFTER RUNNING REMOTE script.php
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Drive');
$doc->setDescription('Document');
$doc->setMimeType('text/plain');
$content = file_get_contents('drive.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
?>
好吧,现在我可以在MYSERVER的同一个文件夹中上传一个token.json空文件(可写)和一个简单的drive.txt(要在我的驱动器中上传的文件),但是当我最终访问http://www.MYSERVER.com/script2.php浏览器时每次都会出现 HTTP 500(内部服务器错误),并且我的Google云端硬盘上没有上传文件:步骤中有错误,或者脚本存在问题?请帮我解决这个问题!
修改
MYSERVER错误日志已满:
PHP Fatal error: Uncaught exception 'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in /var/www/vhosts/.../gdrive/google-api-php-client/src/auth/Google_OAuth2.php:113
Stack trace:
#0 /var/www/vhosts/.../gdrive/google-api-php-client/src/Google_Client.php(131): Google_OAuth2->authenticate(Array, NULL)
#1 /var/www/vhosts/.../gdrive/sample2.php(23): Google_Client->authenticate()
#2 {main}
thrown in /var/www/vhosts/.../gdrive/google-api-php-client/src/auth/Google_OAuth2.php on line 113
答案 0 :(得分:2)
似乎您无法获得新的访问令牌,因为您的旧令牌尚未过期,这就是此代码告诉您的内容:
'Google_AuthException',显示消息'提取OAuth2访问令牌时出错,消息:'invalid_grant'
您必须获取访问令牌ONCE,将其保存在某处并使用它直到它过期,每次尝试查询时都无法获得新的访问令牌
撤销您的第一个访问令牌转到Google API Console,您会在已安装应用程序的客户端ID 下找到它
最好的问候