How do I authorize a service account for Google Calendar API in Ruby?

雨燕双飞 提交于 2019-12-02 08:28:55

OK I found a way.

https://developers.google.com/api-client-library/ruby/auth/service-accounts

require 'google/apis/calendar_v3'
require 'googleauth'

# Get the environment configured authorization
scopes =  ['https://www.googleapis.com/auth/calendar']
authorization = Google::Auth.get_application_default(scopes)

# Clone and set the subject
auth_client = authorization.dup
auth_client.sub = 'myemail@mydomain.com'
auth_client.fetch_access_token!

# Initialize the API
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = auth_client

# Fetch the next 10 events for the user
calendar_id = 'primary'
response = service.list_events(calendar_id,
                               max_results: 10,
                               single_events: true,
                               order_by: 'startTime',
                               time_min: Time.now.iso8601)
puts 'Upcoming events:'
puts 'No upcoming events found' if response.items.empty?
response.items.each do |event|
  start = event.start.date || event.start.date_time
  puts "- #{event.summary} (#{start})"
end

And

>set GOOGLE_APPLICATION_CREDENTIALS=client_secrets.json

C:\Users\Chloe\workspace>ruby quickstart.rb
Upcoming events:
- Test (2018-05-17)
- SSL Certificate for CMS (2019-02-13)

But I wonder where it saves the refresh token and access token? All I have to do now is make it work for ephemeral file systems like Heroku and store the tokens in the database.

For anyone still looking this is what worked for me:

require 'google/apis/calendar_v3'
require 'googleauth'

scope = 'https://www.googleapis.com/auth/calendar'

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('/path/to/creds.json'),
  scope: scope)

authorizer.fetch_access_token!

service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = authorizer

calendar_id = 'primary'
response = service.list_events(calendar_id,
                               max_results: 10,
                               single_events: true,
                               order_by: 'startTime',
                               time_min: Time.now.iso8601)
puts 'Upcoming events:'
puts 'No upcoming events found' if response.items.empty?
response.items.each do |event|
  start = event.start.date || event.start.date_time
  puts "- #{event.summary} (#{start})"
end

The trick was finding the docs for the google-auth-library-ruby https://github.com/googleapis/google-auth-library-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!