【发布时间】:2013-09-11 10:20:57
【问题描述】:
每个人 我需要通过 API 将文件上传到 Google Drive,我确实做到了https://developers.google.com/drive/quickstart-php 中提到的内容。
我已生成访问令牌并将其保存在文件中,问题是它仅在第一次有效,下次出现错误
OAuth2 token, message: '{ "error" : "invalid_grant" }
我们只需要通过表单从用户那里获取文件后,将文件上传到谷歌驱动器(我们自己的帐户)。
我尝试过许多教程中的脚本,但似乎没有用。 我也尝试过离线访问权限,但仍然没有运气。
更新: 这是我用来生成访问令牌的代码
require_once APP_PATH.'_includes/google_drive/Google_Client.php';
require_once APP_PATH.'_includes/google_drive/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('xxxxxxxxxxxxxxxx');
$drive->setClientSecret('xxxxxxxxxxxxxxx');
$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);
然后我使用了这段代码 $drive = new Google_Client();
$drive->setClientId('xxxxxxxxxxx');
$drive->setClientSecret('xxxxxxxxxxxxxxx');
$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']= '4/axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Document');
$doc->setDescription('Test description');
$doc->setMimeType('text/plain');
$content = file_get_contents('document.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
效果很好,但是当我再次运行该页面时,它显示
Fatal error: Uncaught exception 'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in ...Google_OAuth2.php on line 115
感谢任何帮助。
【问题讨论】:
-
您似乎再次致电
$client->authenticate($authCode);。请说明你用 sn-p 做什么。 -
@BurcuDogan 我已经更新了问题,我已经完全按照本教程中提到的html.it/articoli/google-drive-e-php-come-integrarli
-
感谢@BurcuDogan,删除验证方法后它可以工作。
-
这条线在做什么?我在这条线上遇到错误
$authorizationCode = trim(fgets(STDIN));Use of undefined constant STDIN - 假定为“STDIN”你能解释一下 STDIN 吗? -
什么是标准输入?看起来它还没有定义。
标签: php google-drive-api