Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created August 18, 2013 03:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save komasaru/6259750 to your computer and use it in GitHub Desktop.
Save komasaru/6259750 to your computer and use it in GitHub Desktop.
Ruby script to get Facebook user informations by Facebook API.
require 'json'
require 'net/https'
# 各種定数
URL_BASE = "https://graph.facebook.com/{ユーザID or ユーザ名}"
APP_ID = "{Facebook アプリの APP-ID}"
APP_SECRET = "{Facebook アプリの APP-SECRET}"
# [CLASS] Facebook API
class FbApi
def initialize
# App Access Token 取得
@token = get_token
end
# Facebook 情報取得
def get_info
begin
uri = URI.parse(URL_BASE)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = http.request(Net::HTTP::Get.new("#{uri.request_uri}?access_token=#{@token}"))
contents = JSON.parse(res.body)
puts JSON.pretty_generate(contents)
# 個別に取得するなら以下のように。
#puts contents["location"]["id"]
#puts contents["location"]["name"]
rescue => e
STDERR.puts "[ERROR][#{self.class.name}.get_info] #{e}"
exit 1
end
end
private
# App Access Token 取得
# ( ここでのアクセストークンは、
# User に紐付いている User Access Token ではない。
# Facebook アプリに紐付いていている App Access Token のこと。 )
def get_token
begin
uri = URI.parse("https://graph.facebook.com/oauth/access_token")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = http.request(Net::HTTP::Get.new("#{uri.request_uri}?client_id=#{APP_ID}&client_secret=#{APP_SECRET}&grant_type=client_credentials"))
return res.body.split("=")[1]
rescue => e
STDERR.puts "[ERROR][#{self.class.name}.get_token] #{e}"
exit 1
end
end
end
# 開始メッセージ
puts "#### Get Facebook information [ START ]"
# Facebook 情報取得
obj_main = FbApi.new
obj_main.get_info
# 終了メッセージ
puts "#### Get Facebook information [ E N D ]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment