Error Creating Shopify Webhook through the API - ruby-on-rails

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?

Related

How To Search a User in Discourse Using Ruby

I am trying to find and delete unwanted user in my discourse using ruby
puts "Search Member you want to Delete"
puts "Search By E-Mail"
usermail = gets
puts client.search(usermail)
in result it takes me to discourse page
is there any possible ways to search and find the exact user by email.
thanks for your nice and helpful comments
i think we cannot search users by email and we can just use the following for geting users list
require 'rest-client'
RestClient.get 'http://example.com/resource', {params: {id: 50, 'foo' => 'bar'}}
we can get a user by name using Http gem
require 'http'
username = 'username'
response = HTTP.get("https://discourse.example.com/user/#{username}.jason?api_key=Your_Discourse_api_key")
puts response.body.to_s
it worked for me

How to troubleshoot quickbooks-ruby

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.

"campaing_id" is not a symbol error when using mail chimp api with gibbon

Context:
I have a rails application. I have a form where users can enter their email list to be a part of the news letter.
I am using mail chimp and gibbon gem for rails.
I can successfully add new subscribers to a list using the gibbon api
I can successfully create a new campaign as shown in the code below.
In my gem file :
gem 'gibbon', git: 'git://github.com/amro/gibbon.git'
For testing out the functionality, I invoke the create action in CampaignsController(code below).
The campaign is created successfully and I get the result back from the api, but in the next step the app crashes with the following error message :
Problem:
TypeError in CampaignsController#create
["xyz"] is not a symbol where xyz is the campaign_id of the newly created campaign.
Code:
In CampaignsController
def create
mailchimp = Gibbon::API.new(Rails.application.secrets.mailchimp_api_key)
new_campaign = mailchimp.campaigns.create({:type=>"plaintext",
:options=>
{:list_id=>"abcdefgh",
:subject=>"Hello World",:from_email => "xyz#gmail.com",
:from_name => "abc",:to_name =>"Programmer"},
:content =>
{:text => "Hello remote programmers I hope you find this mail."}
})
cid = new_campaign["id"]
mailchimp.campaigns.send(cid)
end
It looks like mailchimp.campaigns.send is looking for a hash of options, not just an id.
From their specs:
expect(#gibbon.campaigns.send({"cid" => "1234567"})).to eq({"cid" => "1234567"})

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