gpt4 book ai didi

php - Google oauth2 访问 token 将在 1 小时后过期。我想做 1 天

转载 作者:可可西里 更新时间:2023-11-01 00:40:15 24 4
gpt4 key购买 nike

我已经使用 Google OAuth2 凭据创建了一个用于 Google 日历的项目。

但是,访问 token 每 1 小时过期一次。

谁能帮我把过期时间改成 1 天。

我已使用此代码访问谷歌日历事件:

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));

if (isset($_GET['code']))
$google_oauth_code = $_GET['code'];
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$_SESSION['last_action'] = time();
}

最佳答案

关于 Oauth2,您需要了解一些事情。访问 token 的生命周期很短,它们只能持续一个小时,这是它们的工作方式,您无法更改。

您应该做的是在设置以下内容时存储身份验证过程返回的刷新 token 。

$client->setAccessType('offline');

通过使用刷新 token ,您可以请求一个新的访问 token 。此示例可能有助于它显示如何在访问 token 过期时设置它。 upload example

大概是这样的。

    $client = new Google_Client();
$client->setApplicationName(APPNAME);
$client->setClientId(CLIENTID); // client id
$client->setClientSecret(CLIENTSECRET); // client secret
$client->setRedirectUri(REDIRECT_URI); // redirect uri
$client->setApprovalPrompt('auto');

$client->setAccessType('offline'); // generates refresh token

$token = $_COOKIE['ACCESSTOKEN'];

// if token is present in cookie
if($token){
// use the same token
$client->setAccessToken($token);
}

// this line gets the new token if the cookie token was not present
// otherwise, the same cookie token
$token = $client->getAccessToken();

if($client->isAccessTokenExpired()){ // if token expired
$refreshToken = json_decode($token)->refresh_token;

// refresh the token
$client->refreshToken($refreshToken);
}

return $client;
}

关于php - Google oauth2 访问 token 将在 1 小时后过期。我想做 1 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42996918/

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