OAuth.phpだけで twitter APIする
問題
twitterのAPIを使うライブラリはいろいろあるけど、なるべくシンプルな装備でtwitterのAPIを使えないか。phpで。

解答例
OAuth.php(http://code.google.com/p/oauth/)だけを使ってやってみる。
OAuth1.0の仕様にある、署名の計算やエンコード、パラメータの並び替えなどのややこしそうな部分はOAuth.phpにお任せする。
それ以外を自分でやる。
oauth_*なパラメータもリクエスト本体に含める場合
<?php
//依存するのはこれだけ
require 'OAuth.php';
//OAuthのいつもの
$consumer_key = '**********************';
$consumer_secret = '****************************************';
$oauth_token = '********-*****************************************';
$oauth_token_secret = '*****************************************';
//どの twitter API
$url = 'https://api.twitter.com/1/statuses/update.json';
//POST or GET
$method = 'POST';
//パラメータ
$parameters = array('status' => 'テストのツイート');
//難しそうなところだけOAuth.phpにお願いする
$sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
$consumer = new OAuthConsumer($consumer_key, $consumer_secret);
$token = new OAuthConsumer($oauth_token, $oauth_token_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $parameters);
$request->sign_request($sha1_method, $consumer, $token);
//↑こうして出来上がった$requestから何でももらえる(メソッド、リクエスト送信先、パラメータ、ヘッダ、署名 etc.)
//POSTリクエストはfile_get_contents()で十分可能
$options = array(
'http'=>array(
'method' => $request->get_normalized_http_method(),
'content' => $request->to_postdata()
)
);
$context = stream_context_create($options);
$result = file_get_contents($request->get_normalized_http_url(), false, $context);
//例えば結果を確認してみる
var_dump($result);
oauth_*なパラメータはヘッダに含めたい場合
$request->to_postdata()をするとoauth_*も混ざってきたので、使わないようにしてみた。
<?php
//依存するのはこれだけ
require 'OAuth.php';
//OAuthのいつもの
$consumer_key = '**********************';
$consumer_secret = '****************************************';
$oauth_token = '********-*****************************************';
$oauth_token_secret = '*****************************************';
//どの twitter API
$url = 'https://api.twitter.com/1/statuses/update.json';
//POST or GET
$method = 'POST';
//パラメータ
$parameters = array('status' => 'テストのツイート');
//難しそうなところだけOAuth.phpにお願いする
$sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
$consumer = new OAuthConsumer($consumer_key, $consumer_secret);
$token = new OAuthConsumer($oauth_token, $oauth_token_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $parameters);
$request->sign_request($sha1_method, $consumer, $token);
//↑こうして出来上がった$requestから何でももらえる(リクエスト送信先、パラメータ、ヘッダ、署名 etc.)
//POSTリクエストはfile_get_contents()で十分可能
$options = array(
'http'=>array(
'method' => $request->get_normalized_http_method(),
'header' => array(
//Authorization: OAuth ... のヘッダ
$request->to_header(),
),
//oauth_*なパラメータを含めないで
'content' => OAuthUtil::build_http_query($parameters)
)
);
$context = stream_context_create($options);
$result = file_get_contents($request->get_normalized_http_url(), false, $context);
//例えば結果を確認してみる
var_dump($result);