我需要通过 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
任何帮助表示赞赏。