NOTE: This post was written using Facebook’s PHP SDK version 2.1.2. Since this post was made, the PHP SDK has changed and some of the process that are explained below may have changed as well. At some point I’ll have to revisit this post and update it but at this time just keep in mind of the above.

As promised, here is a post (similar to my Twitter API post) on using the Facebook API. There are many reason why one would want to access the Facebook API – maybe to create a mobile app that lets you post photos to your Facebook albums, or maybe you just want to show your last few Facebook status updates on your blog; what ever the reason may be, Facebooks Graph API mixed in with their PHP SDK makes it really easy to accomplish this.

Objectives

  • Setup our environment
  • Register an app on Facebook
  • Understand the authentication process and extended parameters
  • Understand Graph API
  • Retrieve our latest status updates
  • Add a new status update
  • Retrieve our photos from our albums
  • Add a new photo

Setup our Environment

You have two options here, you can access my github and download this project with all required files and library or you can follow this tutorial step by step – it’s really up to you. If you want to download all the files ahead of time, you can get them at this github repo. If you are going step by step, first create a folder (I’m calling mine facebook) in your server where you want this site, next create a folder named library in the root of this site, and finally add the following two files facebook.php and fb_ca_chain_bundle.crt in the library folder that you can get from the Facebook PHP SDK repo at: https://github.com/facebook/php-sdk/tree/master/src/.

Register an App on Facebook

I’m making the assumption you already have a facebook account and if you don’t, first create one. To create an app on Facebook, you first need to confirm your account by giving Facebook a phone number where they can send you a code. This may be a new process since I don’t remember having to do this a few months ago. Go to http://developers.facebook.com/setup and if your account is not verified, you’ll be prompted to add the information mentioned above. After verifying your accout, you’ll be taken to the ‘Create an Application’ page.

Create App

This is what the page should look like

Simply give your site a name and type in your site’s url and click create app. In my case I’m calling my app ‘Blog Test’ and my site would be ‘http://www.joeyrivera.com/’. Next you will be prompted to type in a captcha and continue. Now you are done setting up your app, you see a screen like the following with your app id and app secret:

App Created

Here is your app info

Authenticating and Extended Parameters

Facebook uses OAuth for authenticating involving tokens being send back and forth but we don’t have to concern ourselves with the details – the Facebook PHP SDK does it all for us. It makes sure to send all the required information in the proper format so Facebook gets what it needs and sends us back what we need. You can read more about authenticating with Facebook at their site and you can also read my Twitter API post that discusses the OAuth in a little more detail if you are interested. The SDK also takes care of handling all API calls for us so we only have to give it the resource we are trying to access, let it know if we want to do a get or post, and finally give it all the parameters required for the call.

Extended Parameters is an interesting way of restricting access to an app (I’m using the term app to describe what we are building here) through the API. Unless a user allows access to certain parts of their account, an app will not be able to modify nor read parts of the account even if they are authenticated. Extended Parameters need to be explicitly assigned at the point of authenticating. When the user is taken to Facebook and asked to allow access to their account, the user is also presented with all the various parts of their account this app wants to interact with. Here is an example of what the user will see when trying to authenticate with our app:

Extended Permissions

The first one in the screen shot is the default requested permission to access all the users basic information. The other three we need to accomplish our goals set including: read and post status updates as well as view and post photos. Here you can see a complete list of all the available extended permissions. If you access that link, you’ll see there are a lot of permissions. I recommend taking some time reading through their descriptions to get a better understanding of the kinds of things you can do with the API. There have been times where I’ve tried to do something with an app and the Facebook Graph API without success only to find out I hadn’t requested a required permission for that to work.

Time for code, what we are about to do is to create an array with our app id and app secret to feed to the Facebook class when we instantiate it. Next, we are going to check to see if we are authenticated and if not, redirect us to the Facebook authenticate page passing it the extended parameters we want access to. Below is the code for the config.php file. Download form my repository or create the file below on the root of your site:

config.php

require_once ‘library/facebook.php’;

$app_id = "yourappid";
$app_secret = "yourappsecret";

