如何在使用google api时设置refresh_token? [英] How can I set the refresh_token when working with the google api?
问题描述
我正在尝试学习如何使用google api更改日历上的事件。服务器是将根据数据库中的信息更新日历的用户。实际上不需要用户交互。
问题是我遇到/使用刷新令牌的问题。我点击了添加到页面的Connect Me链接,它给了我一个错误:
致命错误:未捕获异常'Google_Auth_Exception'消息'错误刷新OAuth2令牌,消息:'{错误:invalid_request,error_description:缺少必需的参数:refresh_token}
我有尝试以这种方式设置刷新标记,以及类似的方法,但似乎没有一个我打印出 $ _ SESSION ['access_token']
变量,它不显示 refresh_token
:
$ b
{access_token:token ,token_type:Bearer,expires_in:3599,created:1417534503}
授权'用户'而不用 refresh_token
部分(基于示例):
function googleAuth(){
$ client_id ='myclientid';
$ client_secret ='myclientsecret';
$ redirect_uri ='redirecturi';
$ client = new Google_Client();
$ client-> setAccessType('offline');
$ client-> setClientId($ client_id);
$ client-> setClientSecret($ client_secret);
$ client-> setRedirectUri($ redirect_uri);
$ client-> setScopes('https://www.googleapis.com/auth/calendar');
/ ***************************************** *******
如果我们注销,我们只需要清除我们的
本地访问令牌在这种情况下
************* *********************************** /
if(isset($ _ REQUEST ['logout' ])){
unset($ _ SESSION ['access_token']);
}
/ **************************************** ********
如果我们从OAuth 2.0流程返回代码
,则需要使用authenticate()
函数交换该代码。我们将生成的访问令牌
包存储在会话中,并重定向到我们自己。
********************************************** ** /
if(isset($ _ GET ['code'])){
$ resp = $ client-> authenticate($ _ GET ['code']);
$ _SESSION ['access_token'] = $ client-> getAccessToken();
$ redirect ='https://'。 $ _SERVER ['HTTP_HOST']。 $ _SERVER [ PHP_SELF];
header('Location:'。filter_var($ redirect,FILTER_SANITIZE_URL));
}
/ ************************************ ************
如果我们有访问令牌,则可以发出
请求,否则我们会生成一个验证URL。
********************************************** ** /
if(isset($ _ SESSION ['access_token'])&& $ _SESSION ['access_token']){
$ client-> setAccessToken($ _ SESSION ['access_token'] );
} else {
$ authUrl = $ client-> createAuthUrl();
}
if(isset($ authUrl)){
echo< a class ='login'href ='。 $ authUrl。 '>连接我!< / a>;
}
return $ client;
}
以下是我用于将事件添加到日历的代码:
函数addEvent($ title,$ location,$ startTime,$ stopTime,$ client){
$ event = new Google_Service_Calendar_Event();
$ start = new Google_Service_Calendar_EventDateTime();
$ event-> setSummary($ title);
$ event-> setLocation($ location);
$ start-> setDateTime($ startTime);
$ end = new Google_Service_Calendar_EventDateTime();
$ end-> setDateTime($ stopTime);
$ event-> setStart($ start);
$ event-> setEnd($ end);
$ atendee = new Google_Service_Calendar_EventAttendee();
$ atendee-> setEmail(someGuy@someDomain.com');
$ atendees = array($ atendee);
$ event->参加者= $ atendees;
$ service = new Google_Service_Calendar($ client);
$ event_id = $ service-> events-> insert('primary',$ event);
如何设置缺少的参数:refresh_token?代码的结构是否存在问题?我已经浏览过文档,我愿意再看一些,但如果有人可以帮助解释如何做到这一点,那将是惊人的。谢谢!
检查令牌是否有刷新令牌(如果您请求离线访问,则会发送刷新令牌第一次使用访问令牌)。
类似于此
$ token = $ client-> getAccessToken();
$ authObj = json_decode($ token);
if(isset($ authObj-> refresh_token)){
save_refresh_token($ authObj-> refresh_token);
}
其中save_refresh_token将刷新令牌保存在某处(db)。
然后您可以检查令牌是否过期:
$ client-> isAccessTokenExpired()
如果是这样,您可以更新它:
$ client-> refreshToken($ your_saved_refresh_token);
然后将您的新访问令牌设置为会话:
$ _SESSION ['access_token'] = $ client-> getAccessToken();
I'm working off an example trying to learn how to use the google api to change events on a calendar. The server is the user which will update the calendar based off of information in a database. No user interaction is actually required.
The problem is I am having issues getting/using refresh tokens. I click the "Connect Me" link that gets added to the page and it gives me an error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_request", "error_description" : "Missing required parameter: refresh_token" }
I have tried setting the refresh token this way, along with similar methods, but none of them seem to work which makes me think I am implementing them incorrectly.
When I print out the $_SESSION['access_token']
variable, it shows no refresh_token
:
{"access_token":"token","token_type":"Bearer","expires_in":3599,"created":1417534503}
Here is the function I am using to authorize the 'user' without the refresh_token
portion(based off an example):
function googleAuth(){
$client_id = 'myclientid';
$client_secret = 'myclientsecret';
$redirect_uri = 'redirecturi';
$client = new Google_Client();
$client->setAccessType('offline');
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes('https://www.googleapis.com/auth/calendar');
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$resp = $client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
if (isset($authUrl)) {
echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
}
return $client;
}
Here is the code I am using to add the event to the calendar:
function addEvent($title, $location, $startTime, $stopTime, $client){
$event = new Google_Service_Calendar_Event();
$start = new Google_Service_Calendar_EventDateTime();
$event->setSummary($title);
$event->setLocation($location);
$start->setDateTime($startTime);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($stopTime);
$event->setStart($start);
$event->setEnd($end);
$atendee = new Google_Service_Calendar_EventAttendee();
$atendee->setEmail('someGuy@someDomain.com');
$atendees = array($atendee);
$event->attendees = $atendees;
$service = new Google_Service_Calendar($client);
$event_id = $service->events->insert('primary', $event);
}
How can I set the missing parameter: "refresh_token"? Are there issues with the structure of the code? I have looked through documentation, and I am willing to look some more, but if somebody can lend a hand at explaining how to do this, that would be amazing. Thanks!
Check if the token has a refresh-token (if you request offline access, the refresh-token will be sent with the access token the first time).
Something like this
$token = $client->getAccessToken();
$authObj = json_decode($token);
if(isset($authObj->refresh_token)) {
save_refresh_token($authObj->refresh_token);
}
Where save_refresh_token saves your refresh-token somewhere (db).
Then you can check if token as expired by:
$client->isAccessTokenExpired()
If it is, you can update it with:
$client->refreshToken($your_saved_refresh_token);
And then set your new access token to the session:
$_SESSION['access_token'] = $client->getAccessToken();
这篇关于如何在使用google api时设置refresh_token?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!