i am using google api for ruby, but not know how to start, just give me an ABC example someone, thanks very much?
If you are creating a Service Account application to access Google Analytics.
Register it with Google through https://code.google.com/apis/console.
On API Access tab, click Create client ID, choose Service Account. Store the key file Google will generate, and remember the password for that key.
Here is some code to get you started
require 'rubygems'
require 'google/api_client'
api_client = Google::APIClient.new
path_to_key_file ="/path/to/key/file-privatekey.p12"
passphrase = "google_generated_password"
key = Google::APIClient::PKCS12.load_key(path_to_key_file, passphrase)
Once a key is available, initialize the asserter with your client ID (email in APIs console)
and authorization scopes.
asserter = Google::APIClient::JWTAsserter.new(
'super_long_client_id_from_api_console#developer.gserviceaccount.com',
'https://www.googleapis.com/auth/analytics.readonly',
key)
# To request an access token, call authorize:
api_client.authorization = asserter.authorize()
puts api_client.authorization.access_token
http://code.google.com/p/google-api-ruby-client/wiki/ServiceAccounts
I've answered something similar in a couple of other posts I found that were like this one... so incase its relevant, for ruby, using the google-api-client (for any of the google apis), there's a few ins and outs with authentication when using an api key as opposed to OAuth...
I've outlined this process (using an api key server side) at the code abode.
You have to explicitly set the authorzation param to nil when constructing the client, otherwise the gem tries to use OAuth to authenticate, so if calling from a server using an api key only, you will always get a 401 Unauthorized.
the code abode - google-api-client for ruby
Related
I'm trying to develop a ruby script to query the Google Adwords API using service account credentials. I know that the json credentials file works in another script which isn't ruby but I can't get past authorization in this ruby script. I can't find any examples using this pattern. I don't want to use OAuth2. I know this script is not well developed but I'm just trying to get the basics. What am I doing wrong here?
My company has a G Suite account and I have full administrator permissions.
Here is my code:
#!/usr/bin/ruby
require 'googleauth'
require 'fileutils'
require 'adwords_api'
API_VERSION = :v201809
scopes = ["https://www.googleapis.com/auth/adwords"]
credential_file = File.open('credentials/adwords-production.json')
prn = "adwords#mycompany.com"
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: credential_file, scope: scopes, prn: prn)
def get_report_fields(report_type)
adwords = AdwordsApi::Api.new
report_def_srv = adwords.service(:ReportDefinitionService, API_VERSION)
# Get report fields.
fields = report_def_srv.get_report_fields(report_type)
if fields
puts "Report type '%s' contains the following fields:" % report_type
fields.each do |field|
puts ' - %s (%s)' % [field[:field_name], field[:field_type]]
puts ' := [%s]' % field[:enum_values].join(', ') if field[:enum_values]
end
end
end
begin
report_type = 'ACCOUNT_PERFORMANCE_REPORT'
get_report_fields(report_type)
end
From Google's docs here:
All AdWords API calls must be authorized through OAuth2. OAuth2 enables your AdWords API client app to access a user's Google Ads account without having to handle or store the user's login info.
It appears you have to use OAuth2 Authentication.
Further reading here confirms this:
Your app will need to access user data and contact other Google services on your behalf. Authentication via OAuth2 allows your app to operate on behalf of your account.
To enable your app to access the API, you need an OAuth2 client ID and client secret.
You say you have done this somewhere else where you were able to use a JSON file, so I looked into the source a little.
The source for the Ruby API is here and here. It appears there really is no other way to manage credentials, at least in the Ruby API. Looking here:
# Retrieve correct soap_header_handler.
#
# Args:
# - auth_handler: instance of an AdsCommon::Auth::BaseHandler subclass to
# handle authentication
# - version: intended API version
# - header_ns: header namespace
# - default_ns: default namespace
#
# Returns:
# - SOAP header handler
#
def soap_header_handler(auth_handler, version, header_ns, default_ns)
auth_method = #config.read('authentication.method', :OAUTH2)
handler_class = case auth_method
when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT
AdsCommon::SavonHeaders::OAuthHeaderHandler
else
raise AdsCommon::Errors::AuthError,
"Unknown auth method: %s" % auth_method
end
return handler_class.new(#credential_handler, auth_handler, header_ns,
default_ns, version)
end
Notice that unless OAuth is used, it throws an error. There really is no other way to authenticate. Even if you managed to authenticate another way and try passing it to the credential manager, it will reject it.
Short answer: This is not possible in the Ruby API without hacking it some way.
Hey guys I have an error when getting some tokens from google. Do you have any ideas about this error? And let me know how I can solve this error.
[{"domain"=>"usageLimits", "reason"=>"dailyLimitExceededUnreg", "message"=>"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "extendedHelp"=>"https://code.google.com/apis/console"}], "code"=>403, "message"=>"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."}}
My fetching code:
def self.request_tokens(code)
Request.post('https://www.googleapis.com/oauth2/v4/token', {
client_id: 'XXXXXXXXXXXXXX',
client_secret: 'XXXXXXXXXXXXXX',
redirect_uri: 'http://localhost:8080',
grant_type: 'authorization_code',
code: code,
})
end
def self.request_profile(access_token)
Request.get("https://www.googleapis.com/plus/v1/people/me?access_token=#{access_token}")[:body]
end
Add:
I have already added API key like this.
def self.request_profile(access_token)
# Add api key but failed
Request.get("https://www.googleapis.com/plus/v1/people/me?access_token=#{access_token}?key=XXXXXXXXXXXXX")[:body]
# try like this but failed
plus = Google::Apis::PlusV1::PlusService.new
plus.key = 'XXXXXXXXXXXXX'
plus.authorization = access_token
end
It means exactly what it says. You're overusing Google's API, so they're not letting you use it for the rest of the day unless you sign up for an API key. https://code.google.com/apis/console, the link in your error, will let you do that.
"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
Means that you are trying to access a Google api without being authenticated or using an api key (using a valid client). In order to access all google apis you must have created a project on Google developer console. If you are accessing public data you can use an api key if you are accessing private user data you will need to use Oauth2.
You appear to have tried to set the client id in your code. The issue is that its not being applied properly to your request. I am not a ruby dev so can not assist you in debugging your code how ever google has a number of ruby tutorials OAuth 2.0
as well as use api key
require 'google/apis/plus_v1'
plus = Google::Apis::PlusV1::PlusService.new
plus.key = 'api_key'
The Stripe API reference says this about authentication:
The example they give is this:
require "stripe"
Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"
The sk_test_BQokikJOvBiI2HlWgH4olfQ2 secret key is found in the account settings on Stripe's webpage. I understand this is the secret api key for my application to talk with Stripe.
But then I read this documentation on getting started with Stripe Connect:
When using our official API libraries, we recommend that you pass in the
access_token with every request, instead of setting the API key globally.
This is because the access_token used in any API request depends on the user
you're charging on behalf of.
The example they give is:
# Not recommended: setting global API key state
Stripe.api_key = ACCESS_TOKEN
Stripe::Customer.create(
:description => "example#stripe.com"
)
# Recommended: sending API key with every request
Stripe::Customer.create(
{:description => "example#stripe.com"},
ACCESS_TOKEN # user's access token from the Stripe Connect flow
)
Here, the access token is returned to the application after a user has connected to the application through Stripe Connect. The access token can be used to perform actions on behalf of that user, like charging their card.
So, they pass the API key with every request, but why would the user's access token be an api key? I thought from the first documentation that the api key is supposed to be my application's secret api key? Instead, they are setting the user's access token. How will Stripe identify my application then if I'm setting the user's access token and not my own secret key?
Then, I read their example on integrating Stripe Checkout with Sinatra. The code sample they give is:
require 'sinatra'
require 'stripe'
set :publishable_key, ENV['PUBLISHABLE_KEY']
set :secret_key, ENV['SECRET_KEY']
Stripe.api_key = settings.secret_key
....
get '/' do
erb :index
end
post '/charge' do
# Amount in cents
#amount = 500
customer = Stripe::Customer.create(
:email => 'customer#example.com',
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:amount => #amount,
:description => 'Sinatra Charge',
:currency => 'usd',
:customer => customer.id
)
erb :charge
end
So in this instance, they set the API Key to be the application's secret key. They don't pass any Access Token in the request either. So I'm a bit confused why an Access Token would be set as a secret API Key in the previous doc or why I should pass it with each request, when all their example docs don't even do that.
To understand this, you should know first that the Stripe API can be used to build applications that serve two kinds of audiences:
to accept payments from end-users as a merchant (normal use-case) and
to provide add-on services to merchants having their own Stripe
accounts (eg. one service helps me configure the emails to be sent out on different Stripe events)
Hence, all the API endpoints can be authorized in two ways:
the API key way which you can directly get from your Account Settings. This identifies your Stripe account
the access token way through Stripe Connect. This identifies the Stripe account of the connected merchant.
What the Stripe Connect docs is telling you is that suppose you are building an application that serves use-case #2 above, then you must remember to authorize each of your API calls with the right access token and not have a global API key (which, by the way, is fully acceptable for use case #1) as you might be making changes incorrectly to the wrong account(s).
So, if use case #1 is what you want to do, you don't have to worry about Stripe Connect at all.
I'm trying the following sample code, and failing (the uid and password I'm using are valid). Is there something I'm missing, or a simpler example I can try?
testing.rb:
require('rubygems')
gem('twitter4r','>=0.2.0')
require('twitter')
client = Twitter::Client.new(:login => 'uid', :password => 'password')
ARGV.each do |a|
#message = "#{a}"
end
status = client.status(:post, #message)
prompt> ruby testing.rb "test"
/Library/Ruby/Gems/1.8/gems/twitter4r-0.6.0/lib/twitter/client/base.rb:120:in
`raise_rest_error': Unauthorized
(Twitter::UnauthorizedError) from
/Library/Ruby/Gems/1.8/gems/twitter4r-0.6.0/lib/twitter/client/base.rb:125:in
`handle_rest_response' from
/Library/Ruby/Gems/1.8/gems/twitter4r-0.6.0/lib/twitter/client/base.rb:23:in `rest_oauth_connect' from
/Library/Ruby/Gems/1.8/gems/twitter4r-0.6.0/lib/twitter/client/status.rb:42:in `status' from testing.rb:11
#blueberryfields you will need to use the OAuth API that Twitter4R v0.5.0+ supports. This is due to Twitter.com mandating OAuth authentication as of August 2010. Supplying the login and password of your username is no longer supported either via Twitter4R, twitter.com or any other Twitter API client.
There is a fantastic tutorial on using OAuth with Twitter4R at this blog:
http://blog.monnet-usa.com/?p=342
HTH,
#SusanPotter -- Author of Twitter4R
PS Also check out #t4ruby for updates to Twitter4R
Twitter doesn't allow basic Auth (username+password) logins through their API anymore.
You should look for a method that supports OAuth-based login.
You'll need to fetch OAuth keys for your application, which can be done from the following links. The first link allows you to enroll a new application, the second one allows you to see what applications you've registered.
New Twitter Application # dev.twitter.com
Twitter Applications (Existing) # dev.twitter.com
A more in-depth guide is available at the following link. You will want to read this as OAuth requires at least two steps to authenticate before you can use the twitter API.
Authenticating Requests with OAuth
I want to write a ruby app for personal use that access my personal dropbox through their API.
I'm using Tim Morgan gem 'dropbox' version 1.1.1
What I don't understand is the difference between a developer_key and a consumer_key. The gem docs say that I have to use the consumer_key, but when I registered my app on dropbox.com I received only a developer key secret pair (and that's what I put in Dropbox::Session.new)
Anyway the error I get from ruby at every API call is:
Dropbox::UnsuccessfulResponseError: HTTP status Net::HTTPBadRequest
any idea??
You have to redirect your user to the oauth page where he will grant you the authorization to access the datas. This can be done wit something like that:
dropbox_session = Dropbox::Session.new('bla', 'blabla')
redirect_to dropbox_session.authorize_url(:oauth_callback => root_url)