Wrangling with the Facebook Graph API

Wrangling with the Facebook Graph API

Tutorial Details
  • Topic: Facebook Graph API
  • Version: Facebook PHP SDK v.3.1.1
  • Difficulty: Intermediate
  • Estimated Completion Time: 1 Hour

Have you ever wanted to learn how to make your applications more social with Facebook? It’s much easier than you think!

In this tutorial, we’ll be building an application that reads and publishes data to and from Facebook using Facebook’s Graph API. Interested? Join me after the jump!


A Short Introduction to the Open Graph Protocol

Facebook Open Graph

Open Graph Protocol

Image courtesy of http://ogp.me

The Open Graph protocol enables any web page to become a rich object in a social graph. For instance, this is used on Facebook to allow any web page to have the same functionality as any other object on Facebook.

While many different technologies and schemas exist and could be combined together, there isn’t a single technology which provides enough information to richly represent any web page within the social graph. The Open Graph protocol builds on these existing technologies and gives developers one thing to implement. Developer simplicity is a key goal of the Open Graph protocol which has informed many of the technical design decisions.

In a nutshell, the Open Graph Protocol turns any web page into an object in a huge graph. Each object, at least in Facebook’s graph objects, can have many other objects linked to it. For example, a Facebook Page can have multiple Post objects, which are posts made by that page. In turn, each Post object can have multiple Comment objects attached to it, referring to comments written by people on the post. This relationship between graph objects is the basis for Facebook’s Graph API, which in turn allows us to do CRUD operations on these objects.

In this tutorial, we’ll be learning how to use and integrate the Facebook Graph API into an application. We’ll also learn how to use data from the Graph API to do operations like logging in a user via their Facebook account. Ultimately, we’ll be creating a small application than allows people to create and read posts from a Facebook Page they’re managing, similar to HootSuite or TweetDeck.


Step 1: Create a Facebook Application

The first thing you should do when you’re planning to use the Facebook Graph API is to create a Facebook application. This doesn’t necessarily mean that we’ll be putting the application on Facebook (although we can); we just need a Facebook application (specifically an APP ID and APP SECRET) to access the API.

Open http://developers.facebook.com and click on the Apps link in the navigation bar.

Facebook's Developer Site

Facebook’s Developer Site

You’ll be prompted to log in (if you’re not) and allow the Developer application to access your account. Just click on Allow and you’ll be redirected to the Developer App homepage.

Allow the Developer application access

Allow the Developer application access

On the Developer App homepage, click on Create New App in the upper right corner of the page.

Developer App homepage

Developer App homepage

You’ll be greeted with a modal window asking for an App Display Name and App Namespace. Provide anything you want here, but for the purposes of this tutorial, I’ll be using Nettuts+ Page Manager and nettuts-page-manager respectively. Click on Continue.

Birth of the Nettuts+ Page Manager

Birth of the Nettuts+ Page Manager

After some obligatory captcha checking, you’ll be redirected to your newly-minted application’s page. Here you’ll see the APP ID and APP SECRET that we need. Copy and paste these values somewhere for later use.

The APP ID and APP SECRET

The APP ID and APP SECRET

When that’s done, go to the lower part of the page and click on the “Website” box, and below it should appear a form that asks for a Site URL. Since I’m just using my local machine to build the application, I’ll use http://localhost/nettuts/pagemanager. When you’re done, click on the Save Changes button below.

Nettuts+ Page Manager Settings

Nettuts+ Page Manager Settings

Step 2: Download and Set Up Facebook’s PHP SDK

Facebook's GitHub page

Facebook’s GitHub page

Our next task is to download and set up Facebook’s PHP SDK. The best location to get it would be on Facebook’s GitHub page, since this is where the latest and greatest version of the PHP SDK will be.

Downloading Facebook's PHP SDK

Downloading Facebook’s PHP SDK

Point your browser to https://github.com/facebook/php-sdk and click on the “ZIP” button. This should prompt a download for the latest version of the SDK. Save it anywhere you like.

Now, extract this into PHP’s include_path to make it accessible by any application. Alternatively, if you’re just using this for one application, extract it inside the application’s folder — just make sure to take note where, since we’ll have to include facebook.php in our code later.


