With Google API Client, how to create client

前端 未结 3 1460
长发绾君心
长发绾君心 2021-02-19 11:35

I\'m working to use the Google API Client: https://github.com/google/google-api-ruby-client

Specifically, I want to access Google Contacts via the Google API client usin

3条回答
  •  无人共我
    2021-02-19 12:25

    You're getting that error because you're using passing the wrong objects to
    ContactList::GoogleContactsApi.new(client, auth). That gist expects for client to be an instance of the dead Hurley HTTP client and auth to be an OAuth2 instance from Google's Signet library. Instead you're trying to Intridea's OAuth2 libary.

    Since Hurley is a dead project, and that gist lacks any unit tests, I'd recommend you use a tested and working implementation such as the google_contacts_api gem which is compatible with Intridea's OAuth2 library:

    require 'google_contacts_api'
    
    auth = User.first.authentications.first
    client = OAuth2::Client.new('x', 'x', :site => 'https://accounts.google.com')
    oauth2_object = OAuth2::AccessToken.new(client, auth.token)
    google_contacts_user = GoogleContactsApi::User.new(oauth2_object)
    

    The issue of refreshing tokens really belongs in a separate question. In short, you'll have to make a request for a new token periodically using the refresh token Google provides:

    data = {
      :client_id => GOOGLE_APP_KEY,
      :client_secret => GOOGLE_APP_SECRET,
      :refresh_token => oauth2_refresh_token_for_user,
      :grant_type => "refresh_token"
    }
    response = ActiveSupport::JSON.decode(RestClient.post("https://accounts.google.com/o/oauth2/token"), data)
    if response["access_token"].present?
      puts response["access_token"]
    else
      # No Token
    end
    rescue RestClient::BadRequest => e
      # Bad request
    rescue
      # Something else bad happened
    end
    

提交回复
热议问题