首页 > 解决方案 > Google Calendar API - 持续同步

问题描述

我知道如何与 Google Calendar API 同步。我们正在尝试构建一个系统,在该系统中持续同步 Google 日历,而无需请求同意屏幕。我确实搜索了很多,但似乎他们发送了 nextsynctoken 以获取完整的事件列表。但如果我想在 2 周后重新开始同步。我该怎么做?不向用户询问身份验证窗口或同意屏幕?

如果可能,请告诉我。

提前谢谢你萨拉瓦纳

标签: google-calendar-api

解决方案


您向 Google Calendar API 发出的所有请求都必须由经过身份验证的用户授权。

但是,既然您遇到了对我来说似乎令牌过期的问题,为什么不尝试刷新您正在使用的访问令牌呢?

根据Using OAuth 2.0 to Access Google APIs文档

访问令牌的生命周期有限。如果您的应用程序需要在单个访问令牌的生命周期之外访问 Google API,它可以获得刷新令牌。刷新令牌允许您的应用程序获取新的访问令牌。

是服务器和客户端之间交换的nextSyncToken一段数据,用于同步过程。

您可以继续使用,nextSyncToken但您必须使用刷新令牌才能避免每次都使用同意屏幕。

以下是使用 Python为 Web 服务器应用程序使用 OAuth 2.0交换授权代码以获取刷新和访问令牌的示例代码:

state = flask.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=['https://www.googleapis.com/auth/youtube.force-ssl'],
    state=state)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)

# Store the credentials in the session.
# ACTION ITEM for developers:
#     Store user's access and refresh tokens in your data store if
#     incorporating this code into your real app.
credentials = flow.credentials
flask.session['credentials'] = {
    'token': credentials.token,
    'refresh_token': credentials.refresh_token,
    'token_uri': credentials.token_uri,
    'client_id': credentials.client_id,
    'client_secret': credentials.client_secret,
    'scopes': credentials.scopes}

我建议您检查以下链接,因为它们可以提供有关您的问题的更多信息:

  1. 使用 OAuth 2.0 访问 Google API

  2. 授权对 Google Calendar API 的请求

  3. 高效同步资源

对于用于刷新令牌的其他编程语言,您可以检查:

  1. 将 OAuth 2.0 用于 Web 服务器应用程序

推荐阅读