Step 3: Read from Facebook via the Graph API

Let’s start creating our project and using the Facebook Graph API to read information from Facebook. For starters, create an index.php file where a user can log in via Facebook. The index.php file should contain the following code:

<!DOCTYPE html>
<html>
<head>
	<title>Nettuts+ Page Manager</title>
	<link rel="stylesheet" href="css/reset.css" type="text/css" />
	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
	<script src="js/jquery.min.js"></script>
	
	<style>
	body {
		padding-top: 40px;
	}
	#main {
		margin-top: 80px;
		text-align: center;
	}
	</style>
</head>
<body>
	<div class="topbar">
		<div class="fill">
		<div class="container">
			<a class="brand" href="/">Nettuts+ Page Manager</a>
		</div>
	</div>
	<div id="main" class="container">
		<a href="connect.php" class="btn primary large">Login via Facebook</a>
	</div>
</body>
</html>

If you’re wondering, reset.css is just your standard stylesheet reset, and bootstrap.min.css is Twitter Bootstrap. I’ve also added jQuery into the mix to make it easier to do client-side stuff. Now, if you refresh the page, it should look something like this:

Nettuts+ Page Manager First Run
Nettuts+ Page Manager First Run

Now let’s create our connect.php file, which will enable us to connect a user’s Facebook account and the pages that he or she manages. Let’s start by including the Facebook library we downloaded earlier. Instantiate it using the APP ID and APP SECRET:


//include the Facebook PHP SDK
include_once 'facebook.php';

//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
	'appId' => 'REPLACE WITH YOUR APP ID',
	'secret' => 'REPLACE WITH YOUR APP SECRET',
	'cookie' => true
));

The $facebook variable can now be used to make API calls to Facebook on behalf of the application.

  • The appID setting tells Facebook which application we’re using.
  • The secret setting “authenticates” our API calls, telling Facebook that they came from someone who owns the application. This should never be shown to the public, which is why it’s named the “Application Secret.”
  • The cookie setting tells the library to store the user’s session using cookies. Without it, we won’t be able to know whether the user is logged in via Facebook or not.

Now, we check if the current user has already allowed access to the application. If not, the application has to redirect them to Facebook’s “Allow Permissions” page.


//Get the FB UID of the currently logged in user
$user = $facebook->getUser();

//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
	//do stuff when already logged in
} else {
	//if not, let's redirect to the ALLOW page so we can get access
	//Create a login URL using the Facebook library's getLoginUrl() method
	$login_url_params = array(
		'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
		'fbconnect' =>  1,
		'redirect_uri' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
	);
	$login_url = $facebook->getLoginUrl($login_url_params);
	
	//redirect to the login URL on facebook
	header("Location: {$login_url}");
	exit();
}

Essentially, this is all that happens here:

  • The application makes a simple API call to get the user’s Facebook User ID (also known as FB UID) via the $facebook->getUser() method.
  • If the $user variable has a value, it means that the user has already allowed basic permissions for the application.
  • If not, then it means the user hasn’t allowed the application permissions yet, and the application needs to redirect to Facebook’s permissions page to get the necessary permissions.
  • It then generates a Login URL, which is where the application should redirect the user to show Facebook’s permissions page for the application. The getLoginUrl() method takes in the following parameters:

    • scope – this is a comma-delimited list of permissions the application needs
    • fbconnect – this should be 1 to tell Facebook that the application will be using Facebook to authenticate the user
    • redirect_uri – this is the page Facebook redirects to after the user has gone through the Facebook permissions page

    You can read more about the getLoginUrl() method here: https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/

  • Afterwards, the application redirects the user to the Login URL and the user sees Facebook’s permissions page.
Facebook's Permissions Page

Facebook’s Permissions Page

Facebook Permissions

Let’s take a minute to talk about Facebook permissions. Similar to when you install an application on your Android phone, Facebook permissions are various levels of access a Facebook application can do on behalf of a user. For example, if we wanted access to user’s email address, we can add the email permission to the scope setting we use to generate the login URL.

