How to troubleshoot quickbooks-ruby - ruby-on-rails

I have a Rails app set up with the quickbooks-ruby gem.
Oauth seems to be working—there are no errors, I follow the Quickbooks login in a pop-up, and I get a confirmation that the account is connected. No errors.
However, in my audit log on Quickbooks Online, there is not indication that I have logged in.
And when I follow the steps to try to get a list of customers, I get this error:
undefined method 'get' for "qyprd...":String
Which may or may not be a different problem.
This is the code:
def index
#customers = Customer.all
service = Quickbooks::Service::Customer.new
service.company_id = session[:realm_id]
service.access_token = session[:token]
customers = service.query()
end
I don't understand why it isn't working, or how to troubleshoot the issue.

From the above code I see you are not passing the query in last but one line. Query should look something like this i.e customers.query("Select Id, GivenName From Customer")
To understand why it isn't working and to troubleshoot the issue you can use begin and rescue.
begin
oauth_client = OAuth::AccessToken.new($qb_oauth_consumer, token, secret)
service = Quickbooks::Service::Customer.new(:access_token => oauth_client, :company_id => realm_id)
customers = customers.query("Select Id, GivenName From Customer")
rescue Exception => e
# e.message will show response of quickbooks for you request
puts e.message
# e.message.inspect will show logs
puts e.backtrace.inspect
end
You can also try your queries on API explorer and see if get the result set you want.

Related

Twilio returning authenticate error for my local machine only

