Google API php客户端的授权错误
我尝试使用Google API PHP客户端使我的应用程序以脱机方式使用其Google Drive帐户,因为我不希望我的应用程序每次都重定向到Google以获得授权 因此,当我第一次连接并使用access\u令牌和refresh\u令牌接收凭据时,我会备份它并尝试每次使用它 问题是,它一直工作到到期,然后,当API客户端尝试刷新acces令牌时,我不断收到以下错误: 刷新OAuth2令牌时出错,消息:“{”Error:“无效的请求”,“错误描述”:“客户端必须指定客户端id或客户端断言,而不是两者”} 我存储的凭据采用json格式: {“访问令牌”:“XXX”,“令牌类型”:“承载者”,“过期于”:3600,“刷新令牌”:“XXX”,创建:1406537500} 我的代码(摘自谷歌教程,有一些改动):Google API php客户端的授权错误,php,google-api,google-drive-api,Php,Google Api,Google Drive Api,我尝试使用Google API PHP客户端使我的应用程序以脱机方式使用其Google Drive帐户,因为我不希望我的应用程序每次都重定向到Google以获得授权 因此,当我第一次连接并使用access\u令牌和refresh\u令牌接收凭据时,我会备份它并尝试每次使用它 问题是,它一直工作到到期,然后,当API客户端尝试刷新acces令牌时,我不断收到以下错误: 刷新OAuth2令牌时出错,消息:“{”Error:“无效的请求”,“错误描述”:“客户端必须指定客户端id或客户端断言,而不是两
buildService方法的客户端对象尝试根据传递的凭据刷新时出错。我可能自己解决了这个问题。它现在可以工作。因此,正如您在buildService函数中的代码中所看到的,我只设置了凭据最新时所需的字段。但是,当这些字段过期时,为了使刷新客户端有效,需要设置这些字段对象必须用所需字段的其余部分填充。我添加的字段是clientId、作用域、访问类型和客户端。
function exchangeCode($authorizationCode) {
try {
$client = new Google_Client();
$client->setClientId(self::$clientId);
$client->setClientSecret(self::$clientSacred);
$client->setRedirectUri(self::getRedirectURI());
$_GET['code'] = $authorizationCode;
return $client->authenticate();
} catch (Google_AuthException $e) {
echo 'An Google_AuthException occurred: ' . $e->getMessage();
throw new CodeExchangeException(null);
}
}
function getCredentials($authorizationCode, $state='') {
$emailAddress = '';
try {
$credentials = self::exchangeCode($authorizationCode);
$credentialsArray = json_decode($credentials, true);
if (isset($credentialsArray['refresh_token'])) {
self::storeCredentials($credentials);
return $credentials;
} else {
$credentials = self::getStoredCredentials();
$credentialsArray = json_decode($credentials, true);
if ($credentials != null &&
isset($credentialsArray['refresh_token'])) {
return $credentials;
}
}
} catch (CodeExchangeException $e) {
print 'An CodeExchangeException occurred during code exchange.';
$e->setAuthorizationUrl(self::getAuthorizationUrl($emailAddress, $state));
throw $e;
} catch (NoUserIdException $e) {
print 'No e-mail address could be retrieved.';
}
$authorizationUrl = self::getAuthorizationUrl($emailAddress, $state);
throw new NoRefreshTokenException($authorizationUrl);
}
function buildService($credentials) {
$apiClient = new Google_Client();
$apiClient->setUseObjects(true);
$apiClient->setAccessToken($credentials);
return new Google_DriveService($apiClient);
}
function test()
{
$credentials = self::getStoredCredentials();
if ( empty($credentials) )
{
if (!isset($_GET["code"]))
{
header("location:".self::getAuthorizationUrl("xxx@gmail.com", ''));
die();
}
$credentials = self::getCredentials($_GET["code"]);
echo "NEW: ".$credentials;
}
else
{
echo "STORED: ".$credentials;
}
$service = self::buildService($credentials);
}