我遇到的情况是我必须使用zend框架和oauth 2来获取gmail。 一切正常,我收到消息并登录就好了,我的问题是令牌过期时间过长了。
我能够设置它以便永不过期或我应该如何为框架实现刷新令牌?我在登录时使用标准代码。
我基本上需要的是一个不会过期的访问令牌,或者是如何实现刷新令牌以及如何在程序中使用它的指南。
任何帮助表示赞赏。 谢谢。
这是登录页面。
include("../classes/Google/Client.php");
$client_id = "hidden";
$client_secret = "hidden";
$redirect_uri = "hidden";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$client->addScope("https://www.googleapis.com/auth/userinfo.profile");
$client->addScope("https://mail.google.com/");
$client->setRedirectUri($redirect_uri);
$authUrl = $client->createAuthUrl();
echo "<a href=".$authUrl.">Login</a>";
这是回调
$client_id = "hidden";
$client_secret = "hidden";
$redirect_uri = "hidden";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
session_start();
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$oauth2 = new Google_Service_Oauth2($client);
$user = $oauth2->userinfo->get();
$_SESSION['email'] = $user;
$redirect = 'hidden';
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
我知道代码不是很好,但我想知道我是否应该获得刷新令牌以及访问令牌?
答案 0 :(得分:1)
如果有人感兴趣我已经这样做了解决它......现在它的工作原理应该如此。
每次我需要对邮件执行某些操作时都会调用此方法(如果访问令牌无效,则您将无法访问,因此这是为了确保访问始终存在。)
public function checktokenexpiry()
{
global $google_client; // this is global as we use it in our webservice.
session_start();
$time_created = json_decode($_SESSION['access_token']);
$t=time();
$timediff=$t-$time_created->created;
if($timediff>3500) // 3500 as i want to have a little time to connect if it is just about to need refreshing.
{
$user = json_decode($_COOKIE['user']);
$usermail = $user->email;
$refreshtoken = $this->model->getRefreshToken($usermail);
$refreshtoken = $refreshtoken[0]['google_refresh_token'];
$google_client->refreshToken($refreshtoken);
$_SESSION['access_token'] = $google_client->getAccessToken();
}
}