确保Facebook用户在登录前“注册”

时间:2012-04-14 17:12:26

标签: php facebook

如果我在我的网站上放置登录按钮,用户将能够只登录 - 实际上不需要注册,我如何确保“用户”实际注册(所以我可以保存数据)我的数据库)才能真正登录?

我的索引代码......

<?php

require '../src/facebook.php';

$facebook = new Facebook(array(
  'appId'  => '*id trimmed*',
  'secret' => '*secret trimmed*',
));

// See if there is a user from a cookie
$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) {
    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) { ?>
      Your user profile is
      <pre>
        <?php print htmlspecialchars(print_r($user_profile, true)) ?>
      </pre>
    <?php } else { ?>
      <fb:login-button>Logga in med Facebook</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.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>

1 个答案:

答案 0 :(得分:0)

只需将facebook中的用户ID与您的数据库进行比较(如果存在)&gt;登录,否则 - &gt;寄存器:

// ...
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;
  }
}

if ($user)
{
  $id = $user_profile['id']; // facebook user id;
  // now use this $id to compare with your database saved user facebook user id
  // if not exists, then create user, else update login counter or only get profile
}
//...