使用 Google API 客户端刷新令牌
在使用 Google Analytics API (V3) 时,用户可能会遇到错误,特别是在尝试检索时来自测试帐户以外的帐户的数据。此问题通常表现为 403 错误。另外,即使撤销并重新验证令牌后,问题也可能会在令牌过期时重新出现。
为了解决这个问题,解决方案是利用refreshToken方法来获取新的验证令牌。但是,执行 $client->refreshToken(refresh_token_key) 可能会产生无效授予错误消息(“error”:“invalid_grant”)。
在研究refreshToken方法背后的代码后,很明显以下内容参数已发送正确:
令牌刷新的过程如下如下:
$client = new apiClient(); $client->setClientId($config['oauth2_client_id']); $client->setClientSecret($config['oauth2_client_secret']); $client->setRedirectUri($config['oauth2_redirect_uri']); $client->setScopes('https://www.googleapis.com/auth/analytics.readonly'); $client->setState('offline'); $client->setAccessToken($config['token']); // The access JSON object. $client->refreshToken($config['refreshToken']); // Will return error here
解决问题的关键是理解身份验证时获得的初始令牌拥有刷新令牌。虽然初始令牌会在一小时内过期,但可以利用刷新令牌来获取新令牌。但是,请务必注意,此临时令牌也会在一小时后过期,并且没有关联的刷新令牌。因此,要检索新的临时令牌,必须使用初始令牌的刷新令牌。
为了清楚起见,以下代码提供了详细说明:
// Retrieve original token from database $tokenquery = "SELECT * FROM token WHERE type='original'"; $tokenresult = mysqli_query($cxn, $tokenquery); if ($tokenresult != 0) { $tokenrow = mysqli_fetch_array($tokenresult); extract($tokenrow); } $time_created = json_decode($token)->created; $t = time(); $timediff = $t - $time_created; $refreshToken = json_decode($token)->refresh_token; // Initialize Google client $client = new Google_Client(); $client->setApplicationName(''); $client->setScopes(array()); $client->setClientId(''); $client->setClientSecret(''); $client->setRedirectUri(''); $client->setAccessType('offline'); $client->setDeveloperKey(''); // Refresh token if expired if (($timediff > 3600) && ($token != '')) { $refreshquery = "SELECT * FROM token WHERE type='refresh'"; $refreshresult = mysqli_query($cxn, $refreshquery); // If refresh token exists if ($refreshresult != 0) { $refreshrow = mysqli_fetch_array($refreshresult); extract($refreshrow); $refresh_created = json_decode($token)->created; $refreshtimediff = $t - $refresh_created; // If refresh token is also expired if ($refreshtimediff > 3600) { $client->refreshToken($refreshToken); $newtoken = $client->getAccessToken(); $tokenupdate = "UPDATE token SET token='$newtoken' WHERE type='refresh'"; mysqli_query($cxn, $tokenupdate); $token = $newtoken; echo "refreshed again"; } else { $client->setAccessToken($token); echo "use refreshed token but not time yet"; } } else { $client->refreshToken($refreshToken); $newtoken = $client->getAccessToken(); $tokenupdate = "INSERT INTO token (type, token) VALUES ('refresh', '$newtoken')"; mysqli_query($cxn, $tokenupdate); $token = $newtoken; echo "refreshed for first time"; } } // If token is still valid if (($timediff < 3600) && ($token != '')) { $client->setAccessToken($token); } $service = new Google_DfareportingService($client);
以上是使用 Google Analytics API 刷新令牌时如何解决'invalid_grant”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!