我正在使用具有PHP后端服务器(苗条框架 3)的vue.js构建SPA 。这是两个独立的项目,放在两个不同的服务器上,后端根本没有前端。
SPA (vue.js) 通过 ajax 向后端发出请求。
现在我想实现Google Calendar API来在每次用户创建待办事项时创建日历和事件。为此,我需要服务器到服务器访问 Google Calendar API(即使用户未登录,我也可能需要更改 GCAL 上的事件)。
我想了解的是,如何使用 vue.js 使用 Google JS 库获取访问令牌(和刷新令牌)并将其保存在数据库中,以便我的后端可以使用它向 GCAL Api 发出离线请求。
当我使用 JS 库使用 Oauth v.2 时,我得到的只是 access_token,它不能用于服务器到服务器的通信。
[更新]
好的,更多信息。我正在遵循谷歌的指南,我的前端现在看起来像这样 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
字段。