Remember, with great power comes great responsibility, so make sure to only use your permissions for good, not for evil.

It’s important that your application only asks a user for permissions that it actually needs. If you only need to authenticate a user via Facebook, you don’t even need to ask any permissions at all! Remember, with great power comes great responsibility, so make sure to only use your permissions for good, not for evil.

In the app, we use the following permissions:

  • publish_stream – allows the application to publish updates to Facebook on the user’s behalf
  • read_stream – allows the application to read from the user’s News Feed
  • offline_access – converts the access_token to one that doesn’t expire, thus letting the application make API calls anytime. Without this, the application’s access_token will expire after a few minutes, which isn’t ideal in this case
  • manage_pages – lets the application access the user’s Facebook Pages. Since the application we’re building deals with Facebook Pages, we’ll need this as well.

There are a lot more permissions Facebook requires for different things. You can read all about them in Facebook’s documentation for permissions.

Going back to the application, now that the user has allowed the permissions required by the application, we can do some API calls to Facebook! Place this inside the if-else block from the code above:

<pre>
//start the session if needed
if( session_id() ) {

} else {
	session_start();
}

//get the user's access token
$access_token = $facebook->getAccessToken();

//check permissions list
$permissions_list = $facebook->api(
	'/me/permissions',
	'GET',
	array(
		'access_token' => $access_token
	)
);
</pre>

The first thing we do is get the $access_token for the user that the application just authenticated. This is crucial, as the application will need this access token for almost everything we do. To get it, we use the getAccessToken() method. The $access_token acts as a ‘password’ for the user. It’s always unique for every user on every application, so make sure to store this when needed.

Afterwards, we can see how to make API calls to Facebook using the api() method. This method takes in the following parameters:

  • $graph_path – this is the Facebook graph path, which is essentially the “URL” to the open graph object we want to access. This can be any graph object on Facebook, like a Post (e.g. ‘/<post_id>’), a Comment (e.g. ‘/<comment_id>’), or even a User (‘/me’ is a shortcut for the current user whom the $access_token belongs to. It can also be ‘/<user_name>’ or ‘/<fb_uid>’, but the $access_token you’re using must have access to that user, or you’ll only be able to get the user’s public information).
  • $method – this is the kind of method you want to do. It’s usually GET when you’re trying to “get” information, and POST when you’re trying to “post” or update information and DELETE if you want to remove information. If you’re not sure, the Graph API documentation tells you which method to use for specific API calls.
  • $params – these are the parameters that come with your API request. Usually for GET methods you only need to supply the user’s $access_token. For POST methods though, you’ll also need to provide other parameters. For example, if you want to post a new status update, you’ll provide the status update message here.

Alternatively, we can also use the api() method to execute FQL (Facebook Query Language) queries, which lets us get data via SQL-style language. This is great for retrieving information not available in the Graph API, as well as running multiple queries in one call. For example, we can get a user’s name and other details through this FQL API call:

$fql = 'SELECT name from user where uid = ' . $fb_uid;
$ret_obj = $facebook->api(array(
   'method' => 'fql.query',
   'query' => $fql,
 ));

We won’t need this for this tutorial, but it’s good to keep this in mind when you come across something the Graph API can’t get.

Now that we have the list of permissions the user has allowed for the application, we need to check if the user gave the application all the necessary ones. Since Facebook’s permissions page allows users to revoke certain permissions, we need to make sure that all of them have been allowed to make sure the application works. If the user has revoked one of the permissions, we’ll redirect them back to the permissions page.

//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'offline_access', 'manage_pages');
foreach($permissions_needed as $perm) {
	if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
		$login_url_params = array(
			'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
			'fbconnect' =>  1,
			'display'   =>  "page",
			'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
		);
		$login_url = $facebook->getLoginUrl($login_url_params);
		header("Location: {$login_url}");
		exit();
	}
}
var_dump() of the $permissions_list variable

var_dump() of the $permissions_list variable

When that’s done, it means we’re all set and we’ll be able to run the application without any problems. Let’s start by doing another API call, this time to retrieve the list of Facebook Pages the user has administrative rights to, and saving these into a session variable. Afterwards, we’ll redirect the user to the manage.php page, where the page management code will be.

