Sunday, February 13, 2011

How to request OAuth TOKEN from Twitter in PERL

For us to be able to request for a token, the first thing you have to do is to register your application.

To register an app, access the Client Applications page of Twitter. Registering your application allows twitter to identify your application. Remember not to reveal your consumer secrets with anyone.

While creating an application, you will be asked whether your application is a client or browser application, choose browser for this post.



Client applications need not to enter a callback URL. In fact, web applications need not to supply a callback URL either, but as best practice, you should submit your oauth_callback_url on every token request, explicitly declaring what you want the callback to be. This will also be needed to identify the variables we need since we're doing it backend.

You will also be asked for an access type, choose "read and write" for you to be able to post tweet eventually.



After registering your application, you will have the 2 important details below.
  • Consumer Key
  • Consumer Secret
Once you have those details, we are now ready to do the coding part. Just follow the simple steps below and you will be able to retrieve a token from Twitter.

Please take note that this token is not yet ready to access twitter on users behalf. The returned token by this process will be use to AUTHORIZE "next to this oauth process" and ACCESS TOKEN "final oauth process".

1. Install the libraries you need.
  • LWP::UserAgent
  • HTTP::Cookies
  • Digest::MD5
  • Digest::SHA
  • POSIX

2. Initialize the following libraries.

require LWP::UserAgent;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);

my $lwpua = LWP::UserAgent->new;

3. Setup the UserAgent and HTTP header with the name "Authorization" equal to "OAuth".

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

4. Build the signature base and signing key. Please take note that some parameters should be URL Encoded, see the post for the PERL function that you can use - URLENCODE sub function in PERL.

You need the callback URL which you define during client registration, and the consumer key and secret which was generated by Twitter upon registration.

To generate NONCE, we use Digest::MD5::md5_base64() passing the localtime(). We do it twice to make it much UNIQUE.

Timestamp was generated by using POSIX::strftime() with date format UNIXTIME as "%s".

my $post_url = "https://api.twitter.com/oauth/request_token";
my $callback_url = "<your callback url define on client registration>";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $callback_urlenc = &urlencode($callback_url);
my $post_urlenc = &urlencode($post_url);

my $oauth_data = "oauth_callback=$callback_urlenc&oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_version=$version";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&";

5. Generate the OAuth Signature using HMAC-SHA1 method.

my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

6. Post an OAuth request with all the parameters you passed on step #4.

my $response = $lwpua->post($post_url,
                        ['oauth_callback' => $callback_url,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'oauth_version' => $version], @header);
my $form_data = $response->content;

7. Get the return value: oauth_token, oauth_token_secret, and oauth_callback_confirmed

$form_data =~ s/\n//g;
$form_data =~ /^oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $oauth_confirm = $3;


Hope you like it!! Please see the complete code below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

# build the signature base
my $post_url = "https://api.twitter.com/oauth/request_token";
my $callback_url = "http://flusso1.wolfpac.net/tweext/twitter.php";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "fy13RaNud7FQl1AVafzq9g";
my $consumer_secret = "3FHgsf5ychPlLPaDF7f1RRjJthU5rPMCPa9kpJbbpK4";

my $callback_urlenc = &urlencode($callback_url);
my $post_urlenc = &urlencode($post_url);

my $oauth_data = "oauth_callback=$callback_urlenc&oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_version=$version";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&";

# oauth signature
my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

# post oauth request
my $response = $lwpua->post($post_url,
                        ['oauth_callback' => $callback_url,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'oauth_version' => $version], @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /^oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $oauth_confirm = $3;

print "$oauth_token|$oauth_secret|$oauth_confirm\n";
print "done!";

sub urlencode
{
  my ($url) = @_;

  $url =~ s/([^A-Za-z0-9_.-])/sprintf("%%%02X", ord($1))/seg;
  return $url;
}


1;

4 comments:

  1. Your example almost works.. need a tiny tweak

    Set the keys without the quotes oauth_consumer_key instead of 'oauth_consumer_key'


    Thanks so much for this..

    ReplyDelete
  2. no worries, it should work with the quotes coz your setting it to an array element. thanks.

    ReplyDelete
    Replies
    1. Can you post an example for this https://api.twitter.com/1.1/statuses/user_timeline.json.

      this is a get request

      Delete
  3. Not sure if this still works coz it's been a long time already, but I posted about it. please go to this post - http://paulgonzaga.blogspot.com/2011/03/how-to-retrieve-your-twitter-feeds-in.html

    Hope it helps, thanks.

    ReplyDelete

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.