我花了一些时间阅读了几个地方,并查看了 Stack Overflow 以弄清楚如何在服务器到服务器应用程序中将 Google API Ruby 客户端与 Google Calendar 一起使用,而不让服务器客户端完全访问所有用户。我只是希望它能够获取/创建/更新/删除单个日历的事件。可能还有其他方法可以做到这一点,但我在下面记录了我是如何做到的,因为它可能会帮助其他人。
最佳答案
谷歌日历的授权设置
有点帮助的链接:https://developers.google.com/api-client-library/ruby/
- 转到:https://console.developers.google.com/iam-admin/projects
- 点击“+创建项目”
- 输入“项目名称”和“项目 ID”,然后点击“创建”
- 在“库”下选择“日历 API”
- 点击“>启用”
- 返回:https://console.developers.google.com/iam-admin/projects
- 点击“服务帐户”
- 点击“选择项目”
- 选择您的项目并点击“打开”
- 点击“+创建服务帐户”
- 输入“服务帐户名称”并选择“角色”(我选择“编辑”)
- 选中“提供新的私钥”
- 点击“创建”
JSON 文件将下载到您的计算机。 将此文件移动到您的应用程序可以访问的某个位置,并将其重命名为“google_api.json”(或者您想要的任何名称,只要它与下面的正确路径匹配即可)。确保只有应用程序可以访问此文件(它包含一个私钥)。
- 从 JSON 文件中复制“client_email”并转到 您希望此应用程序访问的 Google 日历。
- 点击“日历”
- 选择正确的日历
- 点击“日历地址”下的“更改共享设置”:
- 添加您复制的电子邮件并选择适当的权限
- 点击“保存”
- 复制“日历地址”右侧的“日历 ID”:
- 您可以对下面的日历 ID 进行硬编码,或者将其放入 YAML 文件或作为环境变量。
这是授权和访问 Googe Calendar API 的示例文件:
# http://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/CalendarV3
require 'googleauth'
require 'google/apis/calendar_v3'
class MyApp::GoogleCalendar
def initialize
authorize
end
def service
@service
end
def events(reload=false)
# NOTE: This is just for demonstration purposes and not complete.
# If you have more than 2500 results, you'll need to get more than
# one set of results.
@events = nil if reload
@events ||= service.list_events(calendar_id, max_results: 2500).items
end
private
def calendar_id
@calendar_id ||= # The calendar ID you copied in step 20 above (or some reference to it).
end
def authorize
calendar = Google::Apis::CalendarV3::CalendarService.new
calendar.client_options.application_name = 'App Name' # This is optional
calendar.client_options.application_version = 'App Version' # This is optional
# An alternative to the following line is to set the ENV variable directly
# in the environment or use a gem that turns a YAML file into ENV variables
ENV['GOOGLE_APPLICATION_CREDENTIALS'] = "/path/to/your/google_api.json"
scopes = [Google::Apis::CalendarV3::AUTH_CALENDAR]
calendar.authorization = Google::Auth.get_application_default(scopes)
@service = calendar
end
end
现在您可以调用 cal = MyApp::GoogleCalendar.new
并使用 cal.events
获取事件。或者您可以直接使用 cal.service.some_method(some_args)
进行调用,而不是在此文件中创建方法。
关于ruby-on-rails - 如何使用 Ruby 客户端为服务器到服务器应用程序设置 Google Calendar API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40722687/