duanpei8853 2013-05-13 12:46
浏览 102
已采纳

Facebook登录使用FB PHP sdk无法正常工作


I am working on login using FB id feature for my application and started with downloading the SDK for FB connect from GITHUB (facebook-php-sdk-master).

Within the application it has two examples 1) For Javascript api and 2) For PHP api. I want to use the PHP SDK to neglect the javascript disable feature in users website.
Now I entered my applications

    $facebook = new Facebook(array(
      'appId'  => 'deliberately blank',
      'secret' => '',
    ));

I logged in to facebook to check if its working and it always returns 0 even if the user logs in.
I just tried to print the user variable

   $user = $facebook->getUser();
   print_r($user); 

I checked the app settings and I have them correctly set for domain,URL and Canvas URL.I have also disabled the sandbox mode for it.
Is this an issue with the plugin as the session is not captured or I am doing something wrong here?
Anyone worked on or faced similar issue please share your insights as I am stuck and I tried to print the session data using $_SESSION which returns an array which has

Array ( [fb_117096311791424_state] => 5faba08750cd6456hbf27580df3b371 ) 

But I don't get the user info.Is there any other way to achieve it?Any alternative API etc?

UPDATE for code:

define('HTTP_SERVER', "http://".$_SERVER["HTTP_HOST"]); // eg, http://localhost - should not be empty for productive servers
define('HTTPS_SERVER', ''); // eg, https://localhost - should not be empty for productive servers
define('BASE_URL', HTTP_SERVER.'/'); // eg, https://localhost - should not be empty for productive servers

if(HTTP_SERVER == 'http://localhost'){
    define('DOCUMENT_SERVER', $_SERVER['DOCUMENT_ROOT'].'/XYZ/');
}else{
    define('DOCUMENT_SERVER', $_SERVER['DOCUMENT_ROOT'].'/'); 
}
require(DOCUMENT_SERVER.'includes/applicationTop.php');
$dataObj = new Database();
$generalObj = new General();

file_get_contents('http://www.ABC.com/login/facebookConnect/fbmain.php');
//require_once('http://www.ABC.com/login/facebookConnect/fbmain.php');

/**
* check if user login first time or second time with facebook, records stored in table and session.
**/

if (!empty($user))
{
$firstName = $userInfo['first_name'];
$lastName = $userInfo['last_name'];
$userName = $userInfo['username'];
$gender = $userInfo['gender'];
$email = $userInfo['email'];
$birthday = $userInfo['birthday'];

$userImage = $fqlResult[0]['pic_square'];
$addressName = $fqlResult[0]['hometown_location']['name'];
$addressCity = $fqlResult[0]['hometown_location']['city'];
$addressState = $fqlResult[0]['hometown_location']['state'];
$addressCountry = $fqlResult[0]['hometown_location']['country'];
$addressZip = $fqlResult[0]['hometown_location']['zip'];

$ip = $_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d');

$accountId = strtolower($generalObj->fnCreatePassword(8));


/**
* check user first time login or not with facebook login.
**/

$queryUser = "SELECT tbl_login.userId,tbl_login.accountId,tbl_login.emailId FROM tbl_login WHERE tbl_login.emailId='$email'";
$resultUser = $dataObj->tep_db_query($queryUser);
$userInfo = $dataObj->getRecord($resultUser);
$checkUser = $dataObj->getNumRows($queryUser);

if($checkUser == '0' || $checkUser == '')
{
    /**
    * if user first time login with facebook then records are inserted into table.
    **/
    $qyery = "INSERT INTO ".TABLE_LOGIN." (accountId, emailId,activeFlag,facebook_Userid) VALUES('$accountId','$email','1','$username')";
    $data = $dataObj->tep_db_query($qyery);
    $userID = $dataObj->tep_db_insert_id();
    if(!empty($userID))
    {   
        $sql = "INSERT INTO ".TABLE_USER_INFO." (userId,fName,lName,address,city,country,state,postalCode,emailId,user_dob,profile_Image,user_ip,user_date,activeFlag) VALUES('$userID','$firstName','$lastName','$addressName','$addressCity','$addressCountry','$addressState','$addressZip','$email','$birthday','$userImage','$ip','$date','1')";
        $data = $dataObj->tep_db_query($sql);
    }
    //$_SESSION["gobiggiuserFaceBook"] = true;
    $_SESSION["UserId"] = $userID;
    $_SESSION["username"] = $accountId;
    $_SESSION["emailId"] = $email;
    $_SESSION["ProfileImage"] = $userImage;

}
else
{
    /**
    * updated user's info incase user has been updated own profile's records on facebook.
    **/
    //QUery for update

    /**
    * If user have already login with facebook then records are taking into session
    **/

    $_SESSION["UserId"] = $userInfo['userId'];
    $_SESSION["username"] = $userInfo['accountId'];
    $_SESSION["emailId"] = $userInfo['emailId'];
    $_SESSION["ProfileImage"] = $userImage['profile_Image'];    

}

$sessionUserid = (!empty($_SESSION["UserId"])) ? $_SESSION["UserId"] : '' ; 

if(!empty($sessionUserid)){
    echo "herererere in dashboard part";
    //exit;
    header("Location:".USER_DASHBOARD."userDashboard.php");
    exit();
    //$generalObj->tep_redirect(FILE_PATH.'userDashboard.php');
}else{
    echo "herererere in login part";
    exit;
    header("Location:".LOGIN."login.php");
    exit();
    //$generalObj->tep_redirect(FILE_PATH.'login.php');
}
}
else
{
    //echo LOGIN.USER_DASHBOARD;
    //exit();
    /*I always end up here*/
    header("Location:".LOGIN."login.php");
    exit();
    //$generalObj->tep_redirect(FILE_PATH.'login.php');
}