//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
	'/me/accounts',
	'GET',
	array(
		'access_token' => $access_token
	)
);

//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
$_SESSION['active'] = $accounts['data'][0];

//redirect to manage.php
header('Location: manage.php');
var_dump() of the $accounts variable

var_dump() of the $accounts variable

The /me/accounts graph path gives us a list of the pages that a user has administrative rights to. This returns an array of all of the pages, plus specific $access_tokens for each of these pages. With those $access_tokens, we’ll be able to do API calls on behalf of the Facebook Page as well!

Save these in the $_SESSION array and redirect to the manage.php page.

Let’s start working on our manage.php file. Remember that we’ve saved the user’s $accounts list into the $_SESSION array, as well as set the first account on the list as the default active page. Let’s GET that account’s news feed and display it:

//include the Facebook PHP SDK
include_once 'facebook.php';

//start the session if necessary
if( session_id() ) {

} else {
	session_start();
}

//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
	'appId' => 'APP ID',
	'secret' => 'APP SECRET',
	'cookie' => true
));

//get the news feed of the active page using the page's access token
$page_feed = $facebook->api(
	'/me/feed',
	'GET',
	array(
		'access_token' => $_SESSION['active']['access_token']
	)
);

Again, the application does the intialization of the Facebook library, and then another api() call, this time to /me/feed. Take note that instead of using the user's access token, we use the active page's access token (via $_SESSION['active']['access_token']). This tells Facebook that we want to access information as the Facebook Page and not as the user.

var_dump() of the $page_feed variable

var_dump() of the $page_feed variable

Wow, that’s a lot of information about a Facebook Post. Let’s dissect a single Facebook Post object and see what it’s made of.

The Facebook Post Object

Facebook Post Cheat Sheet

Facebook Post Cheat Sheet
  • id – this is the Post‘s ID
  • from – contains information about the user who posted the message
  • message (red) – the message component of the post
  • picture (orange) – a link to the photo attached to the post
  • name (blue) – the “title” of the Facebook post
  • link (also blue) – the link to where the name goes to when clicked
  • caption (purple) – a few words to describe the link
  • description (pink) – more than a few words to describe the link
  • icon (grey) – a link to the icon image used
  • actions – Facebook actions you can do to the post, such as Liking it or Commenting on it.
  • privacy – the privacy of the post
  • type – the type of the post. A post can be a status, link, photo or video.
  • created_time – the time when the post was created
  • updated_time – the time when the post was updated
  • comments – comments on the post

It would be wise to keep a copy of the cheat sheet above, since we’ll be using that again when we publish Post objects to Facebook.

Moving on, let’s display the news feed in a more pleasing way. Add the following HTML below the PHP code:

<!DOCTYPE html>
<html>
<head>
	<title>Nettuts+ Page Manager</title>
	<link rel="stylesheet" href="css/reset.css" type="text/css" />
	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
	<script src="js/jquery.min.js"></script>
	
	<style>
	body {
		padding-top: 40px;
		background-color: #EEEEEE;
	}
	img {
		vertical-align: middle;
	}
	#main {
		text-align: center;
	}
	
	.content {
		background-color: #FFFFFF;
		border-radius: 0 0 6px 6px;
		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
		margin: 0 -20px;
		padding: 20px;
	}
	.content .span6 {
		border-left: 1px solid #EEEEEE;
		margin-left: 0;
		padding-left: 19px;
		text-align: left;
	}
	.page-header {
		background-color: #F5F5F5;
		margin: -20px -20px 20px;
		padding: 20px 20px 10px;
		text-align: left;
	}
	</style>
	
