Making a Simple Facebook App in 20 minutes

Anna • February 14, 2011 • Comments View Comments

Create a simple app using OAuth2, iFrames, and the Facebook Social Graph.

Create app

Go to Facebook.com/developers/createapp.php.

Type in your ideal app name, accept the terms. Pass the kaptcha. You are not just a robot!

Create Application

Create paths

On the developer page, select “Facebook Integration”.

Edit hackfest2

Create:
Canvas page: The application’s location on Facebook
Canvas url: The applicaiton’s location on your server

Get keys

Facebook will display the application page, and when you select “facebook integration” again you will see the following keys. Keep this page open in a browser while we go to your local web directory and edit files there.
Developers

Create url

Above, when you created “Canvas URL” you should have entered a real directory on your server. We will now edit the index.php page, in that directory.

Add App ID to the index page, near the top, as a constant:

<?php define('FACEBOOK_APP_ID', '[your app id]'); ?>

We are constructing a url that will call Facebook’s authentication service. Include: our app ID, permissions, and the next landing page, or, the “redirect_uri”, in the querystring.

$redir_uri= FACEBOOK_URL."getPopularity.php";
$perms = "publish_stream";
$url = "https://graph.facebook.com/oauth/authorize?
         client_id=".FACEBOOK_APP_ID."&
         scope=".$perms."&redirect_uri=".$redir_uri;

Start the authentication with a redirect

Now, use the URL you created. It will first contact Facebook Oauth2, confirm that your app is official, get permissions from the user, then continue to your local app page. Include this html in the index.php page to start the redirect to Facebook.

<html>
<script>
</script>
</html>

Asking Permission

This is what the user sees, accessing index.php:

Request for Permission

Coding the app

Now that the user has authenticated us, open up the redir_uri page - getPopularity.php- and start coding.
Include the PHP SDK library, instantiate the $facebook object, and make your first call to the Facebook Open Graph.

<?php
include("/var/www/my_app/libraries/facebook.php");
define('FACEBOOK_APP_ID', '[your app id]');
define('FACEBOOK_SECRET', '[your secret]');
$facebook = new Facebook(array('appId' =>FACEBOOK_APP_ID,
               'secret'=>FACEBOOK_SECRET,	'cookie' =>true, ));
try{
  $me = $facebook->api('/me/');
  echo "My Facebook UID is: ".$me["id"];
} catch(FacebookAPIException $e){
  echo "Error using graph: $e<br>";
}
?>

More interesting calls…

Let’s use the graph to get some social info:

// make the content a bit dynamic
$adjArray = array('so many','quite a lot of','lots of','tons of',
              'a helluva lot of', 'many many many', 'an insane amount of',
              'beaucoup de', 'quite a grand amount of', 'a huge load of');
$i = rand(0,count($adjArray)-1);
$adj = $adjArray[$i];
try{
	$friends = $facebook->api('/me/friends');
	echo "You have ".count($friends["data"])." friends. Awesome.
                That's ".$adj." friends!";
} catch (FacebookAPIException $e){
	echo "Sadly, I'm unable to see your friends: $e";
}

Sharing

To share the information- include the following in the HTML portion of the page. Add a button click with “onClick=publish()”. This is the Javascript SDK, GUI element, which I like, from a user expeirence perspective, better than using the PHP server-side version.

<script type="text/javascript">
function publish(){
	var url = 'http://mysite';
	var media = [];
	var imgSrc = 'http://static.howstuffworks.com/gif/cannes-crowds.jpg';
	media.push({'type':'image', 'src':imgSrc, 'href':url});
	var name = "I am Super Popular";
	var description = 'I have <?=count($friends["data"])?> friends.';
	var actionLinks = [{ 'text': 'Popularity', 'href': '<?=FACEBOOK_URL?>' }];
	var attach= {'name':name, 'description':description,'href':url, 'media':media,'properties':''};
	FB.ui({
	   'method': 'stream.publish',
	   'attachment': attach,
	'action_links': actionLinks }, function(response) {
	  }
	);
}
</script>

<a onclick="publish()">Publish</a>


<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript" charset="utf-8"></script>
<div id="fb-root"></div>
<script type="text/javascript" charset="utf-8">
FB.init({
    appId: '<?= FACEBOOK_APP_ID ?>',
    status: true,
    cookie: true,
    xfbml: true
});
	$(window).load(function() {
		FB.Canvas.setSize();
	});
</script>
</body>
</html>

Test Your Popularity

Super Popular

Helpful Resources

FB API Reference
FB Graph Overview
FB.ui / FB JS SDK
FB PHP SDK

Category: App Development, Facebook

About the Author

I'm a developer with Momentus Media. I've done the gamut of OLAP DB modeling to iPhone development and Ruby on Rails. Now, I'm in the fast lane of rapid, viral app development on Facebook.

View Author Profile
  • Wasif

    nice post anna…

  • http://www.banane.com banane

    Thanks!

  • http://twitter.com/SusanPotter Susan Potter

    Nice intro to FB application development using PHP. One thing I noticed: the author’s profile link in the bio gives a 404 at: http://momentusmedia.com/blog/author/Anna/

    HTH
    Susan

  • http://www.brittanymlaughlin.com/ Brittany Laughlin

    Great post! Is this how you add dynamic tabs to Facebook pages too?

  • xDragonZ

    Thx for the guide ! ^^ How to publish photo ? can you help me ? i cant get it working

    var url = ‘http://mysite’;
    var media = [];
    var imgSrc = ‘http://static.howstuffworks.com/gif/cannes-crowds.jpg’;

    media.push({‘type’:'image’, ‘src’:imgSrc, ‘href’:url});

    var name = “I am Super Popular”;
    var description = ‘I am Super Popular!’;
    var properties = ”;
    var attach= {‘name’:name, ‘description’:description,’href’:url, ‘media’:media, ‘properties’:properties};

    var actionLinks = [{ 'text': 'Super Popular', 'href': url }];

    FB.getLoginStatus(function(response) {
    if (response.session) {
    FB.ui({
    ‘method’: ‘stream.publish’,
    ‘attachment’: attach,
    ‘action_links’: actionLinks }, function(response) {

  • http://www.banane.com banane

    Hi - Can’t tell what the issue is here. You may want to post the error you see. Turn on FireBug and read console while you try to test JavaScript.

  • http://www.banane.com banane

    Thanks for the heads-up, just fixed it.

blog comments powered by Disqus