Fetching signed_request in a Facebook App with Ruby/Sinatra and the Rest-Graph gem - ruby

I've built a Facebook app using Sinatra and the Rest-Graph gem. Now I would like to embed the app as an iframe tab in a Facebook Page.
To do that, I need to fetch data from the signed_request sent to my app by Facebook.
The Rest-Graph gem states the following feature on its Github page:
Utility to extract access_token and
check sig in cookies/signed_request
I couldn't find any documentation on how to use this "utility". Can you point me to some documentation or even better, give me an example on how this is used with Ruby/Sinatra?

Nearly all of the Graph API libraries that are available deal with signed_request in a similar way. Rest-Graph has a parse_signed_request method (Rest-Graph/lib/core.rb) that you can call in Sinatra.
I'm using Koala for this with Sinatra, and it works as advertised:
oauth = Koala::Facebook::OAuth.new(APP_ID, APP_CODE)
signed_request = oauth.parse_signed_request(params["signed_request"])
You get back a hash of the JSON object that Facebook posts:
{
"algorithm"=>"HMAC-SHA256",
"issued_at"=>1303883452,
"user"=>
{
"country"=>"us",
"locale"=>"en_US"
},
"user_id"=>"100002364226618"
}
rest-graph makes it pretty easy, too. Just tested this in a Sinatra app. Works perfectly:
rg = RestGraph.new( :app_id => APP_ID, :secret => APP_SECRET)
parsed_request = rg.parse_signed_request!(params["signed_request"])
Lemme know if that doesn't work for you.

I just got a response to this question from "cardinalblue", the developer of the Rest-Graph gem. This little example was exactly what I was looking for:
require 'sinatra'
require 'rest-graph'
app_id = '123'
secret = 'abc'
config = {:app_id => app_id,
:secret => secret}
post '/' do
rg = RestGraph.new(config)
rg.parse_signed_request!(params['signed_request'])
"#{rg.get('me').inspect.gsub('<', '<')}\n"
end
run Sinatra::Application
Sidenote: In case you're building something similar, please note the post '/' do. Facebook Pages fetch your page using a POST request instead of a GET.

Related

Get Wordpress posts by tag in Ruby

We have a Wordpress instance with the XML-RPC API enabled and a Ruby on Rails website we want to display Wordpress posts on. I need to get posts by "tag". Looking at Rubypress it seems as though I have to wp.getPosts and parse out the correct ones. This is inefficient as we add new posts and have to keep updating.
Is there a way to get posts from a Wordpress instance via the API by tag?
Thank you.
We solved this with the wp_api_client gem and using the tags?slug=TAG endpoint. e.g.
require 'wp_api_client'
WpApiClient.configure do |api_client|
api_client.endpoint = "yourwordpress.com/wp-json/wp/v2"
api_client.basic_auth = {username: username, password: password}
end
client = WpApiClient.get_client
client.get("tags?slug=#{tag_you_want}").each do |tag|
client.get("posts?tags=#{tag.id}")
end

Shopify API Search Parameters

I'm trying to get all of my customers that don't accept marketing but nothing seems to be working that I'm trying.
ShopifyAPI::Customer.find(:all, :params => { accepts_marketing: false})
I'm using the shopify_api Ruby gem.
The search endpoint is a little different than the usual. As you point out, your issue has nothing to do with Rails. Instead, just provide the endpoint with a little more information and you'll be fine. Try this:
ShopifyAPI::Customer.all( from: :search, params: {q: "accepts_marketing:true"})
You can search on customer email, whatever you need when you specify the endpoint as search on the Customer.

ruby multipart post image with digest auth