</head>
<body>
<div id="main" class="container">
	<div class="content">
		<div class="page-header">
			<h1>
				<img width="50" src="http://graph.facebook.com/<?php echo $_SESSION['active']['id']; ?>/picture" alt="<?php echo $_SESSION['active']['name']; ?>" />
				<?php echo $_SESSION['active']['name']; ?>
				<small><a href="http://facebook.com/profile.php?id=<?php echo $_SESSION['active']['id']; ?>" target="_blank">go to page</a></small>
			</h1>
		</div>
		<div class="row">
			<div class="span10">
				<ul id="feed_list">
					<?php foreach($page_feed['data'] as $post): ?>
					<?php if( ($post['type'] == 'status' || $post['type'] == 'link') && !isset($post['story'])): ?>
					<?php //do some stuff to display the post object ?>
					<?php endif; ?>
					<?php endforeach; ?>
				</ul>
			</div>
			<div class="span6">
				<h3>Post a new update</h3>
			</div>
		</div>
	</div>
</div>
</body>
</html>

We make use of a simple Graph API trick here: the Picture Graph API object. Basically, you can take the Graph path of any User or Page object (e.g. http://graph.facebook.com/293518907333589), add /picture in the end and you’ll get a 50×50 photo of that object. For example:

http://graph.facebook.com/293518907333589/picture

Becomes…



Demo Picture Graph API Object

Going back, when we refresh the manage.php page now, it should look something like this:

Add this inside the <?php foreach($page_feed['data'] as $post): ?> to display the feed from the page:

<?php if( ($post['type'] == 'status' || $post['type'] == 'link') && !isset($post['story'])): ?>
<li>
	<div class="post_photo">
		<img src="http://graph.facebook.com/<?php echo $post['from']['id']; ?>/picture" alt="<?php echo $post['from']['name']; ?>"/>
	</div>
	
	<div class="post_data">
		<p><a href="http://facebook.com/profile.php?id=<?php echo $post['from']['id']; ?>" target="_blank"><?php echo $post['from']['name']; ?></a></p>
		<p><?php echo $post['message']; ?></p>
		<?php if( $post['type'] == 'link' ): ?>
		<div>
			<div class="post_picture">
				<?php if( isset($post['picture']) ): ?>
				<a target="_blank" href="<?php echo $post['link']; ?>">
					<img src="<?php echo $post['picture']; ?>" width="90" />
				</a>
				<?php else: ?>
				&nbsp;
				<?php endif; ?>
			</div>
			<div class="post_data_again">
				<p><a target="_blank" href="<?php echo $post['link']; ?>"><?php echo $post['name']; ?></a></p>
				<p><small><?php echo $post['caption']; ?></small></p>
				<p><?php echo $post['description']; ?></small></p>
			</div>
			<div class="clearfix"></div>
		</div>
		<?php endif; ?>
	</div>
	<div class="clearfix"></div>
</li>
<?php endif; ?>

When you refresh the page again, it should look something like this:

Looks good, right? We’ll have to thank the Twitter Bootstrap CSS for that!

Now, let’s add a top navigation bar to help us switch from one page to another. Add the following HTML after the <body> tag and before the <div id="main" class="container"> tag:

<div class="topbar">
	<div class="fill">
	<div class="container">
		<a class="brand" href="/">Nettuts+ Page Manager</a>
		<ul class="nav secondary-nav">
			<li class="dropdown" data-dropdown="dropdown">
				<a class="dropdown-toggle" href="#">Switch Page</a>
				<ul class="dropdown-menu">
					<?php foreach($_SESSION['accounts'] as $page): ?>
					<li>
						<a href="switch.php?page_id=<?php echo $page['id']; ?>">
							<img width="25" src="http://graph.facebook.com/<?php echo $page['id']; ?>/picture" alt="<?php echo $page['name']; ?>" />
							<?php echo $page['name']; ?>
						</a>
					</li>
					<?php endforeach; ?>
				</ul>
			</li>
		</ul>
	</div>
	</div>
</div>

Don’t forget to load the dropdown JavaScript library from Twitter Bootstrap’s JavaScript page. You can download it here.

<script src="js/bootstrap-dropdown.js"></script>
<script>
$('.topbar').dropdown()
</script>

Lastly, let’s create the switch.php file, where we’ll set another page as the active page:

<?php
session_start();
$page_id = $_GET['page_id'];

foreach($_SESSION['accounts'] as $page) {
	if( $page['id'] == $page_id ) {
		$_SESSION['active'] = $page;
		header('Location: manage.php');
		exit();
	}
}
exit();
?>

Refresh the manage.php page again and you should see something like this:

And now, by using our dropdown switcher, we’re able to switch pages.


Step 4: Publish to Facebook via the Graph API

Now we’re ready to publish new updates to our page! First of all, let’s create the HTML form where we can set what we’ll publish. Add this below the <h3>Post a new update</h3> HTML:

<img src="post_breakdown.png" alt="Facebook Post Cheat Sheet" width="340" /><br />
<form method="POST" action="newpost.php" class="form-stacked">
	<label for="message">Message:</label>
	<input class="span5" type="text" id="message" name="message" placeholder="Message of post" />
	<label for="picture">Picture:</label>
	<input class="span5" type="text" id="picture" name="picture" placeholder="Picture of post" />
	<label for="link">Link:</label>
	<input class="span5" type="text" id="link" name="link" placeholder="Link of post" />
	<label for="name">Name:</label>
	<input class="span5" type="text" id="name" name="name" placeholder="Name of post" />
	<label for="caption">Caption:</label>
	<input class="span5" type="text" id="caption" name="caption" placeholder="Caption of post" />
	<label for="description">Description:</label>
	<input class="span5" type="text" id="description" name="description" placeholder="Description of post" />
	
	<div class="actions">
		<input type="submit" class="btn primary" value="Post" />
		<input type="reset" class="btn" value="Reset" />
	</div>
</form>

Refresh to see how it looks:



Loving Twitter Bootstrap’s default form styles

The Post cheat sheet should come in handy when we’re figuring out what to put in the fields. Now, let’s create the newpost.php file where we’ll actually use the Facebook Graph API to publish to the page’s feed.

Start by creating the file and initializing the Facebook library like we did for the other pages:

<?php
//include the Facebook PHP SDK
include_once 'facebook.php';

//start the session if necessary
if( session_id() ) {

} else {
	session_start();
}

//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
	'appId' => 'APP ID',
	'secret' => 'APP SECRET',
	'cookie' => true
));
?>

