rails google-api-client contact api - ruby-on-rails

I want to get access to a user's contact list with the google contacts API.
I've managed to get the token and refresh token and I'm now trying to use then on my rails server.
The google-api-client gem seems to be the way to go but I could not find which discovered_api to use. Greg Baugues provides a great tuto to get the gmail API working. The general request seems to look like
client = Google::APIClient.new
client.authorization.access_token = user_token
service = client.discovered_api('gmail')
result = client.execute(
:api_method => service.users.labels.list,
:parameters => {'userId' => 'me'},
:headers => {'Content-Type' => 'application/json'})
pp JSON.parse(result.body)
But I could not find how to query it for contacts. Running
client.discovered_apis.each do |gapi|
puts "#{gapi.title} \t #{gapi.id} \t #{gapi.preferred} \n"
end
(from here) shows now API related to contacts and I'm wondering if this is implemented in the alpha version of the gem...

As mentioned by #abraham, the Google contact API is not supported by the discovery API. Here is how I did it in ruby from the access token using the gems google_contacts_api and oauth2 (thanks to Rael Gugelmin Cunha for pointing them to me):
client = OAuth2::Client.new(client_id, client_secret, site: url)
token = OAuth2::AccessToken.new(client, access_token)
google_contacts_user = GoogleContactsApi::User.new(token)
contacts = google_contacts_user.contacts
There might be some more elegant way to do it but this works :)

The Google Contacts API is on Google's older GData API standard and is not supported by the discovery API. There is a pretty extensive guide for plain Ruby and a helper gem. Retrieving all contacts doesn't provide a Ruby sample but the Python sample should translate pretty easily.
def PrintAllContacts(gd_client):
feed = gd_client.GetContacts()
for i, entry in enumerate(feed.entry):
print '\n%s %s' % (i+1, entry.name.full_name.text)
if entry.content:
print ' %s' % (entry.content.text)
# Display the primary email address for the contact.
for email in entry.email:
if email.primary and email.primary == 'true':
print ' %s' % (email.address)

Related

Sign in users with Google Auth Library for Ruby

I want to sign in users with the google-auth-library-ruby
gem.
In their guides "Google Sign-In for server-side apps " they have a good code example how to exchange the authorization code for an ID token, but it's only for Python (and Java):
credentials = client.credentials_from_clientsecrets_and_code(
CLIENT_SECRET_FILE,
['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
auth_code)
Does anybody know about the equivalent for Ruby?
PS. I'm familiar with the omniauth gem, but would like to use the google-auth-library-ruby gem if possible.
After some research, I found this collection of samples, where the googleauth gem is used. Here you have it:
client_id = Google::Auth::ClientId.new("your Google client ID", "your Google secret")
scope = ["email","profile"]
token_store = nil # there are actually already implemented File or Redis token stores
callback_url = "http://localhost:8000"
authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store, callback_url)
credentials = authorizer.get_credentials_from_code(code: "the auth code in the Sign In response")

How does Rails Geocoder Gem access Google API?

I know that we need to use a unique API key to access the Google Geocoding API.I am using the Rails Geocoder Gem in my application and found out that it uses the Google Geocoding API.I was unable to find any configuration files that define the API keys to access the Google API.How does the Geocoder gem access the Google API's.
Geocoder.configure(
:lookup => :google_premier,
:api_key => [ 'GOOGLE_CRYPTO_KEY', 'GOOGLE_CLIENT_ID', 'GOOGLE_CHANNEL' ],
:timeout => 5,
:units => :km,
)
https://github.com/alexreisner/geocoder
Here is one more link : http://hankstoever.com/posts/11-Pro-Tips-for-Using-Geocoder-with-Rails
under
Some common configuration options are:
You should look into this answer : Does Geocoder gem work with google API key?
It says:
Geocoder supports Google api keys for Google Premier accounts only.
But you can use the Client-Side framework to do that, instead of putting it on the server
https://developers.google.com/maps/articles/geocodestrat
I wrote something like that a few days back in ruby, if it helps :
require 'net/http'
require "resolv-replace.rb"
require 'json'
url = URI("https://maps.googleapis.com/maps/api/geocode/json")
puts "enter country code"
c_code = gets
puts "enter zip code "
zip = gets
url.query= URI.encode_www_form({ address: "#{c_code.chomp}+#{zip.chomp}" })
res = Net::HTTP::get_response(url)
json_data = res.body if res.is_a?(Net::HTTPSuccess)
data = JSON.parse(json_data)
p data

