Skip to content

Instantly share code, notes, and snippets.

@jotto
Forked from sco/facebook_client.rb
Created May 6, 2009 19:22
Show Gist options
  • Save jotto/107682 to your computer and use it in GitHub Desktop.
Save jotto/107682 to your computer and use it in GitHub Desktop.
# Lo-fi client for the Facebook API. E.g.:
#
# fb = FacebookClient.new(:api_key => 'api-key', :secret => 'secret')
# fb.call 'users.getInfo', :session_key => 'session-key', :uids => 'user-id', :fields => 'birthday'
#
class FacebookClient
def initialize(default_params={})
@default_params = default_params.reverse_merge({
:rest_server => 'http://api.new.facebook.com/restserver.php',
:format => 'JSON',
:v => '1.0',
:api_key => '',
:secret => '',
})
end
def call(method, params={})
params = @default_params.merge(params)
params[:method] ||= 'facebook.' + method
params[:call_id] ||= Time.now.to_f.to_s
secret = params.delete(:secret)
rest_server = params.delete(:rest_server)
raw_string = params.inject([]) { |args, pair| args << pair.join('=') }.sort.join
params[:sig] = Digest::MD5.hexdigest(raw_string + secret)
response = Net::HTTP.post_form(URI.parse(rest_server), params)
begin
JSON.parse(response.read_body)
rescue JSON::ParserError
# some FB API methods, like send notification, don't return valid JSON, but rather JSON tokens, like '"123123"'
response.read_body
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment