Twitter関連PHPのOauthライブラリ「twitteroauth」の使用例
ローカルApache上でホームタイムラインを表示してみよう
2011/5/28
Twitterでは、PHP/Python/Rubyなど各プログラミング言語ごとにOAuthのサンプルを提供しています。 ここでは、PHP用のOAuthライブラリ「twitteroauth」を使用して、ローカルApache上で動作させ、認証ユーザーのホームタイムラインを表示する方法を説明します。
取得したホームタイムラインの各ツイートには、TwitterのWeb Intentsを使用して、返信、リツイート、お気に入りリンクを付けてみました。 星マークやRTマークの素材は、Twitter Image Resourcesで提供されているSprites Everythingを使用しています。
設置フロー
-
Twitterの開発者サイトにアクセス。
「Sign In」をクリックし、Twitterアカウントでログインします。 -
ログイン後、「Your Apps」をクリックします。
-
「Register a new app」をクリックし、Twitterへのアプリ登録を行います。
-
アプリ情報を登録します。【Register application】ボタンをクリックすると、規約が表示されますので、【I Accept】ボタンをクリック。
※アプリ名、アプリアイコンは、アプリの許可画面に表示されます。
項目 説明 Application Name アプリ名。 Description アプリの説明文 Application Website アプリの公開URLや、アプリのダウンロードページ。 Organization 組織名。作者名。 Application Type デスクトップアプリなら「Client」、Webアプリなら「Browser」を選択。 Callback URL ブラウザ上で認証後、アプリに戻るためのコールバックURL。プログラムからTwitterにトークンを投げる際、上書きできるので適当でもよいです。 Default Access type アプリが要求するアクセス権限を指定。
ホームタイムラインなどを取得するだけの取得専用なら「Read Only」、 ツイート投稿や更新を行うなど、読書+取得なら「Read & Write」、 読書+取得+DM操作をするなら「Read, Write & Private Message」を選択します。Application Icon アプリアイコンを指定します。アップロード可能な画像形式はGIF/JPEG/PNG。アップロード可能なファイルサイズは700KBまで。 -
アプリの登録が完了すると、Consumer keyとConsumer secretが発行されます。
-
twitteroauthフォルダ内の「config.php」にある定数「CONSUMER_KEY」「CONSUMER_SECRET」をアプリ登録時に取得した「Consumer key」と「Consumer Secret」に変更します。
定数「OAUTH_CALLBACK」には、callback.phpへのパスに変更します(アプリ登録時のコールバックURLはここで指定したものに上書きされます)。
twitteroauth/config.php<?php //アプリのConsumer key define('CONSUMER_KEY', '***************************'); //アプリのConsumer Secret define('CONSUMER_SECRET', ''***************************');'); // リダイレクト先URL define('OAUTH_CALLBACK', 'http://localhost/twitteroauth_c/callback.php');
-
Twitterで提供されているPHP用のOAuthライブラリ「twitteroauth」の最新版のソースコードをダウンロードします。
解凍後、ローカルApacheのhtdocs内にコピペします。
ここでは、htdocs直下(http://localhost/twitter_oauth/)においたものとします。index.phpとhtml.incの内容を下記に書き換えます。
twitteroauth/index.php<?php/* Load required lib files. */session_start();require_once('twitteroauth/twitteroauth.php');require_once('config.php');/* If access tokens are not available redirect to connect page. */if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) { header('Location: ./clearsessions.php');}/* Get user access tokens out of the session. */$access_token=$_SESSION['access_token'];/* Create a TwitterOauth object with consumer/user tokens. */$connection=new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);/* HOMETIMELINE [start] */$apiURL="http://api.twitter.com/1/statuses/home_timeline.json?count=100";$buf=$connection->OAuthRequest($apiURL,"GET",array("format"=>"json"));$buf=json_decode($buf, true);$s="";foreach($buf as $k=>$v){ if(!$v) continue; $tweetID=$v["id_str"]; $s.="<li>"; $s.="<a href='http://twitter.com/".$v["user"]["screen_name"]."' target='_blank'><img src='".$v["user"]["profile_image_url"]."'/></a>"; $s.="@<a href='http://twitter.com/".$v["user"]["screen_name"]."' target='_blank'>".$v["user"]["screen_name"]."</a> "; $s.=formatStr($v["text"]); $s.="<div>"; $s.="<span><a href='http://twitter.com/".$v["user"]["screen_name"]."/status/".$tweetID."' target='_blank'>".formatDate($v["created_at"])."</span></a>"; $s.="<span>".$v["source"]."から</span>"; $s.="<span class='favorite'><a href='http://twitter.com/intent/favorite?tweet_id=".$tweetID."' target='_blank'><b></b>お気に入り</a></span>"; $s.="<span class='retweet'><a href='http://twitter.com/intent/retweet?tweet_id=".$tweetID."' target='_blank'><b></b>リツイート</a></span>"; $s.="<span class='reply'><a href='http://twitter.com/intent/tweet?in_reply_to=".$tweetID."' target='_blank'><b></b>返信</a></span>"; $s.="</div>"; $s.="</li>";}function formatStr($str){ $pattern='/http:\/\/[0-9a-z_,.:;&=+*%$#!?@()~\'\/-]+/i'; $replace='<a href="$0" target="_blank">$0</a>'; return preg_replace ($pattern, $replace, $str);}function formatDate($dateStr){ $paste=strtotime($dateStr); $now=strtotime('now'); $diff=abs($paste - $now); $dd=floor($diff/(24*60*60)); $hh=floor($diff/(60*60)); $mm=floor($diff/60)-($hh*60); $ss=$diff % 60; if($dd>0) return $dd."日前"; elseif($hh>0) return $hh."時間前"; elseif($mm>0) return $mm."分前"; elseif($ss>0) return "いまさっき";//$ss."秒前";}$content="<h2>@<a href='http://twitter.com/".$_SESSION["access_token"]["screen_name"]."'>".$_SESSION["access_token"]["screen_name"]."</a>のホームタイムライン</h2>";$content.="<ul id='res'>".$s."</ul>";/* HOMETIMELINE [end] *//* Include HTML to display on the page */include('html.inc');
twitteroauth/html.inc<!DOCTYPE html> <html > <head> <title>Twitter OAuth in PHP</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <style type="text/css"> *,body { font-family:versana,sans-serif; line-height:1.5; font-size:12px; } body { margin:0; padding:20px; } a { color:#0099B9; } #res { margin:0; padding:0; list-style:none; border-top:1px solid #ccc; } #res li { background-color:#fff; margin:0; padding:10px 10px 10px 62px; list-style:none; display:block; position:relative; min-height:42px; height:auto!important; height:42px; font-size:13px; border-bottom:1px solid #ccc; } #res li:hover { background-color:#d3f7ff; } #res li img { display:block; width:32px; height:32px; margin:0; padding:1px; outline:1px solid #ccc; background:#fff; position:absolute; top:10px; left:10px; } #res li div { margin:5px 0; padding:0; font-size:11px; } #res li div span { margin:0 5px 0 0; padding:0; } #res li div span a b { display:inline-block; width:14px; height:14px; margin:0 8px 0 0; padding:0; background-color:transparent; background-image:url("sprite-icons.png"); background-repeat:no-repeat; background-position:0 0; } #res li div span.favorite a b {background-position:-32px 0;} #res li div span.favorite a b:hover {background-position:-48px 0;} #res li div span.reply a b {background-position:0 0;} #res li div span.reply a b:hover {background-position:-16px 0;} #res li div span.retweet a b {background-position:-176px 0;} #res li div span.retweet a b:hover {background-position:-192px 0;} </style> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> </head> <body> <div> <p>Twitterで提供されているtwitteroauthを使用して、ホームタイムラインを表示するサンプルです。</p> <p>参照:<a href='http://github.com/abraham/twitteroauth'>twitteroauth</a></p> <p>【Sign in with Twitter】ボタンをクリックすると、アプリのアクセス許可確認画面が表示されます。<br />【ログイン】ボタンをクリックすると、この画面上にあなたのホームタイムラインが表示されます。</p> <p><a href='./clearsessions.php'>セッションをクリアする</a> | <a href='https://twitter.com/settings/applications' target='_blank'>アプリの連携を解除する</a></p> <hr /> </div> <p><?php echo $content; ?></p> </body></html>
-
ローカルApache環境の「http://localhost/twitteroauth/」にアクセスし、Twitter認証&アプリのアクセス許可を行うと、ホームタイムラインが表示されます。
サーバーにアップした設置サンプル
2011/5/28
サーバー上にアップしたデモはこちら→DEMO
-
上記のリンクにアクセスし、【Sign in with Twitter】ボタンをクリックします。
-
Twitterサイトに飛び、左図のようなアプリのアクセス許可画面が表示されたら、【ログイン】ボタンをクリックします。
Twitter未ログインの場合は右図のようなTwitter認証が表示されます。 -
転送中画面が表示された後、アプリ側で設定したリダイレクトURL(アプリのトップ画面)に自動的に遷移します。
-
認証したユーザーのホームタイムラインが表示されます。
このアプリ連携を解除する場合は、Twitter公式サイトの設定にあるアプリ連携から許可の取り消しを行ってください。
