我按照本教程直接从远程服务器使用 php 在 Google Drive 上上传文件:所以我从 Google API 控制台创建新的 API 项目,启用 Drive API 和 Drive SDK 服务,请求 OAuth 客户端 ID 和客户端密码,并编写它们在脚本中,然后将其与Google APIs Client Library for PHP文件夹一起上传到http://www.MYSERVER.com/script1.php,以检索 Auth 代码:
<?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 Drive 中没有文件上传:步骤中有错误,或者脚本有问题?请帮我解决这个问题!
编辑:
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