quickbooks integration in rails application (parameter rejected OAuth) - ruby-on-rails

I am creating a rails application to post invoices to quickbooks I am using this gem quickbooks-ruby every time when I try to authenticate with quickbooks It gives this error OAuth::Problem parameter_rejected below is my code.
quickbook.rb (initialiser)
::QB_OAUTH_CONSUMER = OAuth::Consumer.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, {
:site => "https://oauth.intuit.com",
:request_token_path => "/oauth/v1/get_request_token",
:authorize_url => "https://appcenter.intuit.com/Connect/Begin",
:access_token_path => "/oauth/v1/get_access_token"
})
Authenticate method in controller
def authenticate_quickbooks
callback = api_webhooks_quickbook_oauth_callback_path
token = QB_OAUTH_CONSUMER.get_request_token(:oauth_callback => callback)
session[:qb_request_token] = token
redirect_to("https://appcenter.intuit.com/Connect/Begin?oauth_token=#{token.token}") and return
end
callback
def quickbooks_oauth_callback
at = session[:qb_request_token].get_access_token(:oauth_verifier => params[:oauth_verifier])
token = at.token
secret = at.secret
realm_id = params['realmId']
end

Problem solved. My quickbooks app was using oAuth2 and the gem has different method of authentication for oAuth1 and oAuth2.
below is the code (for OAuth2):
quickbook.rb (initialiser)
oauth_params = {
:site => "https://appcenter.intuit.com/connect/oauth2",
:authorize_url => "https://appcenter.intuit.com/connect/oauth2",
:token_url => "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"
}
::QB_OAUTH2_CONSUMER = OAuth2::Client.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, oauth_params)
Quickbooks.sandbox_mode = true
Authenticate method in controller
redirect_uri = "http://localhost:3000#{quickbooks_authenticate_callback_path}"
grant_url = ::QB_OAUTH2_CONSUMER.auth_code.authorize_url(:redirect_uri => redirect_uri, :response_type => "code", :state => SecureRandom.hex(12), :scope => "com.intuit.quickbooks.accounting")
redirect_to grant_url
callback
redirect_uri = oauth_callback_quickbooks_url
if resp = ::QB_OAUTH2_CONSUMER.auth_code.get_token(params[:code], :redirect_uri => redirect_uri)
where oauth_callback_quickbooks_url = application callback which is also defined in quickbooks app
please note that you also have to include oauth2 gem

Related

How to Authenticate Google youtube api with ruby, Signet , google api gem?

ERROR: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
My code :
#client = Signet::OAuth2::Client.new(
:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:token_credential_uri => 'https://oauth2.googleapis.com/token',
:client_id => ENV['GMB_CLIENT_ID'],
:client_secret => ENV['GMB_CLIENT_SECRET'],
:scope => 'https://www.googleapis.com/auth/youtube.upload',
:redirect_uri => 'https://localhost:4200/youtube'
)
# a = my user with token and refresh token got from signet oAuth with google
response = {
"access_token" => a.token,
"refresh_token" => a.refresh_token,
"expries_in" => total_second,
"scope" => "https://www.googleapis.com/auth/youtube.upload",
"token_type" => "Bearer"
}
#client.update!(response)
#service ||= Google::Apis::YoutubeV3::YouTubeService.new
#service.key = "my key"
#service.authorization = #client #setting the authorization for api
status = Google::Apis::YoutubeV3::VideoStatus.new(
privacy_status: 'unlisted',
)
snippet = Google::Apis::YoutubeV3::VideoSnippet.new(
title: "My video",
description: "description",
)
video_object = Google::Apis::YoutubeV3::Video.new(
status: status,
snippet: snippet,
)
#service.insert_video(
'id,snippet,status',
video_object,
notify_subscribers: true,
content_type: 'video/webm',
options: { authorization: #client }
)
Help needed to make it work. Authentication is not working

Yahoo OAuth 1.0 Callback Issue?

