以下是我用来允许用户允许用户授权我的应用通过 OAuth 访问他们的 Google 日历的代码。我基于此示例代码。
它在大多数情况下都可以工作,但有时,控制器中的操作会出现ArgumentError: Missing authorization code
错误。如果我注释掉该行,则所有属性都是.client.authorization.fetch_access_token!
create_google_calendar
services
client.authorization
null
我正在使用 Rails 3.2.0 和 Ruby 1.9.2。
这是什么原因造成的?
宝石文件
gem 'google-api-client', :require => 'google/api_client'
服务.rb
def self.google_calendar_client google_calendar_service=nil
client = Google::APIClient.new
client.authorization.client_id = xxx
client.authorization.client_secret = xxx
client.authorization.scope = 'https://www.googleapis.com/auth/calendar'
url_prefix = Rails.env.production? ? xxx : 'http://localhost:3000'
client.authorization.redirect_uri = "#{url_prefix}/create_google_calendar"
if google_calendar_service.present?
client.authorization.update_token! :access_token => google_calendar_service.token, :refresh_token => google_calendar_service.google_calendar_refresh_token, :expires_in => google_calendar_service.google_calendar_expires_in, :issued_at => Time.at(google_calendar_service.google_calendar_issued_at)
client.authorization.fetch_access_token! if client.authorization.expired?
end
client
end
services_controller.rb
def connect_google_calendar
@google_calendar_url = Service.google_calendar_client.authorization.authorization_uri.to_s
end
def create_google_calendar
client = Service.google_calendar_client
client.authorization.code = params[:code]
client.authorization.fetch_access_token!
current_user.services.create :provider => 'google_calendar', :token => client.authorization.access_token, :google_calendar_refresh_token => client.authorization.refresh_token, :google_calendar_expires_in => client.authorization.expires_in, :google_calendar_issued_at => client.authorization.issued_at
end