LoginSignup
11
13

More than 5 years have passed since last update.

facebookログインでユーザーの情報を取得するコード

Last updated at Posted at 2015-08-13

案外苦戦したので記録

GraphAPIはver2.4を使用。

facebook_accesstoken_fetcher.rb
# coding: utf-8
# facebook authorize constant
CLIENT_ID=XXXXXXXXXXXXXXXXXX
# facebook app secret
APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXX'
# 注意:下記定数変更時はfacebook developerでアプリ情報の変更も必要
REDIRECT_URI = 'http://localhost:3000/web/login/new'

module FacebookInformationFetcher


  # facebookログインダイアログのURLを取得
  def login_dialog_url
    return "https://www.facebook.com/v2.4/dialog/oauth?client_id="+CLIENT_ID.to_s+"&redirect_uri="+REDIRECT_URI+"&scope=email"
  end

  # アクセストークンを取得
  def fetch_accesstoken(code)
    url = "https://graph.facebook.com/oauth/access_token?client_id="+CLIENT_ID.to_s+"&client_secret="+APP_SECRET+"&redirect_uri="+REDIRECT_URI+"&code="+code
    uri = URI.parse(url)
    https = Net::HTTP.new(uri.host, uri.port)
    https.use_ssl = true
    req = Net::HTTP::Post.new(uri.request_uri)
    req["Content-Type"] = "application/json"
    return https.request(req)
  end

  # ユーザーデータの取得
  def fetch_user_information(access_token)
    # 登録に必要な情報の取得
    url = "https://graph.facebook.com/me?fields=email,id,name&access_token="+access_token
    uri = URI.parse(url)
    req = Net::HTTP::Get.new(uri.request_uri)
    req["Content-Type"] = "application/json"
    https = Net::HTTP.new(uri.host, uri.port)
    https.use_ssl = true
    res = https.request(req)
    parameter = JSON.parse(res.body)

    if parameter['error']
      # トークンの期限切れ
      if parameter['error']['code'] == 190
        return false
      end
    else
      return parameter
    end

  module_function :login_dialog_url,:fetch_accesstoken,:fetch_user_information

facebookログイン時のリダイレクト先でアクセストークン取得用のコードが取得できる。
そのコードを使用してfetch_accesstoken メソッドからアクセストークンを取得。
さらに、アクセストークンを使用してfetch_user_informationメソッドからユーザーの情報を取得する。
どのような情報を取得するかはlogin_dialog_url で返さすアドレスのscopeパラメーターに左右されるのでその辺りは調整しないといけない。

参考ページ
Facebook OAuth認証(認証ありで誕生日とEmailを取得)
Facebook Login

11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13