TwitterのOAuthClientを下記URLから設定
http://twitter.com/oauth_clients
consumer_keyとconsumer_secretを取得する。
おおまかな流れ
- index.html からリンクで sample.pl にアクセスし、Twitter の OAuth 許可用のページへリダイレクト
- OAuth 許可用のページで許否を設定後、sample.pl で設定した callback_url (ここ重要)へリダイレクトされる(この場合はcallback.pl)
- callback.pl で oauth_token と oauth_verifier を取得し update を試みる
- 成功であればツイート先へ、失敗であれば Twitter トップページにリダイレクト
コード例
sample.pl
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use lib '/home/foo/local/lib/perl5';
use OAuth::Lite::Consumer;
use URI;
use CGI;
use CGI::Carp qw/fatalsToBrowser/;
my $q = CGI->new();
my $consumer = OAuth::Lite::Consumer->new(
consumer_key => 'YOUR_CONSUMER_KEY',
consumer_secret => 'YOUR_CONSUMER_SECRET',
callback_url => 'http://example.com/callback.pl',
site => 'http://twitter.com/',
request_token_path => 'http://twitter.com/oauth/request_token',
access_token_path => 'http://twitter.com/oauth/access_token',
authorize_path => 'http://twitter.com/oauth/authorize',
);
my $request_token = $consumer->get_request_token();
my $uri = URI->new($consumer->{authorize_path});
$uri->query(
$consumer->gen_auth_query("GET", 'http://twitter.com', $request_token)
);
print $q->redirect($uri->as_string);
exit;
callback.pl
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use lib '/home/foo/local/lib/perl5';
use OAuth::Lite::Consumer;
use Encode;
use CGI;
use CGI::Carp qw/fatalsToBrowser/;
use URI;
my $q = CGI->new();
*OAuth::Lite::Util::encode_param = sub {
my $param = shift;
URI::Escape::uri_escape_utf8($param, '^\w.~-');
};
my $consumer = OAuth::Lite::Consumer->new(
consumer_key => 'YOUR_CONSUMER_KEY',
consumer_secret => 'YOUR_CONSUMER_SECRET',
site => 'http://twitter.com/',
request_token_path => 'http://twitter.com/oauth/request_token',
access_token_path => 'http://twitter.com/oauth/access_token',
authorize_path => 'http://twitter.com/oauth/authorize',
);
my $param_oauth_token = $q->param('oauth_token');
my $param_oauth_verifier = $q->param('oauth_verifier');
my $access_token = $consumer->get_access_token(
token => $param_oauth_token,
verifier => $param_oauth_verifier,
);
my $res = $consumer->request(
method => 'POST',
url => q{http://twitter.com/statuses/update.xml},
token => $access_token,
params => {
status => scalar localtime,
token => $access_token,
},
);
if ($res->is_success) {
use XML::Simple;
my $status = XMLin($res->decoded_content);
print $q->redirect(
"http://twitter.com/"
. $status->{user}->{screen_name}
. '/status/'
. $status->{id}
);
} else {
print $q->redirect('http://twitter.com');
}
exit;