Tuesday, April 2, 2013

get the access token and extend its lifetime for your app

1. the basic idea is : use your 'state' get 'code', then use 'code' get 'access_token', finally use current access_token to get the 60-day long access-token. thus, even the user is not logged into  facebook, you can still access his data:

<?php 
  
   $app_id = "YOUR_APP_ID";
   $app_secret = "APP_SECRET";
   $my_url = "YOUR_URL";
   session_start();
  
   $code = $_REQUEST["code"];
   if(empty($code)) {
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
     $dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . $_SESSION['state'] . "&scope=user_birthday,user_hometown, read_stream, friends_likes, email, user_status, publish_stream, status_update,offline_access";
     header("Location: " . $dialog_url);
  }
  
   if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;
     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     $_SESSION['access_token'] = $params['access_token'];
     $graph_url = "https://graph.facebook.com/me/feed?access_token="
       . $params['access_token'];
     $user = json_decode(file_get_contents($graph_url),TRUE);//get all the data related with 'feed'
  echo "</br>";
  echo "<h3>Your infomation are:</h3>";
  echo "</br>";
  print_r($user);
  echo "</br>";
  echo "</br>";
   }
   else {
     echo("The state does not match. You may be a victim of CSRF.");
   }

 ?>


2. use the short-term token to get the 60-day access token

<?php
 $my_token_url="https://graph.facebook.com/oauth/access_token
    grant_type=fb_exchange_token&          
    client_id=YOUR_APP_ID&
    client_secret=YOUR_APP_SECRET&
    fb_exchange_token=YOUR_CURRENT_ACCESS_TOKEN";

 header("Location: " . $my_token_url);

?>

If your current token is not expired yet, you are likely to get the same token but with longer life(60 days) you can also see how long it will last every time you refresh the page.

1 comment:

  1. This code is total junk. For example: "if(emptyempty($code)) { "

    Why do people with crap code get such high SERPS?

    ReplyDelete