Created
August 14, 2011 12:46
-
-
Save ainame/1144850 to your computer and use it in GitHub Desktop.
Ruby+SinatraでmixiのGraph APIを利用してユーザー情報を取得するチュートリアル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require 'oauth2' | |
require 'sinatra' | |
require 'httparty' | |
require 'yaml' | |
enable :sessions | |
# コンシューマキーとシークレットを設定 | |
configure do | |
config = YAML.load_file("setting.yml") #yaml形式で設定を書いた | |
@@client = OAuth2::Client.new( config['consumer_key'], #yamlで読み込まず直接書いてもOK | |
config['consumer_secret'], | |
:site => 'http://api.mixi-platform.com', | |
:authorize_url => 'https://mixi.jp/connect_authorize.pl', | |
:token_url => 'https://secure.mixi-platform.com/2/token') | |
end | |
# セッションにトークンが存在してればAPIへアクセス | |
get '/' do | |
if session[:token] | |
response = HTTParty.get('http://api.mixi-platform.com/2/people/@me/@self', | |
:query => {:oauth_token => session[:token]}) | |
"ようこそ<br />#{response['entry']['displayName']}さん!"+ | |
"<br /><a href='/logout'>ログアウト</a>" | |
else | |
"ようこそ!<br /><a href='/login'>ログイン</a>" | |
end | |
end | |
# 認証ページへ飛ぶ、スコープの設定もここ | |
get '/login' do | |
redirect @@client.auth_code.authorize_url( | |
:scope => "r_profile r_voice w_voice r_updates") | |
end | |
get '/logout' do | |
session[:token] = nil | |
session[:ref_token] = nil | |
redirect '/' | |
end | |
# コールバックでアクセストークンを取得(コールバックURLを指定) | |
get '/callback' do | |
token = @@client.auth_code.get_token(params["code"], | |
{ :redirect_uri => 'http://0.0.0.0:4567/callback' }) | |
session[:ref_token] = token.refresh_token.to_s | |
session[:token] = token.token.to_s | |
redirect '/' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment