Showing posts with label token. Show all posts
Showing posts with label token. Show all posts

Thursday, July 12, 2012

Freshbooks API Integration on PHP

This post will teach you how to integrate your website with Freshbooks API. There is actually two ways of integrating with Freshbooks, one is via OAuth and the other one is Token-Based method.

For the Token-Based method, this is very simple. You only need to compose an XML request, use your API url and Token from Freshbooks - http://developers.freshbooks.com, then use curl to execute the request. You can check out below on how I do it by calling create client and list clients request.

<?php

$apiurl = 'https://sample.freshbooks.com/api/2.1/xml-in';
$token = '<your token here>';

create_client($apiurl, $token);
list_clients($apiurl, $token);

function create_client($apiurl='', $token='') {
        $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
                <request method=\"client.create\">
                <client>
                        <first_name>Jane</first_name>
                        <last_name>Doe</last_name>
                        <organization>ABC Corp5</organization>
                        <email>janedoe@freshbooks.com</email>
                </client>
                </request>";

        $output = xml_request($apiurl, $token, $xmldata);
        var_dump($output);
}

function list_clients($apiurl='', $token='') {
        $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
                <request method=\"client.list\">
                        <folder>active</folder>
                </request>";

        $output = xml_request($apiurl, $token, $xmldata);
        var_dump($output);
}

function xml_request($apiurl='', $token='', $xmldata='') {
        $output = '';

        system("curl -u $token:X $apiurl -d '$xmldata'", $output);
        return $output;
}

?>


For the OAuth method, this is pretty much complex than the Token-Based method. Please see below on the implementation I did. I also use plaintext signature method, the same method I used on my previous post - Dropbox OAuth API Integration on PHP

The first and important thing we need to have is the App key and App secret which we will use for authentication. I believed you will need an approval from Freshbooks to be able to get this information.

Once we have these credentials, we are now ready to start the coding part.

To start with, since we will be posting request to API url, I created a function in doing post request. We will be using this for request token and access token process.

function post_request($url='', $param='') {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        // disable ssl verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        // submit post request parameters
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

        // getting response from server
        $output = curl_exec($ch);

        return $output;
}


Now we can start requesting for a token. On this request, we need the callback url for freshbooks to redirect after the authorization was made. Once we get the token, we will submit it to authorization url for users to authorize our application.

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// call request token here and pass the App key and App secret
request_token($key, $secret);

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
                $key = $this->data['key'];
                $secret = $this->data['secret'];
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url
        $url = "https://$key.freshbooks.com/oauth/oauth_request.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_callback=$callback";

        $output = $this->post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];



        // redirect to authorize url
        authorize($key);
}


After getting a token from request token url, we can redirect the users to authorize url with the oauth token we get from request token.

function authorize($key='') {
        $oauth_token = $_SESSION['oauth_token'];

        $url = "https://$key.freshbooks.com/oauth/oauth_authorize.php";
        $param = "oauth_token=$oauth_token";

        header("Location: $url?$param");
}


Once the user allow the application to access the users information, Freshbooks will redirect the users to the callback url we put in our request token function. The callback url should be our access token function to get the access token that we can use moving forward.

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// call access token request passing the App key and App secret parameters
access_token($key, $secret);

function access_token($key='', $secret='') {
        $oauth_token = ($_GET['oauth_token']) ? $_GET['oauth_token'] : $_SESSION['oauth_token'];
        $oauth_verifier = $_GET['oauth_verifier'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://$key.freshbooks.com/oauth/oauth_access.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_verifier=$oauth_verifier";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];
}


We need to save the oauth token and oauth token secret for api call. Please watch out for my next post, I'll be posting on how to do the API call using OAuth method. Check out below script for the full implementation of the freshbooks authentication.

<?php

session_start();

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// from callback
$oauth_token = $_GET['oauth_token'];
if ($oauth_token) {
        access_token($key, $secret);
} else {
        request_token($key, $secret);
}

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
                $key = $this->data['key'];
                $secret = $this->data['secret'];
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url
        $url = "https://$key.freshbooks.com/oauth/oauth_request.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_callback=$callback";

        $output = $this->post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        authorize($key);
}

