在远程服务器上使用google api php客户端时,HTTP 500(内部服务器错误)


HTTP 500 (Internal Server Error) when using google api php client on a remote server

我遵循本教程,直接从远程服务器上用php在谷歌驱动器上上传文件:所以我从谷歌API控制台创建新的API项目,启用驱动器API和驱动器SDK服务,请求OAuth客户端ID和客户端秘密,并将它们写在脚本中,然后将其与谷歌API客户端库一起上传到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的同一个文件夹中上传一个令牌。json空文件(可写)和一个简单的驱动器。txt(文件上传到我的驱动器),但当我终于访问http://www.MYSERVER.com/script2.php浏览器给出每次HTTP 500(内部服务器错误)和obv没有文件上传到我的谷歌驱动器:有错误的步骤,或一些问题的脚本?请帮我解决这个问题!

编辑:

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

似乎你不能获得新的访问令牌,因为你的旧的还没有过期,这就是这段代码告诉你的:

'Google_AuthException' with message '取回OAuth2访问令牌错误,message: 'invalid_grant'

您必须获得访问令牌一次,将其保存在某个地方并使用它直到它过期,您不能每次尝试查询某事时都获得新的访问令牌

撤销你的第一个访问令牌去谷歌API控制台,你会发现它在客户端ID为已安装的应用程序