LoginSignup
2
2

More than 5 years have passed since last update.

PHP で OAuth 1.0 Request を生成する

Posted at

[!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 を実装します。

処理のおおまかな流れとしては:

  1. OAuthConsumer クラスと OAuthSignatureMethod クラスをインスタンス化する
  2. OAuthConsumerOAuthSignatureMethod のインスタンスと HTTP リクエスト情報 (URLやパラメータ等) を引数にOAuthRequest クラスをインスタンス化する
  3. OAuthRequest クラスの sign_request() メソッドで署名(シグネチャ)を生成する
  4. 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);

参考

2
2
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
2
2