Services_Twitterを使ってOAuth
すでにご存知のように、今年6月末2010/08/16*1でAPIのBASIC認証がサポートされなくなり、OAuthかxAuthのみになります。
で、非常に今更感漂いますが、PEAR::Services_Twitter+OAuthを使って、タイムラインを更新するアプリケーションを動作させるまでやってみたので、その手順をまとめてみました。
事前準備
1. アプリケーションが更新するアカウントでtwitterにログイン
2. Twitter Developer Platform — Twitter Developersの『Register an app』からアプリケーションを登録する。『Application Name』『Description』『Application Website』は必須。『Application Type』は"Client"、『Default Access type』は"Read & Write"にそれぞれ指定。
あとは、キャプチャの文字を入力して『Register application』をクリック。
3. アプリケーションを登録するとOAuthに必要なキーが発行されるので確認する。Consumer key、Consumer secretは、登録直後の画面(Application details)に表示される。
Access Token、Access Token Secretは、Application details画面の右にあるリンク『My Access Token』から確認する。
アプリケーションの作成とテスト
PEAR::Services_TwitterのAPIドキュメントにあるサンプルがまさにそのもの。HTTP_OAuth_Consumerクラスのコンストラクタに渡している4つの引数が、事前準備の最後に確認したキーになります。
<?php require_once 'Services/Twitter.php'; require_once 'HTTP/OAuth/Consumer.php'; try { $twitter = new Services_Twitter(); $oauth = new HTTP_OAuth_Consumer('consumer_key', 'consumer_secret', 'auth_token', 'token_secret'); $twitter->setOAuth($oauth); $msg = $twitter->statuses->update("test"); print_r($msg); } catch (Services_Twitter_Exception $e) { echo $e->getMessage(); }
これを実行し、次のように表示されれば、とりあえず成功です(設定によっては、Strictエラーが発生します)。
$ php oauth.php stdClass Object ( [contributors] => [coordinates] => [geo] => [in_reply_to_user_id] => [source] => <a href="http://www.doyouphp.jp/" rel="nofollow">shimooka_test</a> [user] => stdClass Object ( [statuses_count] => 11954 [profile_sidebar_border_color] => 87bc44 [url] => http://d.hatena.ne.jp/shimooka/ [description] => Do You PHP?の中の人 [favourites_count] => 114 [contributors_enabled] => [location] => 日本 [geo_enabled] => [notifications] => [profile_background_color] => 9ae4e8 [profile_image_url] => http://a1.twimg.com/profile_images/552708352/2905457_723594618_normal.jpg [time_zone] => Tokyo [lang] => en [verified] => [profile_text_color] => 000000 [screen_name] => shimooka [profile_background_image_url] => http://s.twimg.com/a/1273875281/images/themes/theme1/bg.png [profile_link_color] => 0000ff [protected] => [following] => [created_at] => Thu Apr 12 02:01:24 +0000 2007 [followers_count] => 775 [name] => Hideyuki Shimooka [profile_background_tile] => [profile_sidebar_fill_color] => e0ff92 [id] => 4279971 [utc_offset] => 32400 [friends_count] => 441 ) [in_reply_to_screen_name] => [created_at] => Thu May 27 04:32:10 +0000 2010 [favorited] => [truncated] => [id] => 14812753957 [place] => [in_reply_to_status_id] => [text] => test ) $
あとは、twitterからタイムラインが更新されているかどうかを確認しましょう。
まとめ
PEAR::Services_TwitterがOAuthに対応している、かなり楽に移行できるんじゃないかと思います。
あと、Access TokenとAccess Token Secretをどこで確認するのか分からなかったのは内緒です orz
追記(2010/05/27 18:55)
twitterのREST APIにはリクエスト数の制限があります(1時間あたり150リクエスト)。何らかのサービスを運営している場合、大量のリクエストを投げる可能性があると思いますが、その場合はホワイトリスト申請を行い、リクエスト数制限を緩和してもらう必要が出てくるでしょう。
申請が通れば、アカウントもしくはIPアドレス毎に1時間あたり2万リクエストまで可能になるようです。実際の手続きについては、次のエントリが参考になると思います。
追記2(2010/05/27 19:05)
このエントリでは触れなかったxAuthについてですが、こちらは事前にメールによる申請が必要となります。