[!NOTE]
この記事は 2012/07/15 にseijimomoto.blogspot.com/2012/07/oauth-consumer-request-10php.html
へ投稿した内容を Qiita へ移行してきたものです
この記事で言及されている OAuth 1.0 Library は 2014 年から更新されていません。
PHP の OAuth 1.0 Library を使用して OAuth Consumer Request を実装します。
処理のおおまかな流れとしては:
-
OAuthConsumer
クラスとOAuthSignatureMethod
クラスをインスタンス化する -
OAuthConsumer
とOAuthSignatureMethod
のインスタンスと HTTP リクエスト情報 (URLやパラメータ等) を引数にOAuthRequest
クラスをインスタンス化する -
OAuthRequest
クラスのsign_request()
メソッドで署名(シグネチャ)を生成する -
to_header()
メソッドでAuthorization
ヘッダを生成する
OAuthConsumer のインスタンスは、サービスプロバイダから与えられた Consumer Key ごとに 1つあればよいですが、OAuthRequest は API にアクセスする度にインスタンス化します。
Authorization ヘッダを生成した後は、cURL 関数を使用して HTTP リクエストを送信します。
GET
// OAuthConsumer と OAuthSignatureMethod をインスタンス化する
$consumer_key = "****";
$consumer_sec = "****";
$consumer = new OAuthConsumer($consumer_key, $consumer_sec, null);
$signature = new OAuthSignatureMethod_HMAC_SHA1();
// OAuthRequest をインスタンス化する
$http_method = "GET";
$http_url = "http://example.com/resource";
$req = OAuthRequest::from_consumer_and_token($consumer, null, $http_method, $http_url, null);
$req->sign_request($signature, $consumer, null);
$authorization = $req->to_header();
// cURL で HTTP リクエストを送信する
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $req->to_url());
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = array(
"exec" => curl_exec($ch),
"error" => curl_error($ch)
);
curl_close($ch);
もし、GET パラメータがあるならば $http_url
に ?
で繋げて続けてもよいし、from_consumer_and_token()
メソッドの5つ目の引数に配列型として渡してもいい(どちらにしてもOAuthRequestのコンストラクタがパースしてBase Stringに含めてくれる)。
POST
$token = new OAuthToken($oauth_token="******", $oauth_token_secret="******");
$http_method = "POST";
$http_url = "http://example.com/resource";
$parameters = array("foo" => "bar");
$req = OAuthRequest::from_consumer_and_token($consumer, $token, $http_method, $http_url, null);
$req->sign_request($signature, $consumer, $token);
$authorization = $req->to_header();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $req->to_url());
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization, "Content-Type: application/json; charset=utf-8"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = array(
"exec" => curl_exec($ch),
"error" => curl_error($ch)
);
curl_close($ch);