已签名的请求示例并获取访问令牌

时间:2011-09-07 19:30:35

标签: facebook facebook-access-token

在下面的代码中,有一个永远不会定义的变量。该变量是$ access_token。需要添加代码以获取新的访问令牌,以便程序可以执行而不会产生任何异常。我一直在阅读关于oauth流等的Facebook文档,但我似乎无法弄清楚如何获得这些代码可以接受的访问令牌之一。有谁知道这可以做些什么?

<?php

define('YOUR_APP_ID', 'x');
define('YOUR_APP_SECRET', 'x');

function get_facebook_cookie($app_id, $app_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
  ksort($args);
  $payload = '';
  foreach ($args as $key => $value) {
    if ($key != 'sig') {
      $payload .= $key . '=' . $value;
    }
  }
  if (md5($payload . $app_secret) != $args['sig']) {
    return null;
  }
  return $args;
}

$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);

$access_token="214620421927216|fAAieRnJoDaWmBsG1stxfq4zKN4";
$url = 'https://graph.facebook.com/me?access_token=' . $access_token;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

$user = json_decode($response);
print_r($user);

?>
<html>
  <body>
    <?php if ($cookie) { ?>
      Welcome <?php  ?>
    <?php } else { ?>
      <fb:login-button></fb:login-button>
    <?php } ?>
    <div id="fb-root"></div>
    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
      FB.init({appId: '<?= YOUR_APP_ID ?>', status: true,
               cookie: true, xfbml: true});
      FB.Event.subscribe('auth.login', function(response) {
        window.location.reload();
      });
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

此代码证明在获取正确的访问令牌方面更有用。

<?php 

$app_id = "YOURS";
$app_secret = "YOURS";
$my_url = "YOURS";

session_start();
$code = $_REQUEST["code"];
echo $code . "</br>";

if(empty($code)) {

$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");

}

if($_REQUEST['state'] == $_SESSION['state']) {

$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code;

$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);

$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];

$user = json_decode(file_get_contents($graph_url));
    echo("Hello " . $user->name);
}    
else {
    echo("The state does not match. You may be a victim of CSRF.");
}

?>