1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Basic FB app code - Seems to be working!

Discussion in 'FaceBook' started by nesterdwarf, Feb 12, 2011.

  1. nesterdwarf

    nesterdwarf Regular Member

    Joined:
    May 30, 2008
    Messages:
    276
    Likes Received:
    539
    Location:
    State of Misery...er, Missouri...
    Hello all,

    I've seen a couple of posts asking for the code that will do this or that on Facebook. I've been looking into building iframe apps for FB for the last couple of weeks and have cobbled together the code I'm sharing below. It works for what I have in mind so far, so hopefully it'll help some one else. Anyway, here we go...

    I'm not going to explain setting up an app, check out the Developers site to find the steps for that. It'll also give you ideas about what information you can get FB to give you ;)

    Code Explained:

    This section of the code shows the opening PHP tag and coding for setting up and connection to the DB. To implement this, you'll need to setup a database and supply the required details. You can add/remove the fields that you need to populate later in the script.

    Code:
    <?php
    ob_start();
    # Now lets load the DB details - Make sure and edit these for your specific setup.
    
    $db_server = "localhost";
    $db_username = "DATABASE_USERNAME";
    $db_password = "DATABASE_PASSWORD";
    $db_name = "DATABASE_NAME";
    
    # Lets connect to the Database and set up the table
    mysql_connect($db_server,$db_username,$db_password);
    mysql_select_db($db_name);
    $ct_res = mysql_query("CREATE TABLE IF NOT EXISTS `facebook_user` (
    	`session_key` VARCHAR( 80 ) NOT NULL ,
    	`uid` VARCHAR( 80 ) NOT NULL ,
    	`email` VARCHAR( 80 ) NOT NULL ,
    	`likes` VARCHAR( 80 ) NOT NULL ,
    	`expires` VARCHAR( 80 ) NOT NULL ,
    	`secret` VARCHAR( 80 ) NOT NULL ,
    	`access_token` VARCHAR( 120 ) NOT NULL ,
    	`sig` VARCHAR( 80 ) NOT NULL ,
    	`date` VARCHAR( 80 ) NOT NULL
    	);"
    );
    
    Here the script is loading the required functions to interact with the FB api. Also shown are some custom functions that I am using locally in my implementation that you can omit if you want.

    Code:
    # Now lets load the FB GRAPH API
    
    include_once ('facebook.php'); 
    include_once ('FB.class.php'); 
    
    # Custom Functions
    
    function now(){
    	global $t;
    	$t = time();
    	$d = (date("m-d-Y H:i:s",$t));
    	return $t;
    }
    
    function checkFan($l,$n){
    	global $facebook;
    	for($i = 0; $i < $n; $i++) {
    		$target = $facebook->getUser();
    		$v = $l['data'][$i]['id'];
    		$m = 'ID THAT YOU WANT TO LIKE';
    		if ($v == $m){
    			#$sql="UPDATE facebook_user SET likes = 'yes' WHERE uid = '$target';"; 
    			#$res = mysql_query($sql);
    			#return $l['data'][$i]['name'];
    			return 'yes';
    		}else{
    			return 'no';
    		}
    	}
    }
    
    Here we setup the application. You get this information from FB after setting up an application.

    Code:
    // Create our Application instance.
    
    global $facebook;
    $facebook = new Facebook(array(
      'appId'  => 'APPLICATION_ID',
      'secret' => 'APPLICATION_SECRET_KEY',
      'cookie' => false,
    ));
    
    Setting up the requested premissions when a FB user first accesses the application. This is the good stuff!

    Code:
    
    # Lets set up the permissions we need and set the login url in case we need it.
    
    $par['req_perms'] = "publish_stream,offline_access,email, user_likes";
    $loginUrl = $facebook->getLoginUrl($par);
    
    
    And finishing out the code are the functions that chech if a user has authorized the application and then what you want them to do next.

    Code:
    function get_check_session(){
    	global $facebook;
    	# This function basically checks for a stored session and if we have one it returns it, If we have no stored session then it gets one and stores it
    	# OK lets go to the database and see if we have a session stored
    	$sid=mysql_query("Select access_token from facebook_user");
    	$session_id=mysql_fetch_row($sid);
    	if (is_array($session_id)) {
    		# We have a session ID so lets not get a new one
    		# Put some session checking in here to make sure its valid
    		try {
    		$attachment =  array('access_token' => $session_id[0],);
    		$object_id=$facebook->getUser();
    		$ret_code=$facebook->api('/'.$object_id, 'GET', $attachment);
    		#$ret_code=$facebook->api('/me', 'GET', $attachment);
    		}
    		catch (Exception $e) {
    		# We don't have a good session so
    		$res = mysql_query('delete from facebook_user where expires=0');
    		return;
    	}
    		return $session_id[0];
    	} 
    	else 
    	{
    		# Are we coming back from a login with a session set? 
    		$session = $facebook->getSession();
    		if (is_array($session)) {
    			# Yes! so lets store it!
    			$sql="insert into facebook_user (session_key,uid,expires,secret,access_token,sig,date) VALUES ('".$session['session_key']."','".$session['uid']."','". $session['expires']."','". $session['secret'] ."','". $session['access_token']."','". $session['sig']."','".now()."');"; 
    			$res = mysql_query($sql);
    			return $session['access_token'];
    		}
    		
    	} 
    }
    
    
    $access_token=get_check_session();
    # If we've not got an access_token we need to login.
    if ( is_null($access_token) ) {
    	echo '<center><a href="'. $loginUrl.'" target=_top <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif"></a></center>';
    	$no_log = 'true';
    }
    
    else {
    	$target=$facebook->getUser();
    	$user = json_decode(file_get_contents('https://graph.facebook.com/'.$target.'?access_token='.$access_token));
    	$fname = $user ->{'first_name'};
    	$lname = $user ->{'last_name'};
    	$email = $user ->{'email'};
    	$user_likes = json_decode(file_get_contents('https://graph.facebook.com/'.$target.'/likes?access_token='.$access_token), true);
    	$num_likes = count($user_likes['data']);
    	}
    
    if($no_log == 'true'){
    	}else{
    		echo checkFan($user_likes, $num_likes);
    	}
    ?>
    
    This will let you control access to a registration form, allow you to autopost when a user takes an action, and any number of other things...fiddling with the above code will let you create whatever app you need! I've attached a zip file with the full code and the needed PHP includes.

    If anyone has enhancements they'd like to add feel free. I'm here to learn, too!

    HTH
    ND
     

    Attached Files:

    • Thanks Thanks x 7
    Last edited: Feb 12, 2011
  2. Darkone

    Darkone Junior Member

    Joined:
    Jul 11, 2009
    Messages:
    189
    Likes Received:
    21
    wow thanks a lot, i havent implemented this yet but it appears to do exactly what i want, ill just have to tweak a few things. Like how could i call the app to make the user share my site when they click on a download link on my site? got any idea? pm me or post here. once again thanks.
     
  3. nesterdwarf

    nesterdwarf Regular Member

    Joined:
    May 30, 2008
    Messages:
    276
    Likes Received:
    539
    Location:
    State of Misery...er, Missouri...
    Hey,

    Realized that I yanked the post to feed part out of the code for my app. Here it is-

    Code:
    $attachment =  array(
    			 'access_token' => $access_token,
    			  'message' => 'YOUR MESSAGE HERE',
    	      		  'name' => "SUBMESSAGE",
    	      		  'link' => "LINK",
    	      		  'description' => "DESCRIPOTION",
    			  'picture'=>"IMAGE",
    			);
    $ret_code=$facebook->api('/'.$target.'/feed', 'POST', $attachment);
    
    So the new $access_token variable would look like this -

    Code:
    $access_token=get_check_session();
    # If we've not got an access_token we need to login.
    if ( is_null($access_token) ) {
    	echo '<center><a href="'. $loginUrl.'" target=_top <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif"></a></center>';
    	$no_log = 'true';
    }
    
    else {
    	$target=$facebook->getUser();
            $attachment =  array(
    			 'access_token' => $access_token,
    			  'message' => 'YOUR MESSAGE HERE',
    	      		  'name' => "SUBMESSAGE",
    	      		  'link' => "LINK",
    	      		  'description' => "DESCRIPOTION",
    			  'picture'=>"IMAGE",
    			);
            $ret_code=$facebook->api('/'.$target.'/feed', 'POST', $attachment);
    	$user = json_decode(file_get_contents('https://graph.facebook.com/'.$target.'?access_token='.$access_token));
    	$fname = $user ->{'first_name'};
    	$lname = $user ->{'last_name'};
    	$email = $user ->{'email'};
    	$user_likes = json_decode(file_get_contents('https://graph.facebook.com/'.$target.'/likes?access_token='.$access_token), true);
    	$num_likes = count($user_likes['data']);
    	}
    
    if($no_log == 'true'){
    	}else{
    		echo checkFan($user_likes, $num_likes);
    	}
    
    Now every time someone access your app, it'll post to their wall. Then you just serve up the page with your download link.

    Try that out and see if it'll work for what you need.

    HTH
    ND
     
  4. theundertaker

    theundertaker BANNED BANNED

    Joined:
    Dec 1, 2010
    Messages:
    91
    Likes Received:
    4
    Did you recieve my pm?
     
  5. nesterdwarf

    nesterdwarf Regular Member

    Joined:
    May 30, 2008
    Messages:
    276
    Likes Received:
    539
    Location:
    State of Misery...er, Missouri...
    @theundertaker-

    I did and just replied. Any questions you might have, feel free to ask here. I'm just cobbling this together, so any question you have might help somebody else...including me!

    ND