Afterwards, let’s get all of the content we received from the POST request:

//get the info from the form
$parameters = array(
	'message' => $_POST['message'],
	'picture' => $_POST['picture'],
	'link' => $_POST['link'],
	'name' => $_POST['name'],
	'caption' => $_POST['caption'],
	'description' => $_POST['description']
);

Let’s not forget to add the $access_token for the page to the parameters:

//add the access token to it
$parameters['access_token'] = $_SESSION['active']['access_token'];

Now that we have our $parameters array, let’s build and send our Graph API request!

//build and call our Graph API request
$newpost = $facebook->api(
	'/me/feed',
	'POST',
	$parameters
);

Take note of what difference the $method can make. A GET API call to /me/feed will return the news feed of that particular object, but a POST API call to /me/feed will post a new status update to the object.

To publish a new Post object to Facebook, the application needs to make a call to the /<page_id or /me>/feed graph path, and it needs to supply the following in the $parameters array:

  • access_token – the access token of the account we are publishing for
  • message – the message to publish
  • picture (optional) – a link to the photo of the post
  • name (optional) – the “title” of the post
  • link (optional) – a link to where the name will go to when clicked
  • caption (optional) – a few words to describe the link/name
  • description (optional) – more than a few words to describe the link/name

You can see that the only parameters that are required are the access_token and the message parameters. By providing only these two, we can publish a simple status message, like so:



Status Update Example

Everything else is optional. However, if you provide a name, link, caption, or decription, you have to provide all four. As for picture, if a parameter value is not provided or not accessible, the post’s picture will be blank.

Finally, let’s try publishing to Facebook using the application! Go back to the manage.php page and fill up the form, then press Post:

Afterwards, you should be redirected back to the manage.php page, but there should be a new post on the feed!



Publishing to Facebook successful!

You can also check the Facebook Page itself. You should see the new post there:



Publishing to Facebook Page

Conclusion

By now, you should already have a clear grasp on how to use the Facebook Graph API to both read and publish to Facebook. In this tutorial, we only cover the basics — there’s a whole lot more you can do using the Graph API. Stuff like real-time updates, which lets you subscribe to events that happen to your application’s users (e.g. when a user changes his/her profile photo) or the Insights Graph object, which lets you get the statistics of an application, page, or domain the user has access to.

