【问题标题】:How to set up Google Calendar API using Ruby client for server to server applications如何使用 Ruby 客户端为服务器到服务器应用程序设置 Google Calendar API
【发布时间】:2016-11-21 14:37:21
【问题描述】:
我花了一些时间在几个位置阅读,以及查看 Stack Overflow 以了解如何在服务器到服务器应用程序中使用 Google API Ruby 客户端和 Google 日历,而无需让服务器客户端完全访问所有用户。我只是希望它能够为单个日历获取/创建/更新/删除事件。可能还有其他方法可以做到这一点,但我在下面记录了我是如何做到的,因为它可能会帮助其他人。
【问题讨论】:
标签:
ruby-on-rails
ruby
google-calendar-api
google-api-client
google-api-ruby-client
【解决方案1】:
谷歌日历的授权设置
有点帮助的链接: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 日历 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) 进行调用,而不是在此文件中创建方法。