Given I have this, using Ruby 1.9.3p194
Authentication is digestauth
require 'json'
require 'httpclient'
API_URL= "https://api.somewhere.com/upload"
API_KEY='blahblah'
API_SECRET ='blahlbah'
IMAGE ='someimage.png'
h=HTTPClient.new
h.set_auth(API_URL, API_KEY, API_SECRET)
File.open(IMAGE) do |file|
body = { 'image' => file}
res = h.post(API_URL, body)
p res.inspect
end
I get errors
Ive tried Typheous, Patron, Mechanize, Curl but want to find a way that is simple and works
e.g.
curl --digest -u myusrname:password -F "image=#image.png" "https://api.somewhere.com/upload"
Curl posts nothing and doesnt work as expected. Ive been assured that the API accepts posts, I have a simple web page that does what I need to do via a simple form and it works fine
Any one know what the easiest way ahead is?
Thanks
Solved it, went back to Curb. It is a RESTful API, RestClient was doing something funky with the digest. HttpClient too was posting blank files. Curb did it.

Why does Google's Custom Search API say that I'm missing an access token when using the Ruby client?

I'm trying to use Google's Custom Search API through the Google API Ruby client. I have setup my API key through the Google API console, and have also created my CSE. Based on the documentation, it seems that, as long as I provide an API key (which I am doing), I shouldn't need an OAuth2 authentication token to call the list method. However, when I try to execute the code below, I get the following error:
ArgumentError: Missing access token.
What am I missing? Here's my code:
# create client
client = Google::APIClient.new
# Fetch discovery doc
search = client.discovered_api('custom search')
# Call list method
response = client.execute(
search.cse.list, 'key' => '<my API key>', 'cx' => '<my CSE id>', 'alt' => 'json', 'q' => 'hello world'
)
I believe this is in fact a bug in the client (it's in alpha). After fiddling with it a little more, I've found a workaround:
just after creating the client object, assign it a "dummy" access token:
client.authorization.access_token = '123'
then you can call the search.cse.list method without getting the 'ArgumentError: Missing access token.' error.
If you're just after using Google CSE with ruby, try google-cse. I just built the gem, although I've been using it for a while privately. Much easier to work with than the alpha client
I found out that adding client.retries = 3 to my code solves this problem.
With the current version of the gem (0.7.1), you need to set the authorization to nil in addition to setting the key:
require 'google/api_client'
client = Google::APIClient.new
client.key = ENV['GOOGLE_API_KEY']
client.authorization = nil
client.execute ...

how can I capture response from twitter.com? ( ruby + twitter gem)

how can I capture response from twitter.com? To make sure that everything went ok?
I am using ruby and ruby twitter gem and the my code is basically like that
oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
oauth.authorize_from_access('access token', 'access secret')
client = Twitter::Base.new(oauth)
client.update('Heeeyyyyoooo from Twitter Gem!')
The update twitter api method will send back a response that will let you know if everything went okay. It can respond in either json or xml, I'm sure the twitter gem is using one or the other as a default. You need to save the return value to a variable and parse it, if you have a status id in there then it worked. Try using a token or secret to check what happens when it errors. I would suggest changing your last line to this
ret = client.update('Heeeyyyyoooo from Twitter Gem!')
and then add this line below that to check out what you got back
puts ret.inspect
or
logger.info ret.inspect
or your choice of logging method
[Edit]
It looked like the twitter gem hides the twitter api's actual response from you, parses it for you and just returns you the relevant bits. in the case of the update method it just returns you the id of your new tweet. you can view the id like this
puts ret.id
If you use another library to connect to the twitter api and need to parse xml or json responses then then the rest of this answer may be what you are looking for.
[/Edit]
If you are not using a gem that parses twitter api responses for you then you will need to use something to parse the twitter api's responses into data that you can do something with. There are tons of ways to do this depending on what format you want to parse (json or xml)
My preferences:
XML : Hpricot : gem install hpricot : http://github.com/hpricot/hpricot
json : json : gem install json : http://github.com/flori/json
Here is more information on what the twitter api update method returns: http://apiwiki.twitter.com/Twitter-REST-API-Method:-statuses%C2%A0update
This worked for me...
begin
resp = Twitter.update(params[:message])
rescue Exception => e
# e.message contains the twitter response
end

Resources