Of course, the best resource for learning more about the Graph API is undoubtedly Facebook’s Graph API documentation, but I also suggest taking a look at FBDevWiki, which is a third-party hosted wiki for Facebook Development documentation.



FBDevWiki.com

Additionally, there’s also a special Facebook version of StackOverflow you can visit at http://facebook.stackoverflow.com. The questions here are all about Facebook and Facebook Development, so it’s well worth visiting if you need any help or have any questions on the subject.



Facebook StackOverflow

Hopefully, you’ve learned from this tutorial how easy it is to use the Facebook Graph API to make your applications more social.

Have you used the Facebook Graph API in a previous project, or are you planning to use it now? Tell me all about it in the comments below and thank you so much for reading!

Tags: api
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • tempovan

    Hi ,

    Suppose i build an app with APP_ID AND APP_SECRET in my hand . And i login as a different user.
    I want to access facebook profile information.Will d same appid and app_secret work for a different user ?

    How to get app_id and app_secret programmatically ?
    I am using django as my backend
    Please respond asap

  • Fintan

    Same errors as above. “An error occured please try again later”.

    • http://nativehacker.com/ NativeHacker

      me too… facebook’s API is so hard to beginner

  • http://www.gustavstromberg.se/ Gustav Strömberg

    Please, make a follow up on this one.
    I loved it and would be delighted to read more about it!

    //Gustav

  • http://kyleboyd.co.uk Kyle Boyd

    Hi,

    I have got most things working but cant seem to getthe main login page to work, I have added my app ID and secret key but I keep getting the error – ‘This webpage has a redirect loop’.

    Is the problem because I supposed to change these two lines in connect.php –

    ‘next’ => ‘http://’.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']‘

    but were do I redirect them too? I have put in both index.php and manage.php but still getting same error. Like below.

    ‘next’ => ‘http://http://localhost:8888/tutorial/source/index.php’.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']‘

    Any help appreciated.

    Best,
    K

    • Phendyr

      I’m experiencing the same ‘redirect loop’ issue. any suggestions out there?

      • Jose

        That’s because ‘offline_access’ has been deprecated. Delete ‘offline_access’ from permissions needed and scope and you will find the code working again.

        Great tutorial. Thank you very much.

  • http://wannaco.net Jacobo

    I get an error right after i log in to facebook, when its redirecting me to the permissions, it gives me a too many rederictions ERROR

  • ProfoundGamer

    I think that the loop is caused by the fact that offline_access has been removed
    https://developers.facebook.com/roadmap/offline-access-removal/

  • http://wannaco.net jacobo

    How can it be fixed ? seems like you have to do major changes on the code.

    • http://wannaco.net Jacobo

      fixed, it was pretty simple.

      • shouqin

        hi jacobo how did you fix it? care to share? =)

      • http://www.ianvisits.co.uk IanVisits

        Delete each instance of “offline_access” from connect.php to fix the problem – due to FB removing that option from their platform.

      • jacob

        So you can fix it you just need to go to your facebook App and got to advaced options, follow the instructions given in the link below

        https://developers.facebook.com/roadmap/offline-access-removal/

  • fernando

    sorry for my bad english.
    I jus deleted the permission to access off line in all lines of the code.
    in the app settings on facebook develop do not write an app domain just de site url.
    you can see it in http://mapplesoft.com/bnori/admin

  • Arif

    hello i have some questions..
    1)i saw this message..
    We are in the process of deprecating the REST API. If you are building a new Facebook app, please use the Graph API. While there is still functionality that we have not ported over yet, the Graph API is the center of Facebook Platform moving forward and where all new features will be found.
    does it mean we shouldnt use..
    $facebook->api();-this function or what?
    2)is it possible to create like for pages.

  • Chris

    Just to let some of you know…

    I was getting the “An error occured please try again later” and it ended up being due to the fact that my return URL was different to that registered when I created the app on FB. Works fine now.

    offline_access doesn’t seem to make a difference…

    Chris

  • http://www.theagence.fr Nicolas

    Nice tutorial. But how about logging out?

  • Gladys

    Hi, I’m new to PHP and learning how to publish data onto facebook from my application. I followed your tutorial and when i try to run the manage.php, i get the error messages

    Notice: Undefined index: active in C:\wamp\www\manage.php on line 24
    where line 24 is:
    ‘access_token’ => $_SESSION['active']['access_token']

    Fatal error: Uncaught CurlException: 6: Could not resolve host: graph.facebook.com; Host not found thrown in C:\wamp\www\base_facebook.php on line 887
    where like 887 is:
    $e = new FacebookApiException(array(

    i can’t seem to find out what the problem is, so was hoping someone could help. thank you.

  • http://www.sagarnangare.in Sagar

    Got problem while logging with connect.php. Firefox showing this message “The page isn’t redirecting properly”. Just loaded index.php. Nothing else happened. I have put app ids & secret keys in all required places.

    Please reply.

  • http://www.sn-gate.com SN Gate

    Great article. you may also ask questions related to Facebook APIs at http://www.sn-gate.com and find lot of answers.

  • r3d

    hi, thx, this is a realy useful tuts for me, but i hve to change line:27 on your fbmain.php from:

    $session = $facebook->getSession();
    to
    $session = $facebook->getUser();

    anyway, thx for share :D

  • Mike

    I seem to be getting the same redirect loop issue after allowing permissions through facebook. I’ve tried deleting the instances of offline_access in my code as well as adjusting the advanced options re:offline_access to no avail. Is there anything else anyone would suggest trying?

    • Ethan

      I’m also having this problem so if you come up with anything do post??

      • Mike

        Ethan, what I ended up doing was downloading the latest version of the PHP SDK and using the example.php script as a starting point to build an app. It’s been pretty smooth, so give it a shot.

      • http://www.facebook.com/valentine.mick Valentine Mick London

        Please post your version here?
        It’s driving me crazy seeing this redirect loop thing :(

  • Avantguardia

    Brilliant! Nice work! Just one thing: it show’s bot Page’s and Application? How to remove Application from list, only show Page? Thank you.

  • Avantguardia

    one more bug for infinity loop. using “read_insights” for scope also redirect to infinity…

  • Avantguardia

    Do someone adapt this code to display insights of given page?

  • Vijesh

    Hi,,,

    The code for working fine 2 moths before. but now indirect loop error is coming. Any API changes?… please help

  • http://aykutfarsak.com aykut

    .. and there is a Facebook SDK wrapper https://github.com/aykutfarsak/simplefacebook

  • arth

    thanx…gr8..working very well.

    but if i want to upload photo on facebook page [manage page] and upload cover page on facebook page..so for that if anyone has idea then please give me the code….

  • Lokesh

    php code to tag 10 rand0m friends in my photo where photo id/post id is given.

  • COSINUS

    You have to remove offline permission and it will works

  • ajl

    Great tutorial, thx!!

  • Ashish

    “An error occurred. Please try later”

    When I tries to run this page on my machine I always get this error. I get the same error when I was trying to run some other sample code. Do I need to do special setup apart from Lamp to run fb code locally? All help will be greatly appreciated. I want to develop an application which will check user’s online time they spend on Facebook to save them from IAD.

  • http://www.facebook.com/ankit.agarwal62 Ankit Agarwal

    hello i followed ure instructions to develop the app…but when i click on the login with facebook link facebook shows a blank page.please help me

  • Sam

    Awesome tutorial! I’ve got just quick question: how can I post a video? Thanks.

  • Imrul hasan

    Error:
    Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
    This problem can sometimes be caused by disabling or refusing to accept cookies.

    Please help me

  • http://www.facebook.com/OutStyle Lorenzo Giulioni

    MUST EDIT: get the fb sdk from here: https://github.com/facebook/facebook-php-sdk

  • ming

    can twitter and google do like that???

  • cenobyte

    for those having the infinite loop redirect issue: the problem is the permission “offline_access” in connect.php which is deprecated. Just remove the “offline_access” permission in the scope and it should work :)

  • juanjo

    Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /source/base_facebook.php on line 1040