My team and I are using twilio to send sms messages. Everything seems to work fine on everyone else's local machine (with the same exact code) except twilio always returns an authenticate error to me. I'm sending the messages to their "special number" so it won't actually send a real text message but it still returns an authenticate error.
here's some of our code to send the message:
def send_sms
self.from_phone_number = CONFIG['live_twilio'] ? self.customer.assigned_phone_number : CONFIG['test_phone_number']
self.to_phone_number = CONFIG['live_twilio'] ? self.customer.customer_phone_number : CONFIG['test_phone_number']
begin
report_to_new_relic_insights
send_message_with_twilio!
rescue Twilio::REST::RequestError => e
self.error_description = e.message
end
self.dispatched_at = Time.now
self.save(validate: false)
return e
end
def send_message_with_twilio!
unless self.customer.example_customer?
twilio_params = {
from: "+1#{from_phone_number}",
to: "+1#{to_phone_number}",
body: self.text
}
if ENV['RECORD_TWILIO_STATUSES'].in?(['1', 'true'])
twilio_params[:status_callback] = "#{CONFIG['secure_domain']}/messages/#{id}/update_status"
end
client.account.messages.create(twilio_params)
else
# #onboarding_flow
# don't send the actual SMS to the example customer
self.customer.send_reply_as_example_customer! if self.customer.first_reply?
end
end
def client
#client ||= begin
account_sid = ENV['ACCOUNT_SID'] || CONFIG['account_sid']
auth_token = ENV['AUTH_TOKEN'] || CONFIG['auth_token']
Twilio::REST::Client.new account_sid, auth_token
end
end
every time this line runs: client.account.messages.create(twilio_params)
it returns authenticate error. it works on every other local machine except for mine. all of the code is exactly the same, the auth tokens are exactly the same. any ideas what the problem could be? (the auth tokens are getting pulled from config.yml
More info: even when running the bare bones twilio client in console with the same exact info in both machines, mine returns an error and my coworkers returns valid
Twilio evangelist here.
This could be one of many things, but the only reason Twilio would complain about authentication, is if you have a wrong account SID or auth token.
So can pretty much guarantee this is the bit that is going wrong:
def client
#client ||= begin
account_sid = ENV['ACCOUNT_SID'] || CONFIG['account_sid']
auth_token = ENV['AUTH_TOKEN'] || CONFIG['auth_token']
Twilio::REST::Client.new account_sid, auth_token
end
end
My suggestion here is for you to open up your terminal and run:
$ printenv
This should print all your environment variables for you. You're interested on ACCOUNT_SID and AUTH_TOKEN, so you could get those specific values from terminal as follows:
$ printenv | grep "ACCOUNT_SID\|AUTH_TOKEN"
Then check with your peers if you are using the same values. Please let me know the outcome.

Unable to get facebook Open Graph action approved using rails and the Koala gem

I keep getting this message after submitting my application
Your Open Graph action failed to publish on any of the Platforms you submitted. Make sure the action is working properly by publishing the action with a test user before resubmitting.
I have testers with test users, my own account, testers and it works all the time..
background.
users has_many :authorization_providers, e.g. facebook, twitter, gplus e.t.c
in the facebook action I'm fetching the oauth_token
def facebook
begin provider = authorization_providers.where(provider: 'facebook').first
#facebook ||= Koala::Facebook::API.new(provider.oauth_token)
block_given? ? yield(#facebook) : #facebook
rescue Koala::Facebook::APIError => e #Koala::Facebook::APIError
return nil
end
#facebook
end
In this action I'm getting permission
def facebook_publish_actions
if facebook
begin
permissions = facebook.get_connection("me", "permissions")
publish_actions_permission = permissions.find { |permission| permission["permission"] == "publish_actions" }
publish_actions_permission_granted = publish_actions_permission && publish_actions_permission["status"] == "granted"
return publish_actions_permission_granted
rescue
return false
end
else
return false
end
end
The actual posting is done from a sidekiq worker where 'share_on_facebook' and 'recording' is records from the db
user.facebook.put_wall_post(share_on_facebook.message,
{
"name" => "#{recording.title}",
"link" => "http://www.digiramp.com/users/#{recording.user.slug}/recordings/#{recording.id}",
"caption" => "#{user.name} recomended a recording",
"description" => "#{recording.comment}",
"picture" => "#{recording.get_artwork}"
})
On the facebook developer page I have created one story for the app 'Recommend a Song'
All the above works.
Anyone willing to help me I will grant all the required permissions.
Right now you can go to http://digiramp.com and sign up with facebook.
I will add you as a tester to my project and you should be able to post.
Edit:
I Do pass the id: FbRecordingCommentWorker.perform_async(#share_on_facebook.id)
Can you post the line of the code, where you initiate sidekiq job? Using objects in sidekiq call may not work as expected as objects are stored in hash representation in Redis. So better idea is replacing the object parameters to values.
Replacing some thing like this
User.delay.do_some_stuff(current_user, 20)
with
User.delay.do_some_stuff(current_user.id, 20)
and finding user object in the actual method may fix the issue.

Error Creating Shopify Webhook through the API

I am trying to create a Webhook through the API.
When the Customer installs the app (Controller):
def init_webhooks
topics = ["products/create", "products/update", "products/delete"]
topics.each do |topic|
webhook = ShopifyAPI::Webhook.create(format: "json", topic: topic, address: "http://#{#current_host}/webhooks/#{topic}")
raise "Webhook invalid: (#{topic}) #{webhook.errors}" unless webhook.valid?
end
end
Here is the error from the log:
RuntimeError (Webhook invalid: (products/create) #<ActiveResource::Errors:0x00000003bd7358>):
EDIT:
I have even tried just creating one webhook without the block code like so:
webhook = ShopifyAPI::Webhook.create topic: "products/create", address: "http://myapp.com/webhooks/products/create", format: "json"
But I get the same thing.
From my Routes file:
match 'webhooks/products/create' => 'webhook#product_new'
match 'webhooks/products/update' => 'webhook#product_updated'
match 'webhooks/products/delete' => 'webhook#product_deleted'
I know that the authorization and shop is in fact installing correctly because if I Comment out the 'Raise' error line, I then proceed to the index page which displays some test orders and test products that I created within the Shopify Admin.
I'm not sure where to go from here. Thanks
b
The params you use (topic,format,address) look good to me, but shouldn't it be ShopifyAPI::Webhook.new instead of create?
Did you now there is a shopify console where you can easily test your ruby code?

confused and disoriented with paypal ipn

I am using this gem for payments in paypal https://github.com/tc/paypal_adaptive
I am very confused and disoriented with this gem. It has a poorly documented and is difficult for me to understand how to get the data from paypal on ipn response.
I hope this question will help more people having the same problem.
My steps are:
1º I send request to paypal from my orders_controller.rb with method preaproval_payment.
def preapproval_payment
preapproval_request = PaypalAdaptive::Request.new
data = {
"returnUrl" => response_paypal_user_orders_url(current_user),
"cancelUrl"=> cancel_payment_gift_url(#gift),
"requestEnvelope" => {"errorLanguage" => "en_US"},
"senderEmail" => "gift_1342711309_per#gmail.com",
"startingDate" => Time.now,
"endingDate" => Time.now + (60*60*24) * 30,
"currencyCode"=>"USD",
"maxAmountPerPayment" => "#gift.price",
"ipnNotificationUrl" => ipn_notification_url,
"ip" => request.remote_ip
}
preapproval_response = preapproval_request.preapproval(data)
puts data
if preapproval_response.success?
redirect_to preapproval_response.preapproval_paypal_payment_url
else
redirect_to gift_url(#gift), alert: t(".something_was_wrong")
end
end
2º These are the data of my request in my log console from command puts data :
{"returnUrl"=>"http://localhost:3000/en/u/maserranocaceres/orders/response_paypal", "cancelUrl"=>"http://localhost:3000/en/gifts/gift-1/cancel_payment", "requestEnvelope"=>{"errorLanguage"=>"en_US"}, "senderEmail"=>"gift_1342711309_per#gmail.com", "startingDate"=>2012-07-29 13:05:49 +0200, "endingDate"=>2012-08-28 13:05:49 +0200, "currencyCode"=>"USD", "maxAmountPerPayment"=>9, "ipnNotificationUrl"=>"http://localhost:3000/ipn_notification?locale=en", "ip"=>"127.0.0.1"}
3º I redirect to paypal page, and I make the payment on paypal successfully :D.
4º When payment is completed successfully, I am directed to:
http://localhost:3000/en/u/maserranocaceres/orders/response_paypal
I have response_paypal action in orders_controller.rb. It is GET action and my code for this action is:
def response_paypal
respond_to do |format|
format.html { redirect_to user_orders_url(current_user), :alert => "works fine return url"}
end
end
Up to this point everything works fine.
Now what I need is to get the data I received from paypal and save my database a new order if payment is successfully processed.
5º For this purpose I make a file in lib/paypal_ipn.rb and I add to this file the content from https://github.com/tc/paypal_adaptive/blob/master/templates/paypal_ipn.rb
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
class PaypalIpn
def self.call(env)
if env["PATH_INFO"] =~ /^\/paypal_ipn/
request = Rack::Request.new(env)
params = request.params
ipn = PaypalAdaptive::IpnNotification.new
ipn.send_back(env['rack.request.form_vars'])
if ipn.verified?
#mark transaction as completed in your DB
output = "Verified."
else
output = "Not Verified."
end
[200, {"Content-Type" => "text/html"}, [output]]
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
end
end
In my routes.rb I add:
match "/ipn_notification" => PaypalIpn
My 2 problems are:
a) I do not see that after making the payment this file to be fired and I can not see in my console data I get from paypal.
b) I want to send to paypal in my request, the id of object #gift for being able to recover later in paypal_ipn.rb and to save my database.
What am I doing wrong and how I can solve these problems?
Thank you
I haven't used that gem, but I've used PayPal IPN before. Here are some things you should check:
Do you have your PayPal account set up to use IPN? You must enable this setting on the account for this to work.
Have you verified that when you pass ipn_notification_url during the payment process, that it matches your "/ipn_notification" route?
For this to work, PayPal must be able to communicate directly with the server that is running this app. This means that typically, unless you have a custom setup on your local machine with dynamic DNS or something, that you will need to actually deploy this code to a server in order for PayPal to be able to communicate with your app. In other words, if this is running on http://localhost:3000, this will not work.
To answer your second question, how to recover #gift in order to record the fact it was paid in your database, I'm not entirely sure how to do it with this gem, but I'll tell you how I do it using ActiveMerchant - it is probably quite similar.
In your payment request to PayPal, you can pass in an invoice number. I believe the field is just called "invoice". Here you would pass the ID of the gift.
When PayPal notifies your app via IPN that the order was paid for, it will pass the invoice number back to you. Retrieve the #gift using this invoice number and then you can do what you need with it.
Here are the relevant parts of my working PayPal code, using the ActiveMerchant gem: https://gist.github.com/3198178
Good luck!

Ruby on Rails - Checking against HTTP errors in controller

Just today I've found my fbgraph implementation has started returning a 400 Bad Request error which is causing an internal server error.
The controller looks like:
def fb
fbclient = FBGraph::Client.new(:client_id => 'ID', :secret_id => 'SECRET')
#fbname = fbclient.selection.user('129220333799040').feed.info!['data'][0].from.name
#fbmessage = fbclient.selection.user('129220333799040').feed.info!['data'][0].message
end
How can I check before calling #fbname in my view that I've received a 200 status?
Thanks.
Update: following Devin M's suggestion, I've switched the above action to
def fb
fbclient = FBGraph::Client.new(:client_id => 'ID', :secret_id => 'SECRET')
begin
#fbname = fbclient.selection.user('129220333799040').feed.info!['data'][0].from.name
#fbmessage = fbclient.selection.user('129220333799040').feed.info!['data'][0].message
rescue
#fbname = "Facebook Account"
#fbmessage = "Facebook's API is a nightmare"
end
end
I think that you should write some tests for this, Its hard to work with Facebooks nightmare of an API.
Although if you wanted to catch this error try using that way you can catch the specific error and take some action on it in the rescue portion.
begin
rescue
end
If you want me to take a look at the docs and see what you should catch let me know.

Resources