Graph API & IFrame Base Facebook Application Development PHP SDK 3.0

Facebook recently updated their PHP-SDK to version 3.0. This is a major change. So I decided to update some of my facebook related tutorials with updated code.

At first I want to tell you that, this post is the updated version of my popular post Graph API & IFrame Base Facebook Application Development . So if you never saw that tutorial I request you to visit that and learn the basic things specially facebook application setup. Also on that post I mentioned some important things regarding iframe, so in this post I’ll not mention them again.

So in this updated post we will learn:

  1. How to update facebook php sdk 3.0 library
  2. Authentication
  3. How to give extended permissions
  4. How to call graph api
  5. How to publish stream using facebook’s latest dialog system
  6. How to request/invite your friends and track them

Before proceeding:

1. How to update facebook php sdk 3.0 library

First download Facebook’s php sdk and from the /src directory copy facebook.php, base_facebook.php and fb_ca_chain_bundle.crt to your project dir. Then download my codes from here, in this zip file you also get the php sdk libraries. Now click below image to know about the files functionality.

2. Authentication

In fbmain.php line number 23->77 you’ll see below code.

  • At first we include the facebook.php library.
  • Then we created a $facebook object
  • Then we check if there is a valid session for user by  $user = $facebook->getUser();
  • Then we generate login url with extended permission
  • At line number 62 we call graph api $user_profile = $facebook->api(‘/me’);    to check if session is valid or not. If we get result then user’s session is valid otherwise we set $user = null that means expired or timeout session.
  • If no valid $user found at line number 71 we redirect user to login/authentication page for our application.
$user            =   null; //facebook user uid
    try{
        include_once "facebook.php";
    }
    catch(Exception $o){
        echo '<pre>';
        print_r($o);
        echo '</pre>';
    }
    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId'  => $fbconfig['appid'],
      'secret' => $fbconfig['secret'],
      'cookie' => true,
    ));

    //Facebook Authentication part
    $user       = $facebook->getUser();
    $loginUrl   = $facebook->getLoginUrl(
            array(
                'scope'         => 'email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
            )
    );

    if ($user) {
      try {
        // Proceed knowing you have a logged in user who's authenticated.
        $user_profile = $facebook->api('/me');
      } catch (FacebookApiException $e) {
        //you should use error_log($e); instead of printing the info on browser
        d($e);  // d is a debug function defined at the end of this file
        $user = null;
      }
    }

    if (!$user) {
        echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
        exit;
    }

After user successfully authenticated our application facebook will redirect user to our callback url that we provided in the developer application setting. Facebook additionally pass a parameter named code=XXXX . But as this is a iframe application that runs inside facebook so we used a special code at line number 16->19. This code checks if there is GET parameter code is defined or not, if its defined then it redirects user to the facebook app url.

if (isset($_GET['code'])){
        header("Location: " . $fbconfig['appBaseUrl']);
        exit;
    }

3. How to give extended permissions

When you’ll generate the login url you’ve to provide extended permissions here. Previously the parameter named was ‘req_perms’ and now its ‘scope’.

 $loginUrl   = $facebook->getLoginUrl(
            array(
                'scope'         => 'email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
            )
    );

Checkout extended permission list from here.

4. How to call graph api

In fbmain.php line number 76, you’ll see how I called the graph api. Here $user is facebook user’s UID. To know more about graph api visit this page

//get user basic description
    $userInfo           = $facebook->api("/$user");

5. How to publish stream using facebook’s latest dialog system

In template.php line number 50->54 you’ll see the facebook’s javascript function. To know more about feed please visit here.

FB.ui({ method : 'feed',
                        message: userPrompt,
                        link   :  hrefLink,
                        caption:  hrefTitle
                      });

6. How to request/invite your friends and track them

So you want your user will invite his friends to use this application, and also you want to track to whom your user sends request. Also you want to check if that user is come from via request or not. In demo application click Send Request/Send Invitation to check the request dialog. In template.php line number 88 you’ll see this function.

function newInvite(){
                 var receiverUserIds = FB.ui({
                        method : 'apprequests',
                        message: 'come on man checkout my application. visit http://thinkdiff.net',
                 },
                 function(receiverUserIds) {
                          console.log("IDS : " + receiverUserIds.request_ids);
                        }
                 );
                 //http://developers.facebook.com/docs/reference/dialogs/requests/
            }

This function show a invite dialog and if user selects friends and sends invite, then in the response you’ll get all of user’s friends UIDs as a comma separated string. So if you use Firebug in Firefox, you’ll see console.log(“IDS : ” + receiverUserIds.request_ids); will print IDS: XXXX in the console of firebug. So if you want to track the friends IDS who received invitation, then parse receiverUserIds and save them in your mysql database.

If a user authenticate your application from invitation then his URL would be

http://apps.facebook.com/[app_name]/?request_ids=012345678910

So in fbmain.php line number 23->26 you’ll see below code. I just blank them you’ve to write additional code for tracking user.

if (isset($_GET['request_ids'])){
        //user comes from invitation
        //track them if you need
    }

I hope this tutorial will help you for developing facebook application.