This is the fbmain.php

$fbconfig['appid' ]     = "deliberately blank";
$fbconfig['secret']     = " ";
$fbconfig['baseurl']    = "http://www.ABC.com/login/facebookConnect/facebookHome.php"; 


if (isset($_GET['request_ids'])){
    //user comes from invitation
    //track them if you need
}

$user            =   null; //facebook user uid
try{

    require_once "facebook.php";
}
catch(Exception $o){
    error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => $fbconfig['appid'],
  'secret' => $fbconfig['secret'],
  'cookie' => true,
));

//Facebook Authentication part
$user       = $facebook->getUser();
// We may or may not have this data based 
// on whether the user is logged in.
// If we have a $user id here, it means we know 
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
//print_r($user);
//exit;
$loginUrl   = $facebook->getLoginUrl(
        array(
            'scope'         => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown',
            'redirect_uri'  => $fbconfig['baseurl']
        )
);

$logoutUrl  = $facebook->getLogoutUrl();

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    //you should use error_log($e); instead of printing the info on browser
    d($e);  // d is a debug function defined at the end of this file
    $user = null;
  }
}


//if user is logged in and session is valid.
if ($user){
    //get user basic description
    $userInfo           = $facebook->api("/$user");
   // print_r($userInfo);
    //Retriving movies those are user like using graph api
    try{
        $movies = $facebook->api("/$user/movies");
    }
    catch(Exception $o){
        d($o);
    }

    //update user's status using graph api
    //http://developers.facebook.com/docs/reference/dialogs/feed/
    if (isset($_GET['publish'])){
        try {
            $publishStream = $facebook->api("/$user/feed", 'post', array(
                'message' => "", 
                'link'    => '',
                'picture' => '',
                'name'    => '',
                'description'=> ''
                )
            );
            //as $_GET['publish'] is set so remove it by redirecting user to the base url 
        } catch (FacebookApiException $e) {
            d($e);
        }
        //echo "login successs!!!";exit;
        $redirectUrl     = $fbconfig['baseurl'] . '/login.php?success=1';
        header("Location: $redirectUrl");
    }

    //update user's status using graph api
    //http://developers.facebook.com/docs/reference/dialogs/feed/
    if (isset($_POST['tt'])){
        try {
            $statusUpdate = $facebook->api("/$user/feed", 'post', array('message'=> $_POST['tt']));
        } catch (FacebookApiException $e) {
            d($e);
        }
    }

    //fql query example using legacy method call and passing parameter
    try{
        $fql    =   "select name, hometown_location, sex, pic_square from user where uid=" . $user;
        $param  =   array(
            'method'    => 'fql.query',
            'query'     => $fql,
            'callback'  => ''
        );
        $fqlResult   =   $facebook->api($param);
    }
    catch(Exception $o){
        d($o);
    }
}

function d($d){
    //echo '<pre>';
    //print_r($d);
    //echo '</pre>';
}

The other files are from the SDK itself.

Regards

  • 写回答

1条回答 默认 最新

  • duangan6133 2013-05-13 13:41
    关注

    1. Change file_get_contents('file_path'); to require_once('file_path');

    2. In else condition, where you are checking 1st time user, you have used

    $_SESSION["UserId"] = $userInfo['userId'];
    $_SESSION["username"] = $userInfo['accountId'];
    $_SESSION["emailId"] = $userInfo['emailId'];
    $_SESSION["ProfileImage"] = $userImage['profile_Image']; 
    


    All these values are wrong, I mean the index used for $userInfo are wrong! Instead use as follows:

    $_SESSION["UserId"] = $userInfo['id']; //or $user
    $_SESSION["username"] = $userInfo['username']; 
    $_SESSION["emailId"] = $userInfo['email'];
    $_SESSION["ProfileImage"] = $userImage; //not $userImage['profile_Image']
    


    Just these two changes, and you are through.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题