0

我正在使用 Facebook登录按钮在我的网站中与 facebook 集成。但是,我不知道如何在通过 facebook 登录时将用户名等(facebook 上的用户数据)从 facebook 保存到我的数据库中。如何做到这一点?

目前,当点击facebook登录按钮时,会打开一个窗口,我们可以输入facebook用户名和密码,它就会被连接。

如何在登录时进入 php 部分以在 facebook 上存储用户数据,如果已经存在登录到站点而不存储任何数据?

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=987654321";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>


   // facebook login button

<div class="fb-login-button" data-show-faces="false" data-width="200" data-max-rows="1" ></div>
4

1 回答 1

1

请下载 facebook php sdk。

以下是连接到 facebook 的示例。

<?php session_start();
require 'src/facebook.php';
$facebook = new Facebook(array(
  'appId'  => 'YOUR_APP_ID',
  'secret' => 'YOUR_APP_SECRET',
));

// See if there is a user from a cookie
$user = $facebook->getUser();
//$session = $facebook->getSession();
if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    //echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
    $user = null;
  }
}
?>

<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <body>
    <?php if ($user) { 
    foreach($user_profile as $skey => $sval)
    {
        $_SESSION["$skey"]=$sval;   
    }   
    $_SESSION['fb_name']=$user_profile['name']; //get facebook username and set it in session
    $_SESSION['fb_id']=$user_profile['id']; //get facebook id and set it in session
    $logoutUrl = $facebook->getLogoutUrl();
    $_SESSION['fb_logout']= $logoutUrl;

     ?>
      <pre>            
        <?php //print htmlspecialchars(print_r($user_profile, true)) ?>
      </pre> 
    <?php } else { ?>
      <fb:login-button></fb:login-button>
    <?php } ?>
    <div id="fb-root"></div>
    <script>               
      window.fbAsyncInit = function() {
        FB.init({
          appId: '<?php echo $facebook->getAppID() ?>', 
          cookie: true, 
          xfbml: true,
          oauth: true
        });
        FB.Event.subscribe('auth.login', function(response) {
    window.location.href="index.php";
          //window.location.reload();
        });
        FB.Event.subscribe('auth.logout', function(response) {
          window.location.reload();
        });
      };
      (function() {
        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);
      }());
    </script>
  </body>
</html>

在登录部分检查这样

if(isset($_SESSION['fb_id'])) {
//check whether the entry for this fb_id already exists in db
//if not exists insert id and name into db, else get username from db for this fb_id
}
于 2012-04-16T12:24:07.830 回答