以前在google appengine上搭建过一个twitter api proxy(貌似叫birdnest ?),然后一直使用这个,无论是choqok看推发推,还是命令行curl来调用,都很好很和谐。可是后来twitter升级为oauth了,这个API代理就杯具了,一度导致我发推前还得开浏览器,无比烦恼。后来好像也还用过其他的api proxy程序,貌似也不好用。
一直琢磨着,是否该研究研究twitter oauth,自己给自己写个api proxy。刚好最近要学习php, 于是顺便看了看twitter推荐的oauth php库twitteroauth。代码下载回来后,还有个很详细的test.php——竟然这个库用起来无比简单!基本上只需要这样:
1 2 3 | $parameters = array('status' => 'new test status ...'); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET); $response = $connection->post('statuses/update', $parameters); |
而之前一直很纠结的oauth第一次要跳转到twitter验证的问题(没看那头疼的文档唉),忽然发现其实只是去获取token, token_secret罢了。于是直接预先填写到代码里(反正也只是我个人使用!),一切就简单方便了~~~
不过对于我这个php初学者来说,还有个问题。要想支持全部API代理(例如要给choqok用),写死’statuses/update’肯定是不行的。必然得用到url rewrite之类的。于是又研究了一下,发现可以这样写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function get_twitter_op(){ $doc = "^".$_SERVER['DOCUMENT_URI']; $uri = "^".$_SERVER['REQUEST_URI']; if (substr($doc, -1) !== "/") { $doc .= "$"; } else { $doc = substr($doc, 0, -1) . '$'; } $base_doc = str_replace('index.php$', '', $doc); $op = str_replace($base_doc, '', $uri); $op .= ".json"; return explode('.', $op); } |
上面的函数就是从 ‘/twitterapi/statuses/update.json’ 这样的请求串中截取出 ‘statuses/update’命令和’json’格式。php的代码技巧完全不懂,上面的代码肯定写得很烂。莫笑。
所以,总结起来,这个极简的twitter api proxy,就是这么写(twitteroauth库里的俩文件OAuth.php, twitteroauth.php放在include/下),保存成index.php就能使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <?php require('include/twitteroauth.php'); define('CONSUMER_KEY', 'SFtcUBB5IImkmpff2ezVg'); define('CONSUMER_SECRET', 'MXMSnSTJMgUYWEE1vMLy9tVqJHK6Bcoszlalal'); define('OAUTH_TOKEN', '112133312-lalalal'); define('OAUTH_TOKEN_SECRET', 'lalalala'); function get_twitter_op(){ $doc = "^".$_SERVER['DOCUMENT_URI']; $uri = "^".$_SERVER['REQUEST_URI']; if (substr($doc, -1) !== "/") { $doc .= "$"; } else { $doc = substr($doc, 0, -1) . '$'; } $base_doc = str_replace('index.php$', '', $doc); $op = str_replace($base_doc, '', $uri); $op .= ".json"; return explode('.', $op); } $response = "request method is not support."; $args = get_twitter_op(); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET); $connection->decode_json = false; $connection->format = $args[1]; if ($_SERVER['REQUEST_METHOD'] == 'GET'){ $response = $connection->get($args[0], $_GET); } else if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $response = $connection->post($args[0], $_POST); } echo $response; ?> |
我用的服务器是nginx, 搭配的rewrite规则是:
1 | if (!-e $request_filename){rewrite ^/toap/(.*)$ /toap/index.php last;} |
代码丢在了github上的项目toap里, apache的rewrite规则文件也在其中。

