function authorize($key='') {
        $oauth_token = $_SESSION['oauth_token'];

        $url = "https://$key.freshbooks.com/oauth/oauth_authorize.php";
        $param = "oauth_token=$oauth_token";

        header("Location: $url?$param");
}

function access_token($key='', $secret='') {
        $oauth_token = ($_GET['oauth_token']) ? $_GET['oauth_token'] : $_SESSION['oauth_token'];
        $oauth_verifier = $_GET['oauth_verifier'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://$key.freshbooks.com/oauth/oauth_access.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_verifier=$oauth_verifier";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        var_dump($_SESSION);
}

?>

Saturday, July 7, 2012

Dropbox OAuth API Integration on PHP

This post will teach you how to integrate with Dropbox OAuth using PHP platform. Please take note that I'm not using any library to perform this integration nor special coding or whatsoever.

This is basically built from scratch which I want to share with you all, who wish to integrate with Dropbox.

To start with, you need an API credentials which you can get by logging in to your Dropbox account and create an app on this url - https://www.dropbox.com/developers/apps

We need the credentials below to proceed:
  • App key
  • App secret
We also need to understand the 3 url's that we need to access to complete the authentication process as listed below.
The request token url will be use to get a token which will be use to authorize your app to access users information in their behalf.

The authorization url will be the page for users to allow our application to access the users credential.

The access token url will be use to get an access token which will be use to access users credentials in their behalf.

Another thing that we need to understand is how to create signature. We need this in performing oauth request.

For the sake of this post, we will use the PLAINTEXT signature method, which is the simplest signature method.

Once we have the credentials and the api url's, we are now ready to start by just following the simple steps below.

1. Lets request for a token from the request token url - https://api.dropbox.com/1/oauth/request_token. Since we are using plaintext signature method, the signature will be your app secret plus "%26". Please see below.

$key = '<your app key>';
$secret = '<your app secret>';
$timestamp = time();$nonce = md5(time());
$sig = $secret."%26";
$method = "PLAINTEXT";


2. Once we have all the parameters, lets compose the post request.

$url = "https://api.dropbox.com/1/oauth/request_token";
$param = "oauth_consumer_key=$key".
                "&oauth_signature_method=$method".
                "&oauth_signature=$sig".
                "&oauth_timestamp=$timestamp".
                "&oauth_nonce=$nonce".
                "&oauth_version=1.0";


3. Execute post request using curl, which is the basic command in performing post request.

$ch = curl_init();
           
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// submit post request parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// getting response from server
$output = curl_exec($ch);


4. Parse the output and you will get the "oauth_token" and "oauth_token_secret" below which will be use to perform authorization. You can save these information in your session so that you will retrieve it later when performing access token.

// parse the output
parse_str($output, $token);

// save to session
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['token_secret'] = $token['oauth_token_secret'];


5. From the step #4, we only need the "oauth_token" to request for authorization. For this process, we need to define our callback url in which Dropbox will redirect the users after allowing the access.

$oauth_token = $_SESSION['oauth_token'];
$callback = '<your callback url>';

$url = "https://www.dropbox.com/1/oauth/authorize";
$param = "oauth_token=$oauth_token".
                "&oauth_callback=$callback";

header("Location: $url?$param");


6. After the user allows our application, Dropbox will redirect the user to our callback url we specify on step #5. We need to submit post request to access token url with the parameter "oauth_token" from step #4. This will also require signature, the same way we did on request token process, but this time with extra parameter "oauth_token_secret" from step #4.

$oauth_token = $_SESSION['oauth_token'];
$token_secret = $_SESSION['token_secret'];

$key = '<your app key>';
$secret = '<your app secret>';
$timestamp = time();$nonce = md5(time());
$sig = $secret."%26".$token_secret;
$method = "PLAINTEXT";


7. Lets compose the url and parameter with "oauth_token" as part of the request.

$url = "https://api.dropbox.com/1/oauth/access_token";
$param = "oauth_consumer_key=$key".
                "&oauth_token=$oauth_token".
                "&oauth_signature_method=$method".
                "&oauth_signature=$sig".
                "&oauth_timestamp=$timestamp".
                "&oauth_nonce=$nonce".
                "&oauth_version=1.0";


8. Execute the post request using curl.

$ch = curl_init();
           
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// submit post request parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// getting response from server
$output = curl_exec($ch);


9. Parse the output and we will get an access token which we will use to do the api request. You can save these information in your database so that you won't need to request for authorization when doing api request.

// parse the output
parse_str($output, $token);

// save to session
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['token_secret'] = $token['oauth_token_secret'];


You can try the full script below I made with a live API account and a basic API request. I optimized the script as well for better coding.

<?php

session_start();

$key = 'vh096l7q9m5m8tv'; // put here your app key
$secret = 'omri1uakcak8zqz'; // put here your app secret

// from callback
$oauth_token = $_GET['oauth_token'];
if ($oauth_token) {
        access_token($key, $secret);
} else {
        request_token($key, $secret);
}

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/oauth/request_token";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        authorize();
}

