Google API刷新令牌
问题描述:
我一直在尝试在最初的几个小时内从最初的Google API调用中打印我的refresh_token(即使在取消授权和重新授权的情况下(如其他人所暗示的那样),但我仍然没有运气... API按预期工作,但我想设置更新功能,以便用户在令牌到期后不会失去访问权限(导致错误)。Google API刷新令牌
目前,下面的代码将$ _SESSION ['refresh_token']设置为null。
任何帮助,因为我一直在敲我的头靠在键盘相当长的一段时间内不胜感激...
private function googleAnalyticsClient(){
App::import('Vendor', 'google-api-php-client', array('file' => 'autoload.php'));
$client = new Google_Client();
$client->setAuthConfigFile(__DIR__ . '/client_secrets.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
public function getOauth()
{
App::import('Vendor', 'google-api-php-client', array('file' => 'autoload.php'));
// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfigFile(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/dashboard/tpstats';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
答
在getOauth()函数中添加以下
$client = new Google_Client();
$client->setAuthConfigFile(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessType('offline'); //To fetch refresh token(Refresh token issued only first time)
$client->setApprovalPrompt('force'); //Adding this will force for refresh token
通过试验和错误,我终于能够得到它的工作。我只是在$ client-> authenticate()之后var_dump'd $ client ...有时您只需要一些睡眠:P感谢您的帮助 – trehm