我几乎搜索了谷歌首页的所有结果。但似乎找不到答案。我正在使用谷歌API的refresh_token并接收:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }
我在做什么?首先:我正在创建和存储到google api的持久连接:
$client = new Google_Client();
$client->setClientId('xxxxxx-s73q0pa41aq3i2kcpatmpas6e6kkp99h.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxx');
$client->setRedirectUri('http://xxxxxxxx/generaterefreshtoken.php');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setAccessType('offline');
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
$jsonarray = json_decode($client->getAccessToken());
$arrGoogleAuth['access_token']=$jsonarray->access_token;
$arrGoogleAuth['refresh_token']=$jsonarray->refresh_token;
//filewrite
$myFile = "refreshtoken.conf";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $client->getAccessToken());
fclose($fh);
/*
die();
$service = new Google_DriveService($client);
$file = new Google_DriveFile();
$file->setTitle('My document.txt');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
*/
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
header("Location: $auth");
}
所以基本上一切都运行了令牌被存储在一个文本文件中:
{
"access_token":"xxxxxxxxxxxxxxxN4U0ys2wy5monxs0Xh5fu5ayKL0OIENo-d1sN6g3YA",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"xxxxxxxxxxxxDON-l90BNUcJgnkfZWDfg",
"created":1358120143
}
当我尝试使用以下代码验证时:
$client = new Google_Client();
$client->setClientId($googleDriveConfig['clientid']);
$client->setClientSecret($googleDriveConfig['clientsecret']);
$client->setRedirectUri(curPageURL);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->refreshToken(file_get_contents('../_config/refreshtoken.conf'));
$client->authenticate();
我得到以下错误:刷新OAuth2令牌错误,消息:'{" Error ": "invalid_grant"}
如果您尝试在令牌未过期时刷新,将得到"invalid_grant"错误。
而不是:
$client->refreshToken(file_get_contents('../_config/refreshtoken.conf'));
使用:
$client->setAccessToken(file_get_contents('../_config/refreshtoken.conf'));
一旦你的令牌过期,你应该刷新工作
invalid_grant表示授权码已经被使用(在$GET['code']
中可用),或者在Google api Console中配置的应用程序类型无效。
在Google api控制台注册应用程序时,请确保选择"Web Application"。
为我工作的函数如下
客户端-> setAccessType("refresh_token");
我遇到了类似的事情,对我来说问题是我的系统时钟(在我运行代码的Docker VM内)没有与实时同步。因此,您请求的令牌所创建的日期在过去或将来太远,OAuth将拒绝。
我被这篇报道给提醒了。
在验证之前,必须有如下内容:
$client->grantType("refresh_token")