Created
January 18, 2011 17:02
-
-
Save ritou/784750 to your computer and use it in GitHub Desktop.
hatena OAuth Sample Consumer using Pecl OAuth Library.
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
<?php | |
/* | |
OAuthのPHP Extension(PECL OAuth? http://php.net/manual/ja/book.oauth.php) | |
を使ってはてなのユーザー情報を取得するサンプル。 | |
*/ | |
// エンドポイント | |
// RequestToken取得URLにScopeパラメータをつけておくと、しれっと処理されるっぽい。 | |
$req_url = 'https://www.hatena.com/oauth/initiate?scope=read_public'; | |
$authurl = 'https://www.hatena.ne.jp/oauth/authorize'; | |
$acc_url = 'https://www.hatena.com/oauth/token'; | |
// コールバック。 | |
$cbc_url = '(このPHPが置かれるパス)'; | |
$api_url = 'http://n.hatena.com/applications/my.json'; | |
// ConsumerKey/Secretはそれぞれで取得してください | |
$conskey = '(ConsumerKey)'; | |
$conssec = '(ConsumerSecret)'; | |
session_start(); | |
// セッションの state の値が1の場合、次のリクエストには oauth_token の値が含まれているはずである | |
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0; | |
try { | |
$oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI); | |
$oauth->enableDebug(); | |
if(!isset($_GET['oauth_token']) && !$_SESSION['state']) { | |
// getRequestTokenの第2引数にコールバックURLをつけることで1.0aのリクエストに対応。省略すると"oob"らしい | |
$request_token_info = $oauth->getRequestToken($req_url,$cbc_url); | |
$_SESSION['secret'] = $request_token_info['oauth_token_secret']; | |
$_SESSION['state'] = 1; | |
header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']); | |
exit; | |
} else if($_SESSION['state']==1) { | |
$oauth->setToken($_GET['oauth_token'],$_SESSION['secret']); | |
$access_token_info = $oauth->getAccessToken($acc_url); | |
$_SESSION['state'] = 2; | |
$_SESSION['token'] = $access_token_info['oauth_token']; | |
$_SESSION['secret'] = $access_token_info['oauth_token_secret']; | |
} | |
$oauth->setToken($_SESSION['token'],$_SESSION['secret']); | |
$oauth->fetch($api_url); | |
$json = json_decode($oauth->getLastResponse()); | |
print_r($json); | |
// 最初からやり直す時はブラウザ落とすかセッションクッキー落とすこと。 | |
} catch(OAuthException $E) { | |
print_r($E); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment