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

后端 未结 2 2118
我在风中等你
我在风中等你 2021-01-28 13:37

How do I authorize a service account for Google Calendar API in Ruby? I tried the quick start guide, but it crashed.

https://developers.google.com/calendar/quickstart/ru

2条回答
  •  萌比男神i
    2021-01-28 14:34

    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

提交回复
热议问题