$facebook = new Facebook(array(
        ‘appId’ => $app_id,
        ‘secret’ => $app_secret,
        ‘cookie’ => true
));

if(is_null($facebook->getUser()))
{
        header("Location:{$facebook->getLoginUrl(array(‘req_perms’ => ‘user_status,publish_stream,user_photos’))}");
        exit;
}

Make sure to update the app_id and app_secret variables with the information you received from Facebook after registering your app. Let me give you a quick explanation of the code. First we include the facebook.php file that we downloaded from the Facebook PHP SDK github repository. Then we instantiate a facebook instance passing it the app id, app secret, and tell it to use cookies to store the session/token information after authenticating. Next we call getUser() to see if we are already authenticated – null means we are not, else we receive the users id. If we are not authenticated, we redirect the user to Facebook to authenticate. The url is provided to us from the getLoginUrl method. We are sending that method an array with a key req_perms (required permissions) and the value is a comma delimited list of all the extended permissions we want access to. Again, a complete list of all permissions can be found at Facebooks docs.

Go ahead and try to access this page in your browser. You should be immediately redirected to Facebook. If you are not already logged in with your Facebook account, you’ll first be asked to log in with the user which you want your app to access. Next you’ll see the ‘Request for Permission’ page, click allow and you’ll be taken back to the config.php page on your server. This process takes you back to the page which initiated the authentication which was the config.php page. We have now successfully authenticated with Facebook.

In testing your app, you may decide you need more or less extended permissions. While you are authenticated with Facebook and have your token stored in a cookie, you won’t be able to re-authenticate using this code since you’ll be getting a User object back so you have a few options: You can close your browser, clear cookies, and authenticate again after modifying your code; You can force another echo or header redirect to the getLoginUrl() again with the new parameters; or you can log into your Facebook account (the user you authenticated), click on account on the top right, privacy settings, and in the bottom left you’ll see application and websites, click on edit your settings. Under applications you use, you should see your app listed, click on edit settings. Finally click on the ‘x’ delete button to delete your app from the list. This will now remove your app from this users app list and won’t allow the app to access this account until the user authenticates again.

Graph API

This was confusing to me at first, specially since I keep rushing my project instead of taking my time to carefully look and read over the documents to truly understand what’s going on. Here is the Facebook Graph API overview if you would like to read that first but I’ll try to summarize it here. Graph API allows you to call various resources all of which will be returned to you as JSON objects. You’ll have to spend some time at the Graph API References page to understand the different objects available, parameters they have, and what the required extended permissions are to access them. I’ll try to explain connections in a sec.

Lets talk about the User object first. If you look at the reference page for user, you’ll see that to call the user object (the user who is authenticated by the app) you would call the graph api url with a ‘/me’ at the end. If the call is made successfully, you’ll receive a JSON object with all the possible properties defined in the reference page (if they are set). Here is a quick example.

user.php

require_once ‘config.php’;
$me = $facebook->api(‘/me’);
var_dump($me);

If you run this code you get something like this:

User Object

This is my user object and properties.

Once you have the object, you can access it’s properties or do what you need with it. Now I’ll try to explain connections. If you look at the user reference page again and scroll down, you’ll see a connections section. These are the objects you can get that belong to this user. To access those objects you would call the url /me/object you want. For example, if you want to get this users albums, you would call /me/albums and this would return an array of album objects but remember to meet the required permission. For your app to access /me/albums, you need the user_photos extended permission (which we set in our config.php file).

So a connection is just a bridge between one object an another. Another example would be lets say we do as we did above and get all the users albums. Now we want to see all the photos inside each album. If you look at the album object, you’ll notice that under connections is photos which returns an array of photo objects. That is what we would call to get all the photos in that album for each album and you’ll see the code to do just this later on.

Get Status Posts

Create the following page and I’ll explain the code below.

status.php

require_once ‘config.php’;

// show statuses
$statuses = $facebook->api(‘/me/statuses’);
foreach($statuses[‘data’] as $status)
{
        echo $status["message"], "<br />";
}

