Using Facebook Data to Match People to Ideas or How to Copy Etsy's Facebook App

Everyone seems to like etsy's Gift Ideas for Facebook Friends as it is pretty neat. It works because etsy has a random assortment of mostly awesome (usually over priced) shit that is in the legal gray area. So most Likes, Home Towns, etc. are findable on etsy somewhere, on some product, and even if not, many users like a lot of things, so you can just find the ones that are. But how hard is it to do? Well, not incredibly hard. Their logic is much better and I'm sure their filtering is pretty nice too... and they've got other things going on I don't even touch on, but this will get you started. I'm not going to walk you through every step, if you're having trouble, turn to Google. A useful link will be managing your Facebook app permissions, so you can test and retest the allowing permissions.

Getting Stated

You should already have your Facebook app setup, if not you should set one up, try here: Facebook Apps and make sure you allow yourself and/or whitelist your site if you're sandboxed or using any sort of secure development. You'll also need the Facebook PHP SDK. Take a look at the example in the repository to get a feel of what we will be doing, as I am using that for my base code as well. So let's just save this file as index.php and upload it with the facebook.php file and get started, for real.

Listing Our Facebook Friend(s)

We're not going to be changing too much here, because I don't care what it looks and because this is supposed to be simple. We're going to remove a bunch of stuff, but you might want to keep it for debugging; scrap the Session output and the User Object output, and Natik. You should have something like the code below. To start off, we are going to list out our friends, at least some of them if you have a lot. To do so we will call /me/friends on the Facebook Graph API. This will return an array that contains an array, data, that we will then loop through. Looping through each friend we want to show their picture and name, and link them to our do something page. Ok, we are done. See the index.php page below for full source code.

Doing Something with our Friend(s) Data

We have our friends and our data, awesome! Now what do we want to do? We don't know, so we will just show what our friend(s) likes on the page. This is the point where you should be injecting your own code, ideas, and logic into the app and making amazing things. We are going to use the Graph API again and call /*friend_id*/likes and return their likes, again refer the the API docs for more advanced usage or just use print_r and see what it is that you're getting if you get stuck. For each of our likes, let's just print it out and show it, or do whatever cool thing is it that you want to do with their data.

Finished

You're done! Here is out example page. That wasn't hard at all, and etsy got all that press for that?! Again, I exaggerate, I realize it's slightly more complex than that but you get the idea. This could easily be expanded and add more checking for no likes and removing the user from the listing, and other nice things but one last reminder: this was to get you started quickly and hopefully easily. Have fun and make something awesome, if this was useful you could Tweet it or something.

Notes / Bugs

  • Sometimes after logging in the page fails to refresh, just reload the page.
  • Logging in without Javascript / FBXML will do weird things with permissions.


Source Code

<?php
# Include the Class
require_once './facebook.php';

# Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
	'appId'  => 'app_id',
	'secret' => 'secret',
	'cookie' => true
));

$session = $facebook->getSession();
$me = null;

# Session based API call.
if($session){
	try{
		$uid = $facebook->getUser();
		$me = $facebook->api('/me');
	}
	catch(FacebookApiException $e){
		error_log($e);
	}
}

# login or logout url will be needed depending on current user state.
if($me){
	$logoutUrl = $facebook->getLogoutUrl();
}
else{
	$loginUrl = $facebook->getLoginUrl();
}

# do we need to do something with our friends?
if($me && isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id'])){
	$friend = $facebook->api('/'.$_REQUEST['user_id']);
}

?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Example Facebook App</title>
</head>
<body>
<!-- We use the JS SDK to provide a richer user experience. For more info, look here: http://github.com/facebook/connect-js -->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function(){
	FB.init({
		appId   : '<?php echo $facebook->getAppId(); ?>',
		session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
		status  : true, // check login status
		cookie  : true, // enable cookies to allow the server to access the session
		xfbml   : true // parse XFBML
	});
	// whenever the user logs in, we refresh the page
	FB.Event.subscribe('auth.login', function(){
		window.location.reload();
	});
};
(function() {
	var e = document.createElement('script');
	e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
	e.async = true;
	document.getElementById('fb-root').appendChild(e);
}());
</script>
<?php if($me): ?>
	<a href="<?php echo $logoutUrl; ?>">
		<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
	</a><br/>
<?php else: ?>
	<div>
		Using JavaScript & XFBML: <fb:login-button perms="offline_access, friends_likes"></fb:login-button>
	</div>
<?php endif ?>

<?php if($me): ?>
	<h3>You</h3>
	<p>
		<img src="https://graph.facebook.com/<?php echo $uid; ?>/picture?type=large" alt="<?php echo $me['name']; ?>"/>
		<?php echo $me['name']; ?>
	</p>
<?php else: ?>
	<p>
		<strong><em>You are not Connected.</em></strong>
	</p>
<?php endif ?>

<?php if($friend): ?>
	<p>
		<img src="https://graph.facebook.com/<?php echo $friend['id']; ?>/picture?type=large"/>
		<h3><?php echo $friend['name']; ?> likes...</h3>
	</p>
<?php
$call = $facebook->api('/'.$_REQUEST['user_id'].'/likes?limit=5');
$friends_likes = $call['data'];
foreach($friends_likes as $like){
	echo '<p>Something related to... '.$like['name'].'</p>'."\n";
}
?>
<?php endif ?>

<?php
if($me){
	$call = $facebook->api('/me/friends');
	$friends_list = $call['data'];
	foreach($friends_list as $friend){
		echo '<div class="friend">'."\n";
		echo '<a href="index.php?user_id=' . $friend['id'] . '">'."\n";
		echo '<img src="http://graph.facebook.com/' . $friend['id'] . '/picture" alt="' . $friend['name'] . '"/>'."\n";
		echo '</a>'."\n";
		echo '<a href="index.php?user_id=' . $friend['id'] . '" class="name">' . $friend['name'] . '</a>'."\n";
		echo '</div>'."\n\n";
	}
}
?>
</body>
</html>