Constantly get Authentication+failed.+API+credentials+are+incorrect - ruby-on-rails

I'm trying to create simple PayPal Pay API operation, when I run this code from console it gave me response, that payment is created.
Now, when I'm tring to run it from my controller it gives me
Authentication+failed.+API+credentials+are+incorrect.
Here is my controller :
def pay
require 'httpclient'
require 'xmlsimple'
clnt = HTTPClient.new
credentials = {
'USER' => 'payer_1342623102_biz_api1.gmail.com',
'PWD' => '1342623141',
'SIGNATURE' => 'Ay2zwWYEoiRoHTTVv365EK8U1lNzAESedJw09MPnj0SEIENMKd6jvnKL '
}
header = {"X-PAYPAL-SECURITY-USERID" => "payer_1342623102_biz_api1.gmail.com",
"X-PAYPAL-SECURITY-PASSWORD" => "1342623141",
"X-PAYPAL-SECURITY-SIGNATURE" => "Ay2zwWYEoiRoHTTVv365EK8U1lNzAESedJw09MPnj0SEIENMKd6jvnKL ",
"X-PAYPAL-REQUEST-DATA-FORMAT" => "NV",
"X-PAYPAL-RESPONSE-DATA-FORMAT" => "XML",
"X-PAYPAL-APPLICATION-ID" => "APP-80W284485P519543T"
}
data = {"actionType" => "PAY",
"receiverList.receiver(0).email"=> "denmed_1342605975_biz#gmail.com",
"receiverList.receiver(0).amount" => "10",
"currencyCode" => "USD",
"cancelUrl" => "http://127.0.0.1:3000",
"returnUrl" => "http://127.0.0.1:3000",
"requestEnvelope.errorLanguage" => "en_US"}
uri = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay"
res = clnt.post(uri, data, header)
#xml = XmlSimple.xml_in(res.content)
payKey = #xml["payKey"].to_s()
payKey = payKey.tr("[]", "")
payKey = payKey[1..20]
redirect_to "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay?cmd=_ap-payment&paykey=#{payKey}"
end
Is everything ok ? Can anyone suggest reason my request fails ?

One good man found my error. I redirect user to the wrong url.
This line:
redirect_to "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay?cmd=_ap-payment&paykey=#{payKey}"
Should be:
redirect_to "https://sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=#{paykey}"

I got the same error: I realized I forgot to include
sandbox_email_address: xxx#example.com
in my yml file

Related

undefined method `values_at' for nil:NilClass when I use WashOut gem

I am new to WSDL.
Code (I have added in the view directly - for test): (Page: http://localhost:3000/ccapis )
require 'savon'
client = Savon::Client.new(wsdl: "http://localhost:3000/ccapis/wsdl")
result = client.call(:fetch_prizes, message: { :gl_id => "123456789" })
result.to_hash
And in the controller:
soap_action "fetch_prizes",
:args => { :gl_id => :string },
:return => [:array]
def fetch_prizes
glnumber = params[:gl_id ]
prize = Prize.where(:gl_id => glnumber)
prize_to_show = []
a_hash = {}
prize.each do |p|
a_hash = { :prize => p.prize.to_s, :score => p.score.to_s, :date => p.round_date.to_s }
prize_to_show.push a_hash
a_hash = nil
end
render :soap => prize_to_show
end
When I try and run this in the Console all are good and I can see the result.to_hash but when I go to http://0.0.0.0:3000/ccapis I get the error that I mentioned above.
Explanation of what I am trying to achieve:
I need to supply a WSDL for a client which fetches all the prizes based on a score.
If My approach is wrong please direct me to a document so I can have a read and get a better understanding. Thanks again.

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

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'})

The amount is invalid paypal_adaptive gem rails

I am receiving this error in my log console:
The amount is invalid
I am working in development env, with http://localhost:3000/
I have in my controller:
def pay
pay_request = PaypalAdaptive::Request.new
data = {
"returnUrl" => user_orders_url(current_user),
"requestEnvelope" => {"errorLanguage" => "en_US"},
"currencyCode" => "USD",
"receiverList" =>
{ "receiver" => [
{"receiver"=> [{"email"=>"email1", "amount"=>"10.00", "primary" => true}, {"email"=>"email2", "amount"=>"9.00", "primary" => false}]}
]},
"cancelUrl" => user_orders_url(current_user),
"actionType" => "PAY",
"ipnNotificationUrl" => ipn_notification_user_orders_url(current_user)
}
pay_response = pay_request.pay(data)
if pay_response.success?
# Send user to paypal
redirect_to pay_response.preapproval_paypal_payment_url
else
puts pay_response.errors.first['message']
redirect_to root_url, alert: "Something went wrong. Please contact support."
end
end
What am I doing bad?
Can you test with
"amount"=>10
Or
"amount"=>"10"
The error was fixed:
The error is in "primary" => true and "primary" => false.
I have removed this code and now the controller does works fine.
Thank you very much!

How to use Rhodes without Rhosync or RhoConnect?

I know we can sync data using rhodes without Rhosync or Rhoconnect by using direct web service, but I'm here little bit confuse where to place that code for webservice call and how do we initialize it. Can anyone help me with small example?
Thanks in Advance.
I got it and it works for me.
class ProductController < Rho::RhoController
include BrowserHelper
# GET /product
def index
response = Rho::AsyncHttp.get(:url => "example.com/products.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
render :back => '/app'
end
# GET /product/{1}
def show
id =#params['id']
response = Rho::AsyncHttp.get(:url => "example.com/products/"+ id +".json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# GET /product/new
def new
#product = product.new
render :action => :new, :back => url_for(:action => :index)
end
# GET /product/{1}/edit
def edit
id =#params['product_id'].to_s
response = Rho::AsyncHttp.get(:url => "example.com/products/#{id}.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# POST /product/create
def create
name = #params['product']['name']
price = #params['product']['price']
body = '{"product" : {"name" : "'+ name +'","price" :"'+ price +'" } }'
#result = Rho::AsyncHttp.post(:url => "example.com/products.json",
:body => body, :http_command => "POST", :headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/update
def update
name=#params['product']['name']
price=#params['product']['price']
body = '{"product" : {"name" : "' + name + '","price" :"' + price + '" } }'
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:body => body, :http_command => "PUT",:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/delete
def delete
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:http_command => "DELETE",
:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
end
Most easy form of http server request is next:
Rho::AsyncHttp.get(
:url => "http://www.example.com",
:callback => (url_for :action => :httpget_callback)
)
where httpget_callback is name of the controller callback method.
See more details at official Rhodes docs.

Resources