twitteroauth.phpとjQuery(ajax)を使ってTwitterに投稿する。
Webの通信のGETとPOSTのお勉強がてらやってみました。
- twitteroauth.phpの取得
abraham/twitteroauth · GitHub
こちらから最新の「twitteroauth.php」「OAuth.php」をダウンロード
Twitter Developers あたりから
-
- Consumer key
- Consumer secret
- Access token
- Access token secret
を取得しておきましょう。
- サンプルコード
実際にjQueryを利用したAjaxからデータを受け取って処理するサンプルソースはこちら。
「twitteroauth.php」「OAuth.php」と同じディレクトリに「twitter_post.php」を作成。
(セキュリティ云々は度外視)
<?php // twitter_post.php require_once("./twitteroauth.php"); // Consumer keyの値 $consumer_key = ""; // Consumer key $consumer_secret = ""; // Consumer secret $access_token = ""; // Access token $access_token_secret = ""; // Access token secret // OAuthオブジェクト生成 $to = new TwitterOAuth($consumer_key,$consumer_secret,$access_token,$access_token_secret); if (isset($_POST['tweet'])) { $req = $to->OAuthRequest( "http://api.twitter.com/1/statuses/update.xml", "POST", array( "status" => htmlspecialchars( $_POST['tweet'], ENT_QUOTES ) ) ); header("Content-Type: application/xml"); echo $req; exit(0); } ?>
HTMLはこちら
上記と同じディレクトリに「index.html」
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script> tweet_val = 'ここにツイート内容'; $(function() { $('#test').click(function(event){ $.ajax({ type: "POST", url: "tweet_post.php", data: "tweet=" + encodeURIComponent(tweet_val), success: function(data, dataType) { }, error: function(XMLHttpRequest, textStatus, errorThrown) { } }); }); }); </script> </head> <body> <input id="test" type="button" value="tweet" /> </body> </html>
これで「Tweet」ボタンを押すと、
ここにツイート内容
と、ツイートされます。
PHP側を頑張ってゴニョゴニョすると、Twitter APIの肩代わり出来るんじゃないかなぁ。
その辺誰かやってそうですけど。。。