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

No comments:

Post a Comment

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.