gpt4 book ai didi

php - Google API Oauth php 永久访问

转载 作者:IT王子 更新时间:2023-10-29 00:18:03 25 4
gpt4 key购买 nike

我正在使用谷歌日历 API。这就是我想要的,一旦您授予该应用程序权限,我就可以随时使用该应用程序,而无需每天都授予访问权限。我一直听说我需要保存访问 token 或使用刷新 token 来做我想做的事情。事情是这样的,你是怎么做到的?代码看起来如何?我试过将 token 保存在 cookie 中,但一个小时后,访问 token 已过期。如何让用户保持登录状态?

PS:请给我代码示例和解释。

这是我的代码(使用 CakePHP):

$client = new Google_Client();

$client->setApplicationName("Wanda3.0 Agenda");

$cal = new Google_CalendarService($client);

if (isset($_GET['code'])) {

$client->authenticate($_GET['code']);


$_SESSION['token'] = $client->getAccessToken();


header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);

}

if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); }

if ($client->getAccessToken()) {
/************* Code entry *************/


}else{
/************* Not connected to google calendar code *************/
$authUrl = $client->createAuthUrl();

$returnArr = array('status' => 'false', 'message' => "<a class='login' href='$authUrl'>Connect Me!</a>");

return $returnArr;

}

最佳答案

Ok,等了几天,Terry Seidler(评论下方)的建议让这一切都发生了!这是我的一段代码,介绍如何自动刷新访问 token ,而无需每次都使用 cookie 进行验证。

(注意:将刷新 token 保存在数据库中更安全)

这就是魔法(使用 cookie):

$client = new Google_Client();

$client->setApplicationName("Wanda3.0 Agenda");

$cal = new Google_CalendarService($client);

$client->setAccessType('offline');

if (isset($_GET['code'])) {

$client->authenticate($_GET['code']);

$_SESSION['token'] = $client->getAccessToken();

header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);

}

//Where the magic happends
if (isset($_SESSION['token'])) {

//Set the new access token after authentication
$client->setAccessToken($_SESSION['token']);

//json decode the session token and save it in a variable as object
$sessionToken = json_decode($_SESSION['token']);

//Save the refresh token (object->refresh_token) into a cookie called 'token' and make last for 1 month
$this->Cookie->write('token', $sessionToken->refresh_token, false, '1 month');
}

//Each time you need the access token, check if there is something saved in the cookie.
//If $cookie is empty, you are requested to get a new acces and refresh token by authenticating.
//If $cookie is not empty, you will tell the client to refresh the token for further use,
// hence get a new acces token with the help of the refresh token without authenticating..
$cookie = $this->Cookie->read('token');

if(!empty($cookie)){
$client->refreshToken($this->Cookie->read('token'));
}

就是这样!如果您有任何问题,请随时在下面发表评论,我会尽我所能回答。祝你好运,干杯!

关于php - Google API Oauth php 永久访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com