【发布时间】:2016-02-24 15:11:28
【问题描述】:
我正在使用 vue.js 构建一个 SPA,它有一个 PHP 后端服务器(slim framework 3 )。这是两个独立的项目,放在两个不同的服务器上,后端根本没有前端。
SPA (vue.js) 通过 ajax 向后端发出请求。
现在我想实现 Google Calendar API,以便在用户每次创建待办事项时创建日历和事件。为此,我需要服务器到服务器访问 Google Calendar API(即使用户未登录,我也可能需要更改 GCAL 上的事件)。
我想了解的是,如何使用 vue.js 使用 Google JS 库获取访问令牌(和刷新令牌)并将其保存在数据库中,以便我的后端可以使用它向 GCAL Api 发出离线请求.
当我通过 JS 库使用 Oauth v.2 时,我得到的只是 access_token,它不能用于服务器到服务器的通信。
[更新]
好的,更多信息。我正在遵循Google 的指南,我的前端现在看起来像这样 jsbin
所以我可以成功地授权用户并使用 javascript sdk 访问他们的日历。但是 Javascript SDK 返回的令牌是这样的
{
_aa: "1"
access_token: "xxxxxxx"
client_id: "yyyyyyyyyy"
cookie_policy: undefined
expires_at: "1456400189"
expires_in: "3600"
g_user_cookie_policy: undefined
issued_at: "1456396589"
response_type: "token"
scope: "https://www.googleapis.com/auth/calendar"
state: ""
status: Object
google_logged_in: false
method: "AUTO"
signed_in: true
token_type: "Bearer"
}
我将此令牌发送到我的后端服务器并尝试按如下方式向 GCAL api 发出请求
$token = $request->getParam('token');
$client = new Google_Client();
$client->setApplicationName('Web');
$client->setScopes([Google_Service_Calendar::CALENDAR]);
$client->setAuthConfigFile(ROOT_DIR . '/client_secret.json');
$client->setAccessType('offline');
$client->setAccessToken(json_encode($token));
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
它返回错误,说明令牌已过期。我检查了谷歌代码,发现它返回这个错误的原因是因为这些行
public function isAccessTokenExpired()
{
if (!$this->token || !isset($this->token['created'])) {
return true;
}
// If the token is set to expire in the next 30 seconds.
$expired = ($this->token['created']
+ ($this->token['expires_in'] - 30)) < time();
return $expired;
}
如您所见,来自前端的令牌既没有 created 字段,也没有 refresh_token 字段。
【问题讨论】:
-
很乐意提供帮助,但您的问题非常广泛。请贴出你写的代码,得到的结果,想要得到的结果。然后我们可以找出问题所在。
标签: javascript google-calendar-api slim vue.js slim-3