WebAppNiche

We dont just develop applications, we build business

Facebook Application Development using Graph Api and Cakephp

In this article I will show you how to write a iframe based facebook application using popular php framework cakephp and facebook graph api. I chose cakephp because of it's excellent ORM which is similar to that of Ruby on Rails. I prefer iframe as it supports my favorite javascript library - jquery.

I assume that you are familiar with cakephp and facebook graph api. So without any delay, lets jump into the steps:-

1) Set up a new facebook application -

New Facebook Application

Complete the visual verification in the next step which will create the new facebook application and bring up the setting screen for the new application.

2) Go to the Facebook Integration tab and note down the Application ID and Application Secret, set the Canvas Page url which will be your facebook application url. Now set the Canvas URL to something like http://localhost/cakephp-app or the appropriate url where your cakephp installation is going to reside -

Click on Save Changes. Now we are done with facebook application setup. Now it's time to dive into cakephp.

3) Install cakephp in your web-server document root to the location you just mentioned in canvas URL.

4) Create a configuration file facebook.php inside app/config folder for storing our facebook settings. The contents of the file are :-

<?php
$config['appId'] = 'APP ID';
$config['apiKey'] = 'API KEY';
$config['secret'] = 'APP SECRET';
$config['canvasPage'] = 'CANVAS PAGE URL';
?>

5) Download facebook php-sdk from github and store it in your app/vendors folder.

6) Now edit cake/libs/controller/apps_controller.php file with these contents :-

class AppController extends Controller {

var $components = array('Session');
var $facebook;

function beforeFilter() {
App::import('Vendor', 'facebook');
Configure::load('facebook');

$appId = Configure::read('appId');
$apiKey = Configure::read('apiKey');
$secret = Configure::read('secret');

$this->set('appId',$appId);

$this->facebook = $facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true
));
$this->checkFbAuthorization();
$this->set('facebookId', $this->Session->read('facebookId'));
$this->set('id', $this->Session->read('id'));
}

function checkFbAuthorization(){
$session = $this->facebook->getSession();

if (!$session) {
$url = $this->facebook->getLoginUrl(array(
'req_perms' => 'publish_stream,offline_access,email,user_birthday,user_education_history,user_hometown,user_location,user_website,user_work_history,friends_work_history,friends_education_history',
'canvas' => 1,
'fbconnect' => 0,
'next' => '/users/home'
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
} else {
try {
$me = $this->facebook->api('/me');
$facebookId = $this->Session->read('facebookId');
//if facebookId session variable is not set or a different user has logged in, check if user is present in our db or not
if(!isset($facebookId) || $facebookId != $me['id']){
$user = ClassRegistry::init('User')->updateFacebookUser($me);
$this->Session->write('id',$user['id']);
$this->Session->write('facebookId',$user['facebook_id']);
}
} catch (FacebookApiException $e) {
echo "Error:" . print_r($e, true);
}
}
}
}

The code is pretty straight forward, we import our facebook php-sdk and load facebook settings. We then initialize facebook object with our appId and secret. Next we check if our user has authorized our facebook app or not.

We try to fetch active facebook session using $session = $this->facebook->getSession(); , if no active session is found, we build our facebook login url. We ask the user for all extended permissions which we shall be needing in our application in the 'req_perms' parameter. For more information about Extended Permissions visit facebook documentation. Another important parameter is 'next' which is the url to which facebook should redirect our user after (s)he authorizes our application.

If the user has granted our application access permissions, we try to create a facebook user object using $me = $this->facebook->api('/me'); . Now $me would contain all information about our app user. While this should be enough for most simple applications, but for applications which require storing the user information in our database, we can do so with the next steps.

First we check if we already have a session variable - facebookId set. If no session variable is set or if a different user has logged in from the same machine, we check if our database to see if the user is already stored in our users table and if not save it in our database. The code should be simple and hence not documented here. The function returns the facebookId and our native userId which is set in session.

Now we are ready to take over with our own logic.

7) We shall fetch user's information in our home action of users controller:-

	function home(){
//fetch data
$this->set('userInfo' , $this->facebook->api('/me'));
}

8) A basic home.ctp for getting you started :-

<div class="container">
<div class="profile-pic">
<img src="https://graph.facebook.com/<?php echo $facebookId;?>/picture" />
</div>
<div class="user-details">
Welcome <?php echo $userInfo['name']; ?>
</div>
</div>

9) For automatically resizing the iframe, we will update our default layout file (cake/libs/view/layouts/default.ctp) and paste the following code just before the ending </body> tag :-

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo $appid?>', status: true, cookie: true, xfbml: true});
FB.Canvas.setAutoResize();
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>

That's it, we are done with our cakephp based facebook application. This is a very basic application but should be enough to get you started. If you have any questions or suggestions for bettering the code, feel free to comment.

 
You are here: Blogs Latest Facebook Application Development using Graph Api and Cakephp
 

facebook application development social applications joomla commerce business developers portal community software websites webappniche twitter network management requirement install drupal project services experience networking internet custom platform developer networks portals engines wordpress shopping customization android client optimization mobile ecommerce myspace companies windows joominvite virtuemart ferret develop installation opensocial google customers promote library service cakephp questions server quality technologies projects solutions travel company hosting providers professional traffic analysis apache solution maintenance programming linkedin framework marketing products