First include the config.php file we created earlier (you’ll include this in all the other pages as well). The api method is what we’ll be using every time we need to call a resource and it can take in three parameters: the resource, get/post (defaults to get), and params (if any). In this case we want to call the statuses connection in the user object which returns and array of status messages. After receiving the messages, we loop through each and echo them out. If you want to see all the properties of each status, just do a var_dump on each status. That’s it, now the next example.

Add New Status

Here we are doing something a bit different, we are publishing to Facebook and for more info you can look at the Facebook Graph API Overview in the publishing section. We want to create a new post so lets look at the reference guide for information on post and its properties. Scroll down to the publishing section and notice we need the publish_stream extended property and you can see all the different properties that this object supports. I’m personally a bit confused on what is considered a required property and what it not, is seems nothing is required but for this example we want to submit a post with a message.

status_add.php

require_once ‘config.php’;

// add a status message
$status = $facebook->api(‘/me/feed’, ‘POST’, array(‘message’ => ‘This post came from my app.’));

var_dump($status);

This is all the code required to make a post! It’s that easy. We call the api method, tell it we want to call the /me/feed connection, set method to post, and finally pass an array with the properties we want to set – in this case just the message property. If you wanted to set other properties, you would have set them in that array such as ‘link’ => ‘http://link.to.something’, etc. If the call is successfully, you’ll receive an id back which is the id for the new post you just created. Run this code and if all goes well, you should be able to go check our the users Facebook wall and see this latest post. I don’t think you can post the same message twice (unless I’m confusing Facebook with Twitter) so if you try it twice and it doesn’t work, that might be why.

View Photos From Albums

In this example, we want to get all the different albums for our user. Then we need to loop through each album and make a second call that will return all the photos for each album.

photos.php

require_once ‘config.php’;

// get albums
$albums = $facebook->api(‘/me/albums’);

foreach($albums[‘data’] as $album)
{
        // get all photos for album
        $photos = $facebook->api("/{$album['id']}/photos");

        foreach($photos[‘data’] as $photo)
        {
                echo "<img src=’{$photo['source']}’ />", "<br />";
        }
}

Here we call the albums connection on user to get all the album objects. We loop through each and for each album get the album id to then call the photo connection on the album object. If this sounds confusing just let me know and I’ll try to explain this further. When I think of connections I think of joins in a db. It’s like saying I want to join the albums table for the user in the user table therefor retrieving all rows in ablum for a specific user.

Add Photo

In the interest of time and complexity, I’m just going to add a photo without specifying an album. By doing this, Facebook will automatically create a new album to add this photo to. Just know that you can specify an album to add photos directly too if needed.

photos_add.php

require_once ‘config.php’;

$img = realpath("C:\\path\\to\\file.jpg");

// allow uploads
$facebook->setFileUploadSupport("http://" . $_SERVER[‘SERVER_NAME’]);

// add a status message
$photo = $facebook->api(‘/me/photos’, ‘POST’,
        array(
                ‘source’ => ‘@’ . $img,
                ‘message’ => ‘This photo came from my app.’
        )
);

var_dump($photo);

I choose this example for people that want to understand how to post a file through a service like this. First lets start at the top. We need to specify the path to the image we want to upload so change that path to where you file resides. Usually this would be the tmp path for a photo just uploaded to your server via $_FILE. Next we need to tell facebook to allow uploading of a file. I didn’t investigate that method much other then the comments said to specify the server so I use SERVER_NAME to signify this server. Next we make the call. We are calling /me/photos since that’s what is specified in the photos reference page under publishing. We are passing two parameters, message is the text that will show up with the image and source is the image we want to upload. Notice there is an @ before the path to the image. This is because we want to post the contents of the file and not pass a string to where the file is. Run this code and if all worked well, you’ll see this image and an new album in your users Facebook page.

Conclusion

If all went well, your users Facebook wall should look something like this:

Done

My test users Facebook wall

I hope that with this, you have a good understanding on how Facebook’s Graph API works. Start trying to call other objects and play with different extended permissions. The Facebook team did a great job in providing us with the PHP SDK to make this so extremely easy so thumbs up to them. If you have any question/comments, just post them below.