Search code examples
phpfacebook-php-sdkfacebook-apps

Simple Facebook App With Php Sdk


I just need simple and working facebook app. I bought ssl for this and i dont want too much expenses.

If user allowed app it will write his name and gender and his/her friends gender.

my app doesnt redirect after user allow the app. I cant fix it so just need basic app with out url redirecting.

ı used this code but it doesnt work. it need to be corrected:

require_once("facebook.php");
$facebook = new Facebook(array(
    'appId'  => '***',
    'secret' => '***',
  'scope'  => 'manage_pages,offline_access,publish_stream,user_photos'
));

$user = $facebook->getUser();

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    $user = null;
  }
}

if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl();
}

Solution

  • Here is the simple one page application full fills your needs

    make the file with name index.php

    download the facebook library download here

    <?php 
    
    require_once 'library/facebook.php';
    
    
    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId' => 'appid',
      'secret' => 'secret',
      'cookie' => true,
    )); 
    
         $app_id = 'appid';
    
         $canvas_page = "canvas_page_link";
    
    
         $auth_url = "http://www.facebook.com/dialog/oauth?client_id=" 
                . $app_id . "&redirect_uri=" . urlencode($canvas_page) . ("&scope=email,read_stream&response_type=token");
    
         $signed_request = $_REQUEST["signed_request"];
    
         list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
    
         $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
    
         if (empty($data["user_id"])) {
                echo("<script> top.location.href='" . $auth_url . "'</script>");
         } else {
    
         //getting the userid and some other data for verification 
    
         //get the user id 
                $UserId = $data["user_id"];
                echo 'UserId;' . $UserId;
    
        //get the user access token
                $token = $facebook->getAccessToken();
                echo "</br>" . 'Access_Token:' . $token;
    
        //set default access token and profile
                $facebook->setAccessToken($token);
                $user_profile = $facebook->api('/me');
    
         //get the user name 
                $user_id = $facebook->getUser();
                $user_profile = $facebook->api('/me','GET');
                $user_name = $user_profile['name'];
                echo "Name: " . $user_name;
                $user_gender = $user_profile['gender'];
                echo "Gender: " . $user_gender;
    
    } 
    ?>