3

我的主页是index.php. 在这里,我执行用户登录,然后重定向到url.php使用 ajax 请求。现在用户可以移动到不同的页面。

我需要这些页面上的当前用户 facebook id。我怎么才能得到它?

登录.php

 <script type="text/javascript">
    window.fbAsyncInit = function() {
      FB.init({
        appId: '<?php
        echo $appId;
        ?>',
        cookie: true,
        xfbml: true,
        //  channelUrl: '<?php
        echo $return_url;
        ?>channel.php',
        oauth: true}
             );
    };
    (function() {
      //alert("1");
      var e = document.createElement('script');
      e.async = true;
      e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';
      document.getElementById('fb-root').appendChild(e);
    }());
    function CallAfterLogin(data,callback){
      FB.login(function(response) {
        if (response.status === "connected")
        {
          LodingAnimate();

          FB.api('/me?fields=movies,email,name', function(mydata) {

              $.post('movies_db.php',{'myd':a, name: name, email: email, myid:myid}, function(data) 
                     {
                       $.ajax({
                         url:'url.php'
                         ,async:     true
                         ,type : 'POST'
                         ,cache:     false
                         ,data : 'myid=' + myid
                         ,dataType:  'html'
                         ,success:   function(data){
                           $('body').html(data);
                           FB.XFBML.parse();
                         }
                       }

我以这种方式尝试过:在 url.php/ 或我想要获取会话信息的任何页面上

$id= $_SESSION['fb_<appID>_user_id'];
echo "X is $id";

另一个使用 php sdk 的尝试:

require_once("facebook.php"); //given correct path

$config = array();
$config['appId'] = '1788xxxxxx2';
$config['secret'] = '390c04c60xxxxxxxxx68aca44';

$facebook = new Facebook($config);

$appId = $facebook->getAppId();  //gives correctly
$uid = $facebook->getUser();   //always 0
echo "$uid";

再试一次:

<?php
session_start();
print $_SESSION['fb_<myAppID>'];  //prints correct
//print $_SESSION['fb_<userID>'];
print $_SESSION['fb_<myAppID>_user_id'] = '<user_id>';  //does not print anything
//echo "id :$x";
?>

没运气。还有什么想法吗?或者这里的错误在哪里?

4

2 回答 2

6

更新

JS (jQuery)

script.js

  $('#login').click( function(e){

      e.preventdefault;

        FB.login(function(r) {
        if (r.authResponse) {
            var accessToken = r.authResponse.accessToken;
            $.ajax({ 
                type     : "GET",
                url      : "set-session.php",
                data     : { accessToken : accessToken },
                datatype : 'json',
                success  : function(user) {
                                    $('p').fadeOut( function() { 
                                         $('p').html('Hey, Good to see you <a href='+ user.link +'>'+ user.first_name +'</a>!</p>');
                                         $('p').fadeIn();
                                    });
                                    $('#login').fadeOut().remove();
                           },
                error    : function() {
                                    $('p').fadeOut( function() { 
                                         $('p').html('Something went wrong :( try again');
                                         $('p').fadeIn();
                                    });          
                           }
            });
        } else {
            $('p').fadeOut( function() { 
                 $('p').html('You didn\'t authorize the app');
                 $('p').fadeIn();
            }); 
          }
      });

    });

PHP

set-session.php

<?php
require_once 'facebook-sdk/facebook.php';
header('Content-Type: application/json');

if ( isset($_GET['accessToken']) && !empty($_GET['accessToken']) ) {

        $accessToken = $_GET['accessToken'];
        $facebook    = new Facebook(array(
                                    'appId'  => '1419692231579671',
                                    'secret' => 'd69245290e6c6fb1346faa32437652c5',
                                    'cookie' => true
        ));

        # set the access_token for $facebook for future calls
        $facebook->setAccessToken($accessToken);

        try {

             $userData = $facebook->api('v2.0/me');
             # register a new session for the user, containing their basic information, id, username, first_name, last_name, profile_picture
             # and another one for the access_token.
             $_SESSION['fb-user-token'] = $accessToken;
             $_SESSION['fb-user']       = $userData;

             echo json_encode( array('id'         => $userData['id'],
                                     'link'       => $userData['link'],
                                     'username'   => $userData['uesrname'],
                                     'first_name' => $userData['first_name'],
                                     'last_name'  => $userData['last_name'],
                                     'gender'     => $userData['gender']      ), JSON_PRETTY_PRINT);

        } catch (FacebookApiException $e) {

           error_log($e);

        }

} else {
   header('HTTP/1.1 400');
}

指数

index.php

<?php
if ( isset($_SESSION['fb-user']) ) {
    $user = $_SESSION['fb-user'];
?>
    <div>
       <p>Hey, Good to see you <a href="<?php echo $user['link'] ?>"><?php echo $user['first_name']; ?></a>!</p>
    </div> 
<?php
    } else {
?>
    <div>
       <p>Hey there, Login with your Facebook</p>
    </div>
    <a class="fsl fsl-facebook" href="#" id="login">
       <span class="fa-facebook fa-icons fa-lg"></span>
       <span class="sc-label">Login W/ Facebook</span>
    </a>    

<?php  
}
?>

演示

您可以在GitHub 上下载并为该存储库做出贡献

于 2013-10-20T21:32:53.147 回答
1

Index.php ajax: 使用 php sdk 方法进行身份验证,登录时单页重新加载。

<script>
    function TestAjaxSession(pid){
    var thisxmlhttp = "xmlhttp"+pid+"";
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      thisxmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      thisxmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    thisxmlhttp.onreadystatechange=function()
      {
      if (thisxmlhttp.readyState==4 && thisxmlhttp.status==200)
        {
       document.getElementById(pid).innerHTML=thisxmlhttp.responseText;
        }
      };
      thisxmlhttp.open("GET","session.test.php" ,true);
      thisxmlhttp.send();
    };
</script>

<div id="sessiontest"><div>
<script>TestAjaxSession('sessiontest');</script>

被调用页面: " session.test.php" 注意: 前面没有空格 session_start();

<?php
session_start();
echo '<pre>';
if($_SESSION){
print_r($_SESSION['fb_135669679827333_user_id']);
}else{
echo 'No session detected';
}
echo '</pre>';
?>
于 2013-10-20T18:43:32.967 回答