Facebook请求权限示例?

时间:2013-03-07 21:17:38

标签: php javascript facebook authentication permissions

我一直在寻找一个关于如何使用facebook登录实现权限请求的实际示例,但我找不到任何。我能找到的只是权限的名称,有关要求的建议,但没有示例。

问题是:在哪里以及如何使用php或js请求权限?一些代码会非常有用。我是facebook新手,我已经开始阅读有关facebook登录和facebook api的所有内容,并尝试做几个小应用程序,所以我习惯了工作原理,但我有点卡住了。


编辑我找到了这段代码,这似乎是我一直在寻找的:

FB.login(function(response) {
  // handle the response
}, {scope: 'email,publish_actions'})

1 个答案:

答案 0 :(得分:6)

您应该从Facebook PHP SDK开始,关键是要了解服务器端登录流程,如here所述,您可以将此示例用作开头:

require 'facebook.php';

$facebook = new Facebook(array(
  'appId'  => 'YOUR_APP_ID',
  'secret' => 'YOU_APP_SECRET',
));

// Get User ID
$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.

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(array("scope" => "user_photos"));
}

?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <head>
    <title></title>
  </head>
  <body>    
    <?php if ($user): ?>
      <a href="<?php echo $logoutUrl; ?>">Logout</a>
    <?php else: ?>
      <div>
        <a href="<?php echo $loginUrl; ?>">Login with Facebook</a>
      </div>
    <?php endif ?>

    <h3>PHP Session</h3>
    <pre><?php print_r($_SESSION); ?></pre>

    <?php if ($user): ?>
      <h3>You</h3>
      <img src="https://graph.facebook.com/<?php echo $user; ?>/picture">

      <h3>Your User Object (/me)</h3>
      <pre><?php print_r($user_profile); ?></pre>
    <?php else: ?>
      <strong><em>You are not Connected.</em></strong>
    <?php endif ?>

  </body>
</html>