function authorize() {
        $oauth_token = $_SESSION['oauth_token'];
        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url

        $url = "https://www.dropbox.com/1/oauth/authorize";
        $param = "oauth_token=$oauth_token".
                 "&oauth_callback=$callback";

        header("Location: $url?$param");
}

function access_token($key='', $secret='') {
        $oauth_token = $_SESSION['oauth_token'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/oauth/access_token";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        folders($key, $secret);
}

function folders($key='', $secret='') {
        $oauth_token = $_SESSION['oauth_token'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/metadata/dropbox";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = file_get_contents($url."?".$param);
        $jsondata = json_decode($output);

        foreach ($jsondata->contents as $contents) {
                echo $contents->path."<br/>";
        }
}

function post_request($url='', $param='') {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        // disable ssl verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        // submit post request parameters
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

        // getting response from server
        $output = curl_exec($ch);

        return $output;
}

?>


Thursday, May 17, 2012

Setting up a remember me functionality on your website

First we need to have a login page where to put the "remember me" check box to have an identifier whether the user wants to be remembered or not.

Second, we need to set the users table to store the remember me token which we will use to identify as to which user should be logged in.

Please take note that I used token which is another field rather than using the actual user id coz having a token that changes every time is much secure than having just a static id.

I will discuss below on how you can make it much secure.

Okay, once you have the above in placed, we are now ready to do the coding.

You need to capture those users that agrees to be remembered then call this function below. For the benefit of this post, I set the cookie to expire in 14 days.

<?php
 

if (!mysql_connect('localhost', 'mysql_user', 'mysql_password')) die("can't connect to db: ".mysql_error());

if (!mysql_select_db('database_name')) die("can't select db: ".mysql_error);

$user_id = '<your login user id>';

// call this function to set cookie and expiry time

set_remember($user_id);

// set cookie and expiry time
function set_remember($user_id=0) {
        $token = md5($user_id."-".date('YmdGis'));
        $expire = time() + (14 * 86400); // 14 days

        setcookie("remember_me_token", $token, $expire);

        $expire = date('Y-m-d', $expire);
        $return = update_user_token($user_id, $token, $expire);
}

// update users table for token and expiry time
function update_user_token($user_id=0, $token='', $expire='') {
        $sql = "UPDATE user_table SET token='$token)', expire='$expire' ".
               "WHERE user_id='$user_id'";

        $query = mysql_query($sql);
        return 1;
}

?>

$user_id is the id of the user who successfully logged in to your site. This will be used to generate a random token which we will set in our cookie and update the users table as well.

We will use the function of the PHP to set the cookie.

setcookie("your_cookie_variable", "your_cookie_value", "expiration_of_cookie");

Please take note that you have to make sure that the user be able to login with the right credential before you call the function "set_remember($user_id)".

After calling function, you can get the cookie value by calling $_COOKIE["your_cookie_variable"]; and in our example above, you can call it by this syntax $_COOKIE['remember_me_token'];

I just want to remind you that COOKIE is not like a SESSION that starts when the pages loaded, the COOKIE will store value in your computer, so you need to come up with a COMPLEX name to prevent hackers from hacking your site.

Okay, moving on, since we set our cookie to expire in 14 days, then we have to make the user to be remembered every time they login and extend the expiration accordingly.

To do that, we need to get the token value from the cookie, get the user_id from our database, then call again the function set_remember($user_id);. If there's no cookie available, then redirect the user to login page.

Please see below for the sample implementation.

<?php

if (!mysql_connect('localhost', 'mysql_user', 'mysql_password')) die("can't connect to db: ".mysql_error());

if (!mysql_select_db('database_name')) die("can't select db: ".mysql_error);

$cookie = get_cookie('remember_me_token');
if ($cookie) $user_id = get_user_id_by_cookie($cookie);

// go to login page if no value for user_id
if (!$user_id) header("http://mywebsite/user/login");

// function to get the user id from the cookie
function get_user_id_by_cookie($cookie='') {
        $sql = "SELECT user_id FROM user_table WHERE token='$cookie'";

        $query = mysql_query($sql);
        return mysql_result($query, 0, 0);
}

// call this function to renew token then set a new new expiry datetime
set_remember($user_id);

// set cookie and expiry time
function set_remember($user_id=0) {
        $token = md5($user_id."-".date('YmdGis'));
        $expire = time() + (14 * 86400); // 14 days

        setcookie("remember_me_token", $token, $expire);

        $expire = date('Y-m-d', $expire);
        $return = update_user_token($user_id, $token, $expire);
}

// update users table for token and expiry time
function update_user_token($user_id=0, $token='', $expire='') {
        $sql = "UPDATE user_table SET token='$token)', expire='$expire' ".
               "WHERE user_id='$user_id'";

        $query = mysql_query($sql);
        return 1;
}

?>


Hope this post helps a lot!! Thanks!!

Tuesday, February 15, 2011

How to post tweet using OAuth access Token in PERL

OAuth access Token was gain from my previous post - How to exchange requested Token for an access Token from Twitter in PERL

In posting a tweet, we will use the resource URL - http://api.twitter.com/1/statuses/update.json and the POST method.

Just follow the steps below to post tweet on users behalf.

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

2. Initialize the 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 consumer key and secret which was generated by Twitter upon registration.

You also need the Oauth Token and Secret which you get when exchanging the requested token for an access token.

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".

Signing key was generated by combining the 2 parameters: Consumer Secret and OAuth Token Secret delimited by ampersand "&"

my $strToken = "<your oauth access token>";
my $strSecret = "<your oauth access token secret>";
my $strStatus = "<your tweet>";

my $post_url = "http://api.twitter.com/1/statuses/update.json";
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 $post_urlenc = &urlencode($post_url);
my $status_enc = &urlencode($strStatus);

my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_version=$version&status=$status_enc";
my $oauth_dataenc = &urlencode($oauth_data);

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

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_token' => $strToken,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'status' => $strStatus,
                         'oauth_version' => $version], @header);

print $response->content;

7. To know if successful, you can print the response and it should be look like this.

{
    "geo":null,
    "created_at":"Mon Apr 26 23:45:50 +0000 2010",
    "in_reply_to_user_id":null,
    "truncated":false,
    "place":null,
    "source":"&lt;a href=\"http://dev.twitter.com\" rel=\"nofollow\"&gt;OAuth Dancer&lt;/a&gt;",
    "favorited":false,
    "in_reply_to_status_id":null,
    "contributors":null,
    "user":
    {
        "contributors_enabled":false,
        "created_at":"Wed Mar 07 22:23:19 +0000 2007",
        "description":"Reality Technician,
         Developer Advocate at Twitter,
         Invader from the Space.",
        "geo_enabled":true,
        "notifications":false,
        "profile_text_color":"000000",
        "following":false,
        "time_zone":"Pacific Time (US &amp; Canada)",
        "verified":false,
        "profile_link_color":"731673",
        "url":"http://bit.ly/5w7P88",
        "profile_background_image_url":"http://a3.twimg.com/profile_background_images/19651315/fiberoptics.jpg",
        "profile_sidebar_fill_color":"007ffe",
        "location":"San Francisco,
         CA",
        "followers_count":1220,
        "profile_image_url":"http://a3.twimg.com/profile_images/836683953/zod_normal.jpg",
        "profile_background_tile":true,
        "profile_sidebar_border_color":"bb0e79",
        "protected":false,
        "friends_count":1275,
        "screen_name":"episod",
        "name":"Taylor Singletary",
        "statuses_count":5733,
        "id":819797,
        "lang":"en",
        "utc_offset":-28800,
        "favourites_count":89,
        "profile_background_color":"000000"
    },
    "in_reply_to_screen_name":null,
    "coordinates":null,
    "id":12912397434,
    "text":"setting up my twitter \u79c1\u306e\u3055\u3048\u305a\u308a\u3092\u8a2d\u5b9a\u3059\u308b"
}


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 signature base
my $strToken = "<your oauth access token>";
my $strSecret = "<your oauth access token secret>";
my $strStatus = "<your tweet>";

my $post_url = "http://api.twitter.com/1/statuses/update.json";
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 $post_urlenc = &urlencode($post_url);
my $status_enc = &urlencode($strStatus);
my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_version=$version&status=$status_enc";
my $oauth_dataenc = &urlencode($oauth_data);

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

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

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

print $response->content;



1;

Monday, February 14, 2011

How to exchange a requested TOKEN for an access TOKEN from Twitter in PERL

Finally, we're here at the last part of OAuth process, exchanging the requested token for an access token. I assume you were able to follow my last 2 posts below.
To get an access token, we need the OAuth Token, and Verifier from the previous post.

Just follow the simple steps below to gain an access token which we will use to access Twitter API in users behalf. This is likely the same when requesting a token, the only difference are the parameters we pass on.

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

2. Initialize the libraries

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;

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 consumer key and secret which was generated by Twitter upon registration.

You also need the Oauth Token and Verifier which you get when authorizing the requested token.

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".

# build signature base
my $strToken = "<your oauth token>";
my $strVerifier = "<your oauth verifier>";

my $post_url = "https://api.twitter.com/oauth/access_token";
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 $post_urlenc = &urlencode($post_url);

my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_verifier=$strVerifier&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_token' => $strToken,
                         'oauth_verifier' => $strVerifier,
                         '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, user_id, and screen_name

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

my $oauth_token = $1;
my $oauth_secret = $2;
my $user_id = $3;
my $screen_name = $4;


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

#!/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 signature base
my $strToken = "<your oauth token>";
my $strVerifier = "<your oauth verifier>";

my $post_url = "https://api.twitter.com/oauth/access_token";
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 $post_urlenc = &urlencode($post_url);
my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_verifier=$strVerifier&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_token' => $strToken,
                         'oauth_verifier' => $strVerifier,
                         '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=(.*?)&user_id=(.*?)&screen_name=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $user_id = $3;
my $screen_name = $4;

print "$oauth_token|$oauth_secret|$user_id|$screen_name\n";
print "done!";


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

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



1;

How to authorize OAuth TOKEN from Twitter in PERL

I assume you read my previous post - How to request OAuth TOKEN from Twitter in PERL before reading this post. You need the OAuth Token and Secret to proceed to this process.

On this post, we will login to twitter via back-end, please see post - Login to Twitter via backend using PERL on how to do it. Once the user had been logged in, we will authorize our application to post tweet and access users information in users behalf.

This post will outputted an OAuth Token and Verifier which you will use to Access Token "final oauth process" to get the OAuth Token and OAuth Secret.

Follow the simple steps below to authorize your application.

1. Install the following libraries.
  • LWP::UserAgent
  • HTTP::Cookies

2. Initialize the libraries.

require LWP::UserAgent;
use HTTP::Cookies;
my $lwpua = LWP::UserAgent->new;

3. Setup UserAgent, HTTP Header, and Cookies.

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);

my $cookie_file = "/home/wapps/tweext/cookies/twitter/cookies.$intMsisdn.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

my $lwpua->cookie_jar($cookie_jar);

4. Post the OAuth Token with Username and Password to authorize URL - https://api.twitter.com/oauth/authorize

my $strToken = "<your oauth token>";
my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";

my $response = $lwpua->post("https://api.twitter.com/oauth/authorize",
                          ['oauth_token' => $strToken,
                           'session[username_or_email]' => $strUser,
                           'session[password]' => $strPass], @header);
my $cookie_jar->extract_cookies( $response );
my $cookie_jar->save;

$form_data = $response->content;

5. Get the OAuth Token and Oauth Verifier from the output returned by step #4.

$form_data =~ s/\n//g;
$form_data =~ /meta http-equiv="refresh" content="0;url=(.*?)\?oauth_token=(.*?)&oauth_verifier=(.*?)"/ig;

my $oauth_token = $2;
my $oauth_verif = $3;

unlink($cookie_file);



1;


Please see the complete code below. Thank you for reading this post.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

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);

my $cookie_file = "/home/wapps/tweext/cookies/twitter/cookies.$intMsisdn.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

my $lwpua->cookie_jar($cookie_jar);

my $strToken = "<your oauth token>";
my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";

my $response = $lwpua->post("https://api.twitter.com/oauth/authorize",
                          ['oauth_token' => $strToken,
                           'session[username_or_email]' => $strUser,
                           'session[password]' => $strPass], @header);
my $cookie_jar->extract_cookies( $response );
my $cookie_jar->save;

$form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /meta http-equiv="refresh" content="0;url=(.*?)\?oauth_token=(.*?)&oauth_verifier=(.*?)"/ig;

my $oauth_token = $2;
my $oauth_verif = $3;

unlink($cookie_file);



1;

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;

Tuesday, January 18, 2011

How to post facebook status using OAuth with permanent TOKEN via backend in PERL and PHP

This post will teach you how to post facebook status using OAuth process via back-end. This is actually a revised version of the script I made on my previous post How to submit facebook status via back-end using PERL but instead of saving the users credentials, you just need to save the token which we get from the OAuth process.

You just need to have a web server coz facebook OAuth will require application to have a site URL as to be the callback URL in passing information. just for the sake of our testing we can use our local domain.

Just follow the simple steps below and we will be able to submit facebook status via back-end using OAuth process the "LEGAL WAY".

1. Same with my previous post, you should register your application on facebook - http://www.facebook.com/developers/createapp.php again, type in the application name and other details then once created, modify the site URL under web site tab.

2. Once you have the 3 details such as: app ID, app Secret, and site URL. we can now start coding the authorization script which will request permission for our app to do the status update.

app ID - 182635521758593
app Secret - 495625ad928ea277548d0f423f420ef0
site URL - http://localhost/facebook/

3. Since we're using PERL, you have to install the following libraries needed to run the script.
  • LWP::UserAgent;
  • HTTP::Cookies;
4. After installing the libraries, initialize UserAgent and Cookies to do HTTP request. please see below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

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

my $user_agent = "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' => 'http://m.facebook.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

5. Login to the wap site via the URL - http://m.facebook.com/login.php then save the cookies.

my $strUser = '<your facebook username/email>';
my $strPass = '<your facebook password>';
my $strStatus = '<your facebook status>';

# login to facebook
my $response = $lwpua->post('http://m.facebook.com/login.php',
                      ['email' => $strUser,
                       'pass' => $strPass,
                       'login' => 'Login'], @header);
$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

6. Request for permission to post facebook status with the app ID, and site URL of your application where app ID being the "app_id" parameter and site URL being the "next" parameter. just for this testing, we can use the application "Hotshots Point Of View". the application details are stated on step no. 2.

