Show Your Site Feed in Facebook with an Integrated Facebook App

Category: 

Facebook, is the best social media website as we know it. We use it to connect to our friends and do some sharing stuff. But a lot of SEO related work goes on Facebook too. Anyway, today we are not very much concerned about SEO stuffs. But today we are going to built an integrated Facebook application that will show feeds from your site to Facebook App Page. Sounds interesting isn't it? So let us begin.

Basic Overview

This section will list what we are going to use and what we want to achieve.

  1. Downloading the Facebook SDK. Download it from Here.
  2. Make a nice tabular jQuery GUI page. Add the jQuery from Google CDN. Gather some jQuery Tabs script knowledge from here.
  3. Fetching data from your website through Feedburner.
  4. Using YQL to fire up SQL to get the Feeds from the Feedburner.
  5. Use of Facebook Graph API to pull data and to authenticate user.

Application Planning

Here I will list what we want to achieve and how the Application will behave. So, 

  1. First setup a Facebook app in the Facebook development page.
  2. Burn all feeds in Feedburner.
  3. Application will fetch all data feeds from the Feedburner. This will be done by the YQL language.
  4. Make a jQuery Tab effect to display the feeds.
  5. Make a Facebook like pagination to list all the feeds in a pagination based page.

Download And Demo

  1. Do see it in action visit Here.
  2. To download the Tutorial Click Here.

So let's proceed with the Application Building. I will make it as easy as possible, but it is assumed that you have a knowledge of HTML, PHP, AJAX and jQuery.

Step 1. Creating The Application

  • To get started, login to Facebook account and go to https://developers.facebook.com/apps.
  • Click on the "Create New App" button. Then you will see this below image,
    Create New App Page
  • Then you have to fill up the Captcha.
  • On the submit, you will be presented the App Settings page. Here you have to fill up the following. Please keep in mind to make this application we do need these fields. Please see the below image for further reference.
    Application Setting page
    In the App Display Name, give your App's name. Then give a namespace, recommended in lowercase letters. Then the canvas URL should point to your Application hosting page URL. That is say, http://www.example.com/facebook/, if you have a directory called facebook in your domain. Secure Canvas URL is the secured URL with HTTPS.
  • Then all are done, go to Settings > Advanced Tab, navigate for Sandbox Mode, make it Enabled.
  • In the same page, Search for Canvas Settings. There, make the Canvas Width as Fixed and Canvas Height as Settable (Default: 800px).
    Application </p>
<p>Settings Advanced Page

Step 2. Burning the Feeds

Step 3. Set up Facebook SDK

  • In this step we have to setup the Facebook SDK. It is the PHP SDK so we need to include the lib file in the index page.
    <?php
    require_once 'lib/facebook.php';
     
    $app_id = 'Your APP ID';
    $fbconfig['appUrl'] = "CANVAS PAGE URL";
    $canvas_page = "CANVAS PAGE URL";
    $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page);
    $facebook = new Facebook(array(
    	'appId'  => 'APP ID',
      	'secret' => 'SECRET KEY',
      	'cookies' => 'true',
    ));
    ?>
  • Then using Facebook's Graph API we will validate user's authentication. To do that we need to add this code snippet.
    <?php
    $user = $facebook->getUser();
    if ($user) {
    	try {
    		// If the user has been authenticated then proceed
    		$user_profile = $facebook->api('/me');
    	} catch (FacebookApiException $e) {
    		error_log($e);
    		$user = null;
    	}
    }
    ?>
    <?php
    $logoutUrl = $facebook->getLogoutUrl();
    $yqlurl = "http://query.yahooapis.com/v1/public/yql?q=";
    $yqlurl .= urlencode("select * from feed where url='http://feeds.feedburner.com/tutology' LIMIT 5");
    $yqlurl .= "&format=json";
    $yqlfeed = file_get_contents($yqlurl, true);  
    $yqlfeed = json_decode($yqlfeed);
    $json_url ='https://graph.facebook.com/tutology';
    $json = file_get_contents($json_url);
    $json_output = json_decode($json);
    $likes = 0;
    if($json_output->likes){
    	$likes = $json_output->likes;
    }
     
    ?>

    Here, what we have done is,we are getting the $logoutUrl and also we will get the Feeds as JSON format with the help of YQL. Then at last we will use the Graph API to get likes for a specific page. In this case I have a Facebook page called tutology.

Step 4. Set up the jQuery

So far now, we have done the basic Facebook SDK setup and using of Graph API and also the jQuery Tabs coding. Next we will display the feeds.

  • Next, we will use the JavaScript to make the tab like display as in GUI. So, lets begin with the jQuery
    $(function () {
    	$(".tab_content").hide(); //Hide all content
    	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
    	$(".tab_content:first").show(); //Show first tab content
     
    	$("ul.tabs li").click(function() {
    		$("ul.tabs li").removeClass("active"); //Remove any "active" class
    		$(this).addClass("active"); //Add "active" class to selected tab
    		$(".tab_content").hide(); //Hide all tab content
    		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + 
     
    content
    		$(activeTab).fadeIn(); //Fade in the active content
    		return false;
    	});
    });

    To support the jQuery we have to make our HTML as the following,

    <div class="maincontent">
            	<ul class="tabs">
            		<li><a href="#tab1">Posts</a></li>
            		<li><a href="#tab2">About</a></li>
        		</ul>
                <div class="tab_container">
                     <div id="tab1" class="tab_content"></div>
                     <div id="tab2" class="tab_content"></div>
                </div>
    <div>

