我花了一些时间在几个地方阅读,以及查看Stack Overflow以了解如何在服务器到服务器应用程序中使用Google API Ruby客户端和Google日历,而无需让服务器客户端完全访问所有服务器用户。我只是希望它能够获取/创建/更新/删除单个日历的事件。可能还有其他方法可以做到这一点,但我会在下面记录我是如何做到这一点的,因为它可能会帮助其他人。
答案 0 :(得分:1)
一些有用的链接:https://developers.google.com/api-client-library/ruby/
JSON文件将下载到您的计算机。 将此文件移至应用程序可访问的某个位置,并将其重命名为" google_api.json" (或任何你想要的东西,只要它匹配下面的正确路径)。确保只有应用程序可以访问此文件(它包含私钥)。
以下是授权和访问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)
拨打电话,而不是在此文件中创建方法。