$response = $lwpua->get('http://m.facebook.com/connect/uiserver.php?app_id=182635521758593&method=permissions.request&display=wap&next=http%3A%2F%2Flocalhost%2Ffacebook%2F&response_type=code&fbconnect=1&perms=user_photos%2Cuser_videos%2Cpublish_stream', @header);

7. Get the $response->content and parse the "form action", "post_form_id", and "fb_dtsg" via REGEX implementation below. take note that this might change as the facebook wap changes. take note as well that the $response->content might not return as expected if the user already allow the application. hence, the $response->content will be the return output of your callback or site URL. if this is the first time that the user will allow the application, expect a return page with the details we need below.

my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /form id="uiserver_form" action="(.*?)"(.*?)name="post_form_id" value="(.*?)"(.*?)name="fb_dtsg" value="(.*?)"/ig;

my $form_action = $1;
my $form_id = $3;
my $form_fbdtsg = $5;

8. Once we have the "form action", "post_form_id", and "fb_dtsg", we can now trigger user to allow our application. please see below with other details we have from step no. 2, then clear the cookies by unlink() function.

$response = $lwpua->post('http://m.facebook.com/connect/uiserver.php',
                           ['fb_dtsg' => $form_fbdtsg,
                            'post_form_id' => $form_id,
                            'app_id' => '182635521758593',
                            'display' => 'wap',
                            'redirect_uri' => 'http://localhost/facebook/',
                            'response_type' => 'code',
                            'fbconnect' => '1',
                            'perms' => 'user_photos,user_videos,publish_stream',
                            'from_post' => '1',
                            '__uiserv_method' => 'permissions.request',
                            'grant_clicked' => 'Allow'], @header);

$form_data = $response->content;
unlink($cookie_file);

9. Okay, we are just halfway there.. now that we are able to allow the app to update facebook status, next step will be the script to post facebook status, but before that, here is the complete code of the PERL script as detailed on the steps above.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

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

my $user_agent = "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' => 'http://m.facebook.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = '<your facebook username/email>';
my $strPass = '<your facebook password>';

# login to facebook
my $response = $lwpua->post('http://m.facebook.com/login.php',
                      ['email' => $strUser,
                       'pass' => $strPass,
                       'login' => 'Login'], @header);
$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('http://m.facebook.com/connect/uiserver.php?app_id=182635521758593&method=permissions.request&display=wap&next=http%3A%2F%2Flocalhost%2Ffacebook%2F&response_type=code&fbconnect=1&perms=user_photos%2Cuser_videos%2Cpublish_stream', @header);

my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /form id="uiserver_form" action="(.*?)"(.*?)name="post_form_id" value="(.*?)"(.*?)name="fb_dtsg" value="(.*?)"/ig;

my $form_action = $1;
my $form_id = $3;
my $form_fbdtsg = $5;

$response = $lwpua->post('http://m.facebook.com/connect/uiserver.php',
                           ['fb_dtsg' => $form_fbdtsg,
                            'post_form_id' => $form_id,
                            'app_id' => '182635521758593',
                            'display' => 'wap',
                            'redirect_uri' => 'http://localhost/facebook/',
                            'response_type' => 'code',
                            'fbconnect' => '1',
                            'perms' => 'user_photos,user_videos,publish_stream',
                            'from_post' => '1',
                            '__uiserv_method' => 'permissions.request',
                            'grant_clicked' => 'Allow'], @header);

$form_data = $response->content;
unlink($cookie_file);



1;

10. Succeeding steps will then teach you how to submit facebook status in PHP which was triggered by facebook upon allowing our application. if you notice on our authorize URL on step no. 6, we set the "next" parameter to be the same as the value of our facebook app site URL. the "next" parameter will be used by facebook to return the CODE which we can exchange for a TOKEN that we will be using to post facebook status. please see below authorize URL from step no. 6.

