Get Access Token in Facebook API

Posted By: Matpal - March 11, 2011
Getting an access token in Facebook is very simple now. You need to do the following simple steps-

Step 1: Go to http://www.facebook.com/developers/createapp.php and create an App.


Step 2: Create a file connect.php

<?php

 $app_id = "<your app id>";
 $app_secret = "<your app secret>";
 $my_url = "<callback url>"; //For example http://localhost/myFbApp/callback.php

  $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$app_id . "&redirect_uri=".urlencode($my_url)."&scope=email,read_stream,publish_stream";
echo '<a href="'.$dialog_url.'">Connect To Facebook</a>';

?>

Step 3: Create a file callback.php where you'll get the access token. Using that access token you can access the services of Facebook Garph API. Here is the code of callback.php

<?php

$app_id = "<your app id>";

$app_secret = "<your app secret>";

$my_url = "<callback url>"; //For example http://localhost/myFbApp/callback.php



//You will get this from connect.php as a query parameter

$code = $_REQUEST["code"];



$token_url = "https://graph.facebook.com/oauth/access_token?client_id=". $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=". $app_secret . "&code=" . $code."&scope=email,read_stream,publish_stream";


//Access Token is here
$access_token = @file_get_contents($token_url);

$graph_url = "https://graph.facebook.com/me?" . $access_token;

//Access token can give you the details of current user  

$user = @json_decode(file_get_contents($graph_url));

print_r($user);

?>

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.