Cannot get oAuth2 Access Token for Google Analytics API

I am using Rails + Garb Gem (Sija Branch) + omniauth-google-oauth2 Gem and I can successfully authenticate with the Google Analytics API and extract data that our app is generating when using a user login, e.g.:
Garb::Session.login('USERNAME', '<PASSWORD>')
I can then use Garb to connect to the Analytics Profile I want and pull the data from it and display some charts on a webpage. This all works fine.
However, I want to use oAuth2 to authenticate with Analytics which is why I had to install the Sija branch of the Garb Gem from Github (it supports oAuth2) and I also installed the omniauth-google-oauth2 Gem. Now in theory I should be able to authenticate using the following code:
Garb::Session.access_token = access_token # an instance of OAuth2::Client
It's at this point that it gets a little hazy for me and I would greatly appreciate some guidance. Here's how far I have gotten:
1) I created a Project in the Google API console and turned on Analytics API under Services
2) This provided me with a Client ID and Client Secret
3) I came across this code which I could populate with the ID and Secret above:
client = OAuth2::Client.new(
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
{
:site => 'https://accounts.google.com',
:authorize_url => '/o/oauth2/auth',
:token_url => '/o/oauth2/token'
})
4) Then there is the next bit of code:
response = OAuth2::AccessToken.new(
client,
STORED_TOKEN, {
refresh_token: STORED_REFRESH_TOKEN,
expires_at: STORED_EXPIRES_AT
})
5) and then in theory connect with:
Garb::Session.access_token = response
The problem I have is I don't have the token information in Point (4) above. It seems to me that with oAuth2 I need to do a "handshake" once and print out the return token values? Perhaps through Rails code which prints the values returned out and then paste the token values into a constant in the Rails app so that I can use them in the above code? I really am confused. As I mentioned earlier, the web app works fine using the user login authentication. All the web app is doing is authenticating with analytics, pulling down some data and drawing a chart. But I am stuck converting it over to oAuth2 as I just do not know how to get the Access Token that the Garb Gem is looking for. I should also note that this is not a public website with multiple users authenticating, this is a CMS website that is connecting to our own Analytics data.
I have seen some partial snippets of aspects of this but not a fully explained or working example. I would really appreciate any guidance and help with this question.
Many thanks in advance,
JR
I've soldiered through this over the last few weeks, so let me share what worked:
To use Oauth2 you need to get a 'refresh token' that you use to 're-authenticate' with google each time you make an API call. The steps for this are as follows:
1) Setup your account in the API console - https://code.google.com/apis/console/b/0/ (seems like you've done that well)
2) In your API account, make sure you have a redirect URI pointing back to your application:
http://some-url.com/auth/google_oauth2/callback
http://localhost:3000/auth/google_oauth2/callback
Note here that google won't let you call back to your local machine as 0.0.0.0:3000... so you'll need to use localhost explicitly
3) In your route file, tie that redirect url to an action in the controller where you're going to create the project or authentication
match '/auth/:provider/callback' => 'authentications#create'
The ':provider' simply lets you match on multiple types of oauth, but you could just put 'google_oauth2' there as well.
4) Now create that action in your controller
def create
auth = request.env["omniauth.auth"]
params = request.env["omniauth.params"]
project = Project.find(params['project_id'])
Authentication.create(:project_id => project.id, :provider => auth['provider'], :uid => auth['uid'], :access_token => auth['credentials']['refresh_token'])
flash[:notice] = "Authentication successful."
redirect_to owner_view_project_path(project)
end
5) The controller action should retrieve the relevant fields from the response object (details of response object here: https://github.com/zquestz/omniauth-google-oauth2) - in particular, you need to get the 'refresh_token' and save that to your project or authentication object - if you haven't added an 'access_token' attribute to the desired object, go do that now with a migration, then start saving the refresh token to that attribute
6) Now when you're ready to call that particular authentication and get API data for it, you can load up that object where you saved the access token, and use that to get a new session with the google API as follows:
#authentication = Authentications.find(params[:id])
client = OAuth2::Client.new GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET,
{
:site => 'https://accounts.google.com',
:authorize_url => "/o/oauth2/auth",
:token_url => "/o/oauth2/token",
}
response = OAuth2::AccessToken.from_hash(client, :refresh_token => #authentication.access_token).refresh!
Garb::Session.access_token = response
#profiles = Garb::Management::Profile.all
What this code did was create an OAuth2 access token (response) by specifying the client and then a refresh_token, then calling 'refresh!' to get a refreshed access token... then use that access token to establish your Garb session, then call down all the profiles for a given account using the Gard::Management::Profile.all
Hope this helps - let me know if you have questions!
Just a note on what worked for me in:
For steps 3, 4 & 5 I used cURL instead to retrieve the Access/Refresh token. Step 6 is then the same for me (using the Sija branch of the Garb Gem). So using cURL:
Using the details associated with your Google app POST the following using cURL:
curl --data "code=<APP_CODE>&redirect_uri=http://localhost:3000/oauth2callback&client_id=<CLIENT_ID>.apps.googleusercontent.com&scope=&client_secret=<CLIENT_SECRET>&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
The response takes the form:
{
"access_token" : "<ACCESS_TOKEN>",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "<REFRESH_TOKEN>"
}
which you can plug into the Garb Gem as per part 6.
The answer by #CamNorgate is valid.
If you don't have a "refresh_token" back from Omniauth on the callback make sure you are correctly initializing :google_oauth2
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"],
{ :scope=>"https://www.google.com/m8/feeds, https://www.googleapis.com/auth/userinfo.email, https://www.googleapis.com/auth/userinfo.profile",
:approval_prompt=>"force", access_type="offline"
}
end
Make sure to include :approval_prompt=>"force", access_type="offline" in order for the refresh_token to be sent back. The refresh_token is only provided on the first authorization from the user.

Trouble authenticating with Google Content API for Shopping

I'm trying to use OAuth2 for Server to Server Applications in conjunction with Google's Content API for Shopping using the google-api-client gem and Ruby on Rails 3.2.5. Also, I have already set up my merchant account as prescribed in the Content API documentation.
This was the best way I found to be able to:
create/update products in the background
have created products fall under my company's Google Products 'umbrella'
not require every user to authenticate/authorize when their token expires
Using lines 1 - 23 from this sample as a starting point, I've begun to write the following module for use in background jobs:
require 'httparty'
require 'google/api_client'
module GoogleProducts
GOOGLE_CONFIG = YAML.load_file(File.join(Rails.root, "config", "google.yml"))[Rails.env]
CLIENT_ID = "XXXXXXXXXXXX#developer.gserviceaccount.com"
MERCHANT_ID = "XXXXXXX"
SCOPE = "https://www.googleapis.com/auth/structuredcontent"
KEY_FILE_PATH = File.join(Rails.root, "config", "my-privatekey.p12")
KEY_FILE_PASS = "XXXXXXXXXX"
def self.add_item(item_id)
self.fetch_token
xml = self.gen_item_xml(item_id)
headers = {"Content-type" => "application/atom+xml", "Content-Length" => xml.length.to_s}
url = "https://content.googleapis.com/content/v1/#{MERCHANT_ID}/items/products/generic?access_token=#{$gp_token}"
response = HTTParty.post(url, :body => xml, :headers => headers).parsed_response
end
def self.gen_item_xml(item_id)
#building product xml
end
private
def self.fetch_token
api_client = Google::APIClient.new(:authorization => :oauth2)
key = Google::APIClient::PKCS12.load_key(KEY_FILE_PATH, KEY_FILE_PASS)
asserter = Google::APIClient::JWTAsserter.new(CLIENT_ID, SCOPE, key)
begin
api_client.authorization = asserter.authorize
#todo - store in something other than a global
$gp_token = api_client.authorization.access_token
rescue Signet::AuthorizationError => e
puts e.message
ensure
return $gp_token
end
end
end
Everything seemingly works fine - the authentication, the handling of the auth token - until I attempt to actually add an item, which I get the following when I do:
<errors xmlns='http://schemas.google.com/g/2005'>
<error>
<domain>GData</domain>
<code>ServiceForbiddenException</code>
<internalReason>Could not find authenticated customer</internalReason>
</error>
</errors>
Any ideas?
After much anguish and mental toil, I've finally solved my issue!
Since I am using OAuth 2 Server to Server authentication the suggestion hjblok gave didn't apply (thanks for giving it a shot, though!).
I simply added the email address that was associated with my Service Account key from the Google API Console (e.g. XXXXXXXXXXXX#developer.gserviceaccount.com) to my Google Merchant account (Settings > Users on the merchant admin page), and it worked.
If there's any clarification needed, please feel free to comment!
The Google Content API documentation says you need to set it up in the Settings page of the Google Merchant Center:
https://developers.google.com/shopping-content/getting-started/usingapi-products
EDIT rewrote the answer after diving into the Google's API documentation
Did you already try to use Google's OAuth 2.0 playground? I was able to successfully access https://content.googleapis.com/content/v1/#{MERCHANT_ID}/items/products/generic.
In "Step 1" I've chosen the "Content API for Shopping" and then authorized the API with my account.
Then in "Step 2" I've "exchanged authorization code for tokens", which results in a "refresh token" and an "access token".
Then in "Step 3" I've invoked a GET request to https://content.googleapis.com/content/v1/1234567/items/products/generic. Because 1234567 is not a valid MERCHANT_ID it returns an Error. But the Error Messages contains a MERCHANT_ID which actually belongs to your account.
I repeated "Step 3" but now with the correct MERCHANT_ID. Which returns a HTTP/1.1 200 OK with the requested items in the body.
Furthermore I'm not sure, but doesn't Google API expect an Authorization header to be present with the access_token ($gp_token)? Within the OAuth 2.0 playground this Authorization header is used to sent the access_token.
I also found the Structured Content API demo page (https://google-content-api-tools.appspot.com/demo/demo.html), which is more specific to the Content API for Shopping.

Ruby example to access google shopping api using GAN publisher id

I was wondering if anyone could provide an example of how to pull products from the Google Shopping API using a GAN publisher ID and ruby (google-api-ruby-client). I'm gathering you need to authenticate using oauth. The documentation is very sparse so any help would be much appreciated.
Basic usage of the shopping API with the client is easy.
require 'google/api_client'
client = Google::APIClient.new
client.authorization = nil
shopping = client.discovered_api("shopping", "v1")
result = client.execute(:api_method => shopping.products.list,
:parameters => { "source" => "public" })
To query by GAN publisher ID, you need to be authenticated as you're aware. You can use OAuth 2 for that. You can see a sample of that for the ruby client at http://code.google.com/p/google-api-ruby-client/wiki/OAuth2. The scope to use for shopping is:
https://www.googleapis.com/auth/shoppingapi
You can use the APIs explorer to try this out pretty quickly:
http://code.google.com/apis/explorer/#_s=shopping&_v=v1&_m=products.list
With version 0.9.11 is even easier
require 'google/apis/content_v2'
def list_products
content_for_shopping = Google::Apis::ContentV2::ShoppingContentService.new
content_for_shopping.authorization = get_authorization(%w(https://www.googleapis.com/auth/content))
content_for_shopping.authorization.fetch_access_token!
content_for_shopping.list_products(ENV['GOOGLE_MERCHANT_CENTER_ID'])
end
def get_authorization(scopes)
cert_path = Gem.loaded_specs['google-api-client'].full_gem_path + '/lib/cacerts.pem'
ENV['SSL_CERT_FILE'] = cert_path
authorization = Google::Auth.get_application_default(scopes)
# Clone and set the subject
auth_client = authorization.dup
return auth_client
end

Resources