http://m.facebook.com/connect/uiserver.php?app_id=182635521758593&method=permissions.request&display=wap&next=http%3A%2F%2Flocalhost%2Ffacebook%2F&response_type=code&fbconnect=1&perms=user_photos%2Cuser_videos%2Cpublish_stream

11. In back-end, the URL below was executed by our PERL script but if this link was clicked by the user, the user will be redirected to the page where in our facebook application is requesting for permission to post facebook status on users profile. if the user will allow it, facebook will then redirect it to the "next" parameter we specify on the URL above. please see facebook redirection URL format below.

http://localhost/facebook/?code=...

12. Your index page should be able to capture the CODE parameter returned by facebook and exchange it with TOKEN on the access token URL below then parse the return data to get the TOKEN. again, app ID will be the "client_id" parameter, site URL will the "redirect_uri" parameter, and the app Secret will be the "client_secret" parameter.

$code = $_GET['code'];
$oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=182635521758593&redirect_uri=http://localhost/facebook/&client_secret=495625ad928ea277548d0f423f420ef0&code=$code";

$url_handler = fopen("$oauthurl", 'r');
$url_contents = stream_get_contents($url_handler);
fclose($url_handler);

$ret = explode("&", $url_contents);
$token = preg_replace('/^access_token=/', '', $ret[0]);

13. Once you have the TOKEN, you will now be able to post facebook status using CURL. please see below implementation.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/me/feed');
curl_setopt($ch, CURLOPT_POSTFIELDS,'access_token='.urlencode($token).'&message='.urlencode($status));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_setopt($ch, CURLOPT_REFERER, "http://m.facebook.com");
$page = curl_exec($ch);

14. Please take note that the TOKEN you just pulled from facebook is NOT yet permanent. Hence, you need to call another access token with the parameter grant_type=client_credentials.

$oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=182635521758593&client_secret=495625ad928ea277548d0f423f420ef0&grant_type=client_credentials";

$url_handler = fopen("$oauthurl", 'r');
$url_contents = stream_get_contents($url_handler);
fclose($url_handler);

$ret = explode("&", $url_contents);
$token = preg_replace('/^access_token=/', '', $ret[0]);

15. Please see below for the complete PHP script.

<?

$status = "damn!! i'm good!! i was able to crack facebook oauth process via backend using perl and php! - http://paulgonzaga.blogspot.com";

$code = $_GET['code'];

if ($code) {
        // get access token
        $oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=182635521758593&redirect_uri=http://localhost/facebook/&client_secret=495625ad928ea277548d0f423f420ef0&code=$code";

        $url_handler = fopen("$oauthurl", 'r');
        $url_contents = stream_get_contents($url_handler);
        fclose($url_handler);

        $ret = explode("&", $url_contents);
        $token = preg_replace('/^access_token=/', '', $ret[0]);

        if ($token) {
                // get user info
                $infourl = "https://graph.facebook.com/me?access_token=$token";
                $url_handler = fopen("$infourl", 'r');
                $return = json_decode(stream_get_contents($url_handler));
                fclose($url_handler);

                $userid = $return->id;
                $name = $return->name;
                $fname = $return->first_name;
                $mname = $return->middle_name;
                $lname = $return->last_name;
               
                $oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=182635521758593&client_secret=495625ad928ea277548d0f423f420ef0&grant_type=client_credentials";

                $url_handler = fopen("$oauthurl", 'r');
                $url_contents = stream_get_contents($url_handler);
                fclose($url_handler);

                $ret = explode("&", $url_contents);
                $token = preg_replace('/^access_token=/', '', $ret[0]);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/$userid/feed');
                curl_setopt($ch, CURLOPT_POSTFIELDS,'access_token='.urlencode($token).'&message='.urlencode($status));
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
                curl_setopt($ch, CURLOPT_REFERER, "http://m.facebook.com");
                $page = curl_exec($ch);
        }
}

?>

Save the USERID and TOKEN for succeeding facebook status. Hope you like it!! Enjoy!! yeah men!! - http://paulgonzaga.blogspot.com

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.