I want to use Yahoo Fantasy sport API in my web application, For that I am using OAuth for Yahoo login. I have consumer key and secret key and i passed the keys successfully, When I run the following code. It redirects to Yahoo login, It asks permission for accessing the user's credentials. If i give AGREE the page Redirects to https://api.login.yahoo.com/oauth/v2/request_auth and It shows the Verifying code. If i press the close button in verification code page, it's not callback to my URL.
#ts=Time.now.to_i
#callback_url = "http://localhost:3000/callback"
#nonce = SecureRandom.hex()
consumer = OAuth::Consumer.new("my consumerkey","secret key",
{ :site => 'https://api.login.yahoo.com',
:http_method => :post,
:scheme => :header,
:oauth_nonce => #nonce,
:request_token_path => '/oauth/v2/get_request_token',
:authorize_path => '/oauth/v2/request_auth',
:access_token_path => '/oauth/v2/get_token',
:oauth_callback => "http://localhost:3000/callback",
:oauth_timestamp => Time.now.to_i,
:oauth_signature_method => "HMAC-SHA-1",
:oauth_version => "1.0",
:oauth_callback_confirmed => true,
})
request_token = consumer.get_request_token
session[:request_token]=request_token
redirect_to request_token.authorize_url
access_token=request_token.get_access_token
access = ActiveSupport::JSON.decode(access_token.to_json)
if !(access.present?)
#response = "Response failed"
else
#response = access
end
Can you please tell me What changes to be made to get the callback for to get access_token.
I think you got confused while getting callback. change your code as follows, You will surely get access token to make Yahoo API call.
##access_token = nil
##request_token = nil
def get_request_token
##consumer = OAuth::Consumer.new('consumer key',
'secret key',
{
:site => 'https://api.login.yahoo.com',
:scheme => :query_string,
:http_method => :get,
:request_token_path => '/oauth/v2/get_request_token',
:access_token_path => '/oauth/v2/get_token',
:authorize_path => '/oauth/v2/request_auth'
})
##request_token = ##consumer.get_request_token( { :oauth_callback => 'http://localhost:3000/callback' } )
session[:request_token]=##request_token
redirect_to ##request_token.authorize_url
#redirect_to ##request_token.authorize_url( { :oauth_callback => 'http://localhost:3000/success' } )
end
def callback
request_token = ActiveSupport::JSON.decode(##request_token.to_json)
if !(request_token.present?)
$request_token_value = "Response failed"
else
$request_token_value = request_token
end
# access_token = ##request_token.get_access_token({:oauth_verifier=>params[:oauth_verifier],:oauth_token=>params[:oauth_token]})
##access_token = ##request_token.get_access_token(:oauth_verifier=>params[:oauth_verifier])
access_json = ActiveSupport::JSON.decode(##access_token.to_json)
puts "****************************"
puts $access_json
puts "****************************"
end

Twitter Access Token URL returns Invalid Request Token

In my controller I have the following actions
def twitter
client = TwitterOAuth::Client.new(
:consumer_key => ENV['TWITTER_KEY'],
:consumer_secret => ENV['TWITTER_SECRET']
)
request_token = client.request_token(oauth_callback: "http://myawesomeapp.herokuapp.com/create_users/get_twitter_info")
redirect_to "https://www.twitter.com/oauth/authenticate?oauth_token=#{request_token.params[:oauth_token]}"
end
def get_twitter_info
redirect_to "https://www.twitter.com/oauth/access_token?oauth_verifier=#{params[:oauth_verifier]}&oauth_token=#{params[:oauth_token]}"
end
def results
end
In my Twitter application settings, I've set Access to Read Only and checkmarked Allow this application to be used to Sign in with Twitter. Why is it returning
Invalid Request Token
when it hits the https://twitter.com/oauth/access_token page?
In Main function You write Simply this code
redirect_url = "http://myawesomeapp.herokuapp.com/create_users/get_twitter_info"
url = URI.parse(URI.encode(redirect_url.strip))
consumer_key=consumer key
consumer_secret=consumer secret
oauth = OAuth::Consumer.new(consumer_key, consumer_secret,
{ :site => "http://api.twitter.com" })
request_token = oauth.get_request_token(:oauth_callback => url)
session[:twitter_token] = request_token.token
session[:twitter_secret] = request_token.secret
and in
get_twitter_info
function you write
consumer_key=consumer key
consumer_secret=consumer secret
oauth = OAuth::Consumer.new(consumer_key,consumer_secret,
{ :site => "http://api.twitter.com" })
request_token = OAuth::RequestToken.new(oauth, session[:twitter_token], session[:twitter_secret])
#access_token = request_token.get_access_token(
:oauth_verifier => params[:oauth_verifier])
But Keep in mind in your twitter application setting you mention callback url is
http://myawesomeapp.herokuapp.com/create_users/get_twitter_info

Google Calendar Service Account API leads to invalid grant

I have took the sample code from
http://code.google.com/p/google-api-ruby-client/source/browse/service_account/analytics.rb?repo=samples
however, I have been trying to get it working but it just keeps on giving, no matter how hard I try ! Here is the error I keep on getting
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/signet-0.4.5/lib/signet/oauth_2/client.rb:875:in `fetch_access_token': Authorization failed. Server message: (Signet::Authorization
Error)
{
"error" : "invalid_grant"
}
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/signet-0.4.5/lib/signet/oauth_2/client.rb:888:in `fetch_access_token!'
How Do I solve this ?
Here is my complete code
require 'google/api_client'
require 'date'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
# Update these to match your own apps credentials
service_account_email = 'xxxxxx' # Email of service account
key_file = 'privatekey.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = 'xxxxx' # Analytics profile ID.
client = Google::APIClient.new()
# Load our credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => service_account_email,
:signing_key => key)
# Request a token for our service account
client.authorization.fetch_access_token!
analytics = client.discovered_api('analytics','v3')
startDate = DateTime.now.prev_month.strftime("%Y-%m-%d")
endDate = DateTime.now.strftime("%Y-%m-%d")
visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + profileID,
'start-date' => startDate,
'end-date' => endDate,
'dimensions' => "ga:day,ga:month",
'metrics' => "ga:visits",
'sort' => "ga:month,ga:day"
})
print visitCount.data.column_headers.map { |c|
c.name
}.join("\t")
visitCount.data.rows.each do |r|
print r.join("\t"), "\n"
end
I have spent whole day to get this working. Please help. Thanks for your time.
Solved it !
My Computer clock was for some reason 4 hours late ! Corrected System Time, it lead to no error.
1 - Make Your you solve the SSL Error if you have any by using the Google API Faq.
It took me whole day, so I'm going to leave my solutions so in future no one has to go crazy like I did.
account_email = '#developer.gserviceaccount.com'
key_file = 'privatekey.p12'
key_secret = 'notasecret'
client = Google::APIClient.new()
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/calendar',
:issuer => account_email,
:signing_key => key)
# # Request a token for our service account
client.authorization.fetch_access_token!
service = client.discovered_api('calendar', 'v3')
Example to execute something shall be like in similar fashion.
#event = {
'summary' => '',
'location' => 'this is where the location goes',
'description' => 'desc',
'start' => {
'dateTime' => '2013-02-08T10:00:00.000-07:00' # Date with :- offset so (yyyy-mm-dd T hh:mm:ss.000-offset)
},
'end' => {
'dateTime' => '2013-02-08T10:25:00.000-07:00' # Date with :- offset so (yyyy-mm-dd T hh:mm:ss.000-offset)
}
}
# Create event using the json structure
result = client.execute(:api_method => service.events.insert,
:parameters => {'calendarId' => '**'},
:body => JSON.dump(#event),
:headers => {'Content-Type' => 'application/json'})

401 Unauthorized for foursquare OAuth

OK, I am pulling my hair after trying this out too many times to debug.
So please help me out here. I keep getting 401 Unauthorized error after I am redirected back.
Here is my code. What am I doing wrong here?
require 'rubygems'
require 'OAuth'
require 'json'
class SessionController < ApplicationController
before_filter :load_oauth
def index
if session[:request_token] && params[:oauth_token]
#request_token = OAuth::RequestToken.new(#consumer,
session[:request_token], session[:request_secret])
#access_token =
#request_token.get_access_token(:oauth_verifier =>
params[:oauth_verifier])
puts #access_token
#info = #access_token.get("http://api.foursquare.com/v1/
test")
flash[:notice] = "Foursquare! Yay!"
else
redirect_to(#foursqrurl)
end
end
private
def load_oauth
#oauth_key = 'key'
#oauth_secret = 'secret'
#consumer = OAuth::Consumer.new(#oauth_key,#oauth_secret,{
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
#request_token = #consumer.get_request_token(:oauth_callback =>
"http://localhost:3001/session")
session[:request_token] = #request_token.token
session[:request_secret] = #request_token.secret
puts #request_token.token
puts #request_token.secret
# redirecting user to foursquare to authorize
#foursqrurl = #request_token.authorize_url
puts #foursqrurl
end
end
I know absolutely nothing about Oauth and this may be completely wrong, but, if http://foursquare.com is not your local machine and oauth_callback is a URL that http://foursquare.com will call when it has completed then it will be calling back to itself as its definition of localhost will be its own 127.0.0.1 i.e itself.
If I have guessed correctly here then change the :oauth_callback to your public IP Address/name.
I think #request_token = OAuth::RequestToken.new(#consumer,
session[:request_token], session[:request_secret]) is wrong.
If you already have the token and the secret, you don't really need to do the verifier thing.
You should construct it like this:
OAuth::RequestToken.from_hash(consumer, { :oauth_token => params[:oauth_token] })
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
Or if you already have the token and the secret, you should do:
access_token = OAuth::AccessToken.from_hash(consumer, {
:oauth_token => "YOUR_TOKEN",
:oauth_token_secret => "YOUR_SECRET"
})

Resources