Step 5. Display Feeds

  • To display the feeds, we need to add the following code snippets to the App page.
    <div class="tab_container">
                	<div id="tab1" class="tab_content">
                        <?php $i=0; ?>
                        <?php if(!empty($yqlfeed->query->results->item)) : ?>
                        <?php foreach ($yqlfeed->query->results->item as $key => $item ) : ?>
                        	<div class="post <?php if($i == 0) {print 'selected';} ?>" id="<?php print $key;?>">
                            	<h3><a  href="<?php echo $item->link;?>" target="_blank"><?php echo $item->title;?></a></h3>
                                <span class="postInfo">by <a href="#"><?php echo $item->creator;?></a> on <?php echo substr($item->pubDate,0,-9);?></span>
                                <p><?php echo $item->description;?></p>
                                <span class="line"></span> 
                            </div>
                            <?php $i++; ?>
                        <?php endforeach; ?>
                        <?php else : ?>
                        	<div class="post">No Content to Display right now. Please try again later or reload the Page</div>
                        <?php endif;?>
                        <div class="facebook_style" id="facebook_style">
                    		<a id="<?php echo $key; ?>" href="#" class="load_more" >Show Older Posts <img src="images/arrow1.png" /> </a>
                    	</div>
                    </div>
                    <div id="tab2" class="tab_content">
                    	<h3>About Tutology</h3>
                        <p>Tutology - Where Tutorial and Technology meets</p>
                    </div>
                </div> <!-- /tab_container -->
  • Here, we iterated the JSON feeds in a foreach loop. Another point to note is that I have used a built in PHP function, subtr - substr($item->pubDate,0,-9). The reason why I have done this is due to some strange looking characters at the end of our date and time. This simply removes the last nine characters (-9), and leaves our date and time appearing as expected. Then as you can see in the code,I have added a div with class "facebook_style", this one is responsible for the Facebook like pagination.

Step 6. Display Pagination

  • To display the pagination we need to have a AJAX page that will handle the AJAX callback and a server side PHP page, which will process the AJAX request. We will do it in jQuery AJAX.
  • First we should have the jQuery AJAX page as the following code,
    $(function () {
    	$('.load_more').live("click",function() {
    		var last_msg_id = $(this).attr("id");
     
    		if(last_msg_id != 'end') {
    			$.ajax({
    				type: "POST",
    				url: "load_more.php",
    				data: "lastmsg="+ last_msg_id,
    				beforeSend:  function() {
    					$('a.load_more').append('<img src="images/facebook_style_loader.gif" />');
    				},
    				success : function(html) {
    					$(".facebook_style").remove();
    					$("#tab1").append(html);
    				}
    			});
    		}
    	});
    });
  • After the AJAX page, we need the PHP page that will handle the AJAX request. In this case I have it as load_more.php
    <?php
    if(isset($_POST['lastmsg']) &&is_numeric($_POST['lastmsg'])) {
    	$lastmsg = $_POST['lastmsg'];
    	$max_len = 30;
    	$next_increment = ($lastmsg + 2);
    	//Generating the YQL again
    	$yqlurl = "http://query.yahooapis.com/v1/public/yql?q=";
    	$yqlurl .= urlencode("select * from feed({$next_increment},5) where url='http://feeds.feedburner.com/tutology'");
    	$yqlurl .= "&format=json";
    	$yqlfeed = file_get_contents($yqlurl, true);  
    	$yqlfeed = json_decode($yqlfeed);
     
    	$i=0;
    	$html = '';
    	if(!empty($yqlfeed->query->results->item)) {
    		foreach ($yqlfeed->query->results->item as $key => $item ) {
    			if($i == 0) {
    				$selected = 'selected';
    			}
    			$key_id = ($next_increment + $key);
    			$html .= '<div class="post '.$selected.'" id="'.$key_id.'">';
    			$html .= '<h3><a  href="'.$item->link.'" target="_blank">'.$item->title.'</a></h3>';
    			$html .= '<span class="postInfo">by <a href="#">'.$item->creator.'</a> on '.substr($item->pubDate,0,-9).'</span>';
    			$html .= '<p>'.$item->description.'</p>';
    			$html .= '<span class="line"></span>';
    			$html .= '</div>';
    			//$html .= '';
    			$i++;
    		}
    		$html .= '<div class="facebook_style" id="facebook_style">';
        	$html .= '<a id="'.$key_id.'" href="#" class="load_more" >Show Older Posts <img src="images/arrow1.png" /> </a>';
        	$html .= '</div>';
    	} else {
    		$html .= '<div class="facebook_style" id="facebook_style">';
        	$html .= '<a id="end" href="#" class="load_more" >No More Posts</a>';
        	$html .= '</div>';
    	}
     
    	echo $html;
    }
    ?>

So after this long coding we are quite done to see the application in live. So go to your Canvas Page URL to see it in action. Please note, there are many areas that I have not discussed including the CSS styles and other some PHP code related sections which are meant to be understood by any PHP developer.

Rate this content: 

Average: 3.9 (7 votes)

Comments

Add new comment