简体   繁体   English

使用javascript SDK登录后如何Facebook getuser()

[英]How to facebook getuser() after login with javascript SDK

So I have to ask for extended permission by clicking the enter button, but after the login is necessary to refresh the page in order to display the app. 因此,我必须通过单击Enter按钮来请求扩展权限,但是登录后必须刷新页面才能显示该应用程序。 Here's my code: 这是我的代码:

<?php
require 'facebook.php';
$facebook = new Facebook(array(
  'appId'  => '< THE APPID >',
  'secret' => '< THE SECRET >',
  'cookie' => true,
));
$user = $facebook->getUser();

if ($user) {
  try {
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}
?>
<body>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {

    FB.init({
      appId      : '< THE APPID >',
      status     : true,
      cookie     : true,
      xfbml      : true
    });

    // Additional initialization code such as adding Event Listeners goes here
    $('#btn-enter').click(function(){
        login();
    });

  };
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));

    function login() {
        FB.login(function(response) {
            if (response.authResponse) {        
                // connected
            } else {
                // cancelled
            }
        //});
        }, {scope: 'read_friendlists,friends_photos,publish_stream'});
    }
</script>
<?php if ($user): ?>
    <!--Here is my APP-->
<?php else: ?>
<a id="btn-enter">Enter</a>
<?php endif ?>

Is there a better way to do this ? 有一个更好的方法吗 ? What works for me is: 对我有用的是:

function login() {
    FB.login(function(response) {
        if (response.authResponse) {
            top.location.href='https://the_app_url';            
        } else {
        }
    //});
    }, {scope: 'read_friendlists,friends_photos,publish_stream'});
} 

But this causes the entire page to refresh and is not 'elegant' per se... 但这会导致整个页面刷新,并且本身并不“优雅”。

After the user authentication, you can call the graph API by the Javascript SDK and issue a request to /me . 用户身份验证后,您可以通过Javascript SDK调用图形API并向/me发出请求。

The response will contain an object with the user's info. 响应将包含一个带有用户信息的对象。

Here's how: 这是如何做:

if (response.authResponse) {
      FB.api('/me', function(response) {
        alert(response.name);
   });  
} 

Read more about it in the Facebook Developers site . Facebook Developers网站上阅读有关它的更多信息。

 require_once("facebook.php");
 $fbconfig['appid' ]     = "APPID";
 $fbconfig['secret']     = "SECRET";
 $fbconfig['baseurl']    = "BASEURL"; 
 $user            =   null; //facebook user uid
 $facebook = new Facebook(array(
  'appId'  => $fbconfig['appid'],
  'secret' => $fbconfig['secret'],
  'cookie' => true,
 )); 
 //Facebook Authentication part
    $user       = $facebook->getUser();
    //Login URL
    $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']
            )
    );
    //Logout URL
    $logoutUrl  = $facebook->getLogoutUrl();
    if ($user){
        //get user basic description
        try {
          // Proceed knowing you have a logged in user who's authenticated.
          $user_profile = $facebook->api('/me');
          $_SESSION['fbid'] = $user_profile['id'];
          $_SESSION['logout'] = $logoutUrl;
        } 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;
        }
    }
$me = $user_profile;
//print_r($me);
//////////////////////////INSERTING DATA ON USER-RECORD FOR FACEBOOK USER/////////////////
if($_SESSION['fbid']){ 
$find_dup=$jeob->SqlQuery("select * from je_user_record where personal_id='".$me['id']."' AND first_name='".$me['first_name']."' AND last_name='".$me['last_name']."' AND email='".$me['email']."' AND oauth_provider='face' ");
//If no record in database
if($jeob->SqlRows($find_dup)=="0")
{
$insquery=mysql_query("insert into je_user_record (personal_id,first_name,last_name,email,oauth_provider) values('".$me['id']."','".$me['first_name']."','".$me['last_name']."','".$me['email']."','face')");
$faceuserid=mysql_insert_id();
    $_SESSION['userid'] =$faceuserid;
    $_SESSION['oauth_provider']= 'face';
//    header("location:index.php");
}
//if record found in database
//////////IF  RECORD FOUND IN DB//////////////////
else
{
    while($ff=mysql_fetch_array($find_dup))
    {
        $_SESSION['userid']=$ff['user_id'];
        $_SESSION['oauth_provider']= 'face';
    }
}

//Insert friend's ID on DB

        $fql    =   "SELECT uid,name,username,email,pic_square FROM user WHERE uid = me() OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
            $param  =   array(
            'method'    => 'fql.query',
            'query'     => $fql,
            'callback'  => ''
            );
            $friend_list   =   $facebook->api($param);
            /*$i=1;*/
            foreach($friend_list as $rec)
            {
            $frnname = $rec['name'];
            $frnid = $rec['uid'];
            $referid = $me['id'];
        $insert_table="fb_friends";
            $query=$jeob->SqlQuery("select * from ".$jeob->dbprefix.$insert_table." where refer_id='$referid' AND friends_id='$frnid' "); 
            if($jeob->SqlRows($query)=="0")
            {
                $insert_qry=array(
                "friends_id"=>"$frnid",
                "friend_name"=>"$frnname",
                "refer_id"=>"$referid");
                $jeob->SqlInsert($insert_table,$insert_qry);
            }
            else                    
            {                       //  if no record
            }                     
        }

} // end facebook session 
?>

In the above code after facebook user authentication their friends information is accessed and inserted into db. 在上面的代码中,经过facebook用户身份验证后,他们的朋友信息被访问并插入到db中。 I think this may helps you. 我认为这可能对您有帮助。 This code also clear the problem of refreshing the page after login with facebook 此代码还清除了使用Facebook登录后刷新页面的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM