Labels

Thursday, December 8, 2011

Facebook Graph API cookbook page

Working with the Graph API

Overview

The graph API is a collection of RESTful web services facebook provides. Using the graph api, you can publish, interact with or create almost anything in facebook. Developers make GET, POST and DELETE requests to different parts of https://graph.facebook.com. These requests can require an access token, which grants read/write privileges.

Facebook provides a tool at https://developers.facebook.com/tools/explorer that lets users generate access tokens for their account with any combination of permissions and make graph api calls. Try using this tool to interact with your facebook accounts. You can read facebook’s graph api documentation here: https://developers.facebook.com/docs/reference/api/

Body

GETing https://graph.facebook.com/1206427506 (my facebook user id) with no access token returns this JSON:
{
 "id": "1206427506",
 "name": "Paul Kinsky",
 "first_name": "Paul",
 "last_name": "Kinsky",
 "link": "https://www.facebook.com/people/Paul-Kinsky/1206427506",
 "gender": "male",
 "locale": "en_US",
 "type": "user"
}

The same call with an access token granting the user_about_me privilege to my account returns this JSON:
{
 "id": "1206427506",
 "name": "Paul Kinsky",
 "first_name": "Paul",
 "last_name": "Kinsky",
 "link": "https://www.facebook.com/profile.php?id=1206427506",
 "hometown": {
   "id": "113001432047882",
   "name": "Wareham, Massachusetts"
 },
 "location": {
   "id": "105596609473837",
   "name": "Worcester, Massachusetts"
 },
 "gender": "male",
 "timezone": -5,
 "locale": "en_US",
 "languages": [
   {
     "id": "113301478683221",
     "name": "American English"
   }
 ],
 "verified": true,
 "updated_time": "2011-11-02T16:50:18+0000",
 "type": "user"
}




The facebook php sdk handles graph api calls with the Facebook::api() method.

$facebook->api('/me/feed', 'POST',
                                   array(
                                     'link' => 'www.example.com',
                                     'message' => 'Posting with the PHP SDK!'
                                ));

Graph API reference:



Components:
  1. $facebook
    1. a Facebook object initialized with your application’s APP_ID and APP_SECRET
  2. '/me/feed'
    1. the part of the facebook graph api to contact
    2. in this case, the feed of the current user
  3. ‘POST’
    1. the type of request
    2. in this case, we’re POSTing to the current user’s feed
  4. array(...)
    1. parameters specific to the graph api call
    2. in this case, we’re posting a link to 'www.example.com' and the message that we’re 'Posting with the PHP SDK!' to the currently logged in user’s feed, or news feed.





Here’s an example using this code from facebook’s documentation:


Example code

<?
 // Remember to copy files from the SDK's src/ directory to a
 // directory in your application on the server, such as php-sdk/
 require_once('php-sdk/facebook.php');


//These parameters can be viewed when you create your test app here: //https://developers.facebook.com/apps
 $config = array(
   'appId' => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',
 );

 $facebook = new Facebook($config);
 $user_id = $facebook->getUser();
?>
<html>
 <head></head>
 <body>

 <?
   if($user_id) {

     // We have a user ID, so probably a logged in user.
     // If not, we'll get an exception, which we handle below.
     try {
       $ret_obj = $facebook->api('/me/feed', 'POST',
                                   array(
                                     'link' => 'www.example.com',
                                     'message' => 'Posting with the PHP SDK!'
                                ));
       echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';

     } catch(FacebookApiException $e) {
       // If the user is logged out, you can have a
       // user ID even though the access token is invalid.
       // In this case, we'll get an exception, so we'll
       // just ask the user to login again here.
       $login_url = $facebook->getLoginUrl( array(
                      'scope' => 'publish_stream'
                      ));
       echo 'Please <a href="' . $login_url . '">login.</a>';
       error_log($e->getType());
       error_log($e->getMessage());
     }   
     // Give the user a logout link
     echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
   } else {

     // No user, so print a link for the user to login
     // To post to a user's wall, we need publish_stream permission
     // We'll use the current URL as the redirect_uri, so we don't
     // need to specify it here.
     $login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
     echo 'Please <a href="' . $login_url . '">login.</a>';

   }

 ?>      

 </body>
</html>

Facebook Auth cookbook page

Facebook Authentication

Overview

Most actions on Facebook require some sort of authentication token. For example, sending a request for information about a user without the relevant auth token returns only their public information: name, user id, and a few other fields. However, a request with the proper token can GET several pages of JSON describing a user who’s authorized the requesting app.

Body

There are several ways to acquire such a token, but we will be focusing on a simple method using the PHP SDK. Complete documentation can be found here.

First, working with the PHP SDK requires initializing an instance of the Facebook object with your App_ID and App_Secret. These values are unique to each app, and can be thought of as you username and password.

The Facebook::getLoginUrl(params) method generates a url that takes the user to a facebook dialouge where the user is asked if they would like to grant your application the permissions specified in params, after which the user is redirected to either a url specified in params or the originating page

From the documentation:
$params = array(
  scope => 'read_stream, friends_likes',
  redirect_uri => 'https://www.myapp.com/post_login_page'
);

$loginUrl = $facebook->getLoginUrl($params);

the scope parameter can be any of these permissions. Remember that requesting unnecessary permissions will make users suspicious.

The auth token obtained is temporary, meaning that this method can only be used when the user is online or shortly after.

There is also a Facebook::getLogoutUrl() method, see the example below for a full example (source)

Example Code

<?
 // Remember to copy files from the SDK's src/ directory to a
 // directory in your application on the server, such as php-sdk/
 require_once('php-sdk/facebook.php');

 $config = array(
   'appId' => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',
 );

 $facebook = new Facebook($config);
 $user_id = $facebook->getUser();
?>
<html>
 <head></head>
 <body>

 <?
   if($user_id) {

     // We have a user ID, so probably a logged in user.
     // If not, we'll get an exception, which we handle below.
     try {

       $user_profile = $facebook->api('/me','GET');
       echo "Name: " . $user_profile['name'];

     } catch(FacebookApiException $e) {
       // If the user is logged out, you can have a
       // user ID even though the access token is invalid.
       // In this case, we'll get an exception, so we'll
       // just ask the user to login again here.
       $login_url = $facebook->getLoginUrl();
       echo 'Please <a href="' . $login_url . '">login.</a>';
       error_log($e->getType());
       error_log($e->getMessage());
     }   
   } else {

     // No user, print a link for the user to login
     $login_url = $facebook->getLoginUrl();
     echo 'Please <a href="' . $login_url . '">login.</a>';

   }

 ?>

 </body>
</html>