试图将oauth用于facebook问题

时间:2011-09-29 14:30:05

标签: php facebook

我试图使用此代码开始构建一个简单的Facebook应用程序,但我似乎无法掌握访问令牌部分,所以我可以得到用户生日等。

有人可以看看,让我知道我做错了什么:

<?php 
$app_id = "*********";
$canvas_page = "https://apps.facebook.com/hotness-battle/";

$auth_url = "https://www.facebook.com/dialog/oauth?client_id=" 
. $app_id . "&redirect_uri=" . urlencode($canvas_page) . '&scope=email,user_birthday';

$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

if (empty($data["user_id"])) {
    echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
    $token_url = 'https://graph.facebook.com/oauth/access_token?client_id=200482573356726&redirect_uri=http://www.impact25.com/hotness-battle/&client_secret=*******&code='.$data['oauth_token'].'';
    echo("<script> top.location.href='" . $token_url . "'</script>");

    $uid = $data["user_id"];
    $token = $data['oauth_token'];
    $full_name = json_decode(file_get_contents('http://graph.facebook.com/'.$uid))->name;
    $gender = json_decode(file_get_contents('http://graph.facebook.com/'.$uid))->gender;
    $birthday = json_decode(file_get_contents('http://graph.facebook.com/'.$uid.'?access_token='.$token))->birthday;
    echo $full_name;
    echo '<br><br>';
    echo $gender;
    echo '<br><br>';
    echo $token;
    echo '<br><br>';
    echo $cookie['access_token'];
}

1 个答案:

答案 0 :(得分:0)

好的,显然你只是从某个地方复制了上面的代码......这里有几个提示:

  1. 阅读Canvas Tutorial
  2. 不需要第二个OAuth请求($token_url),因为如果用户授权您的应用,您将拥有access_token
  3. 中的signed_request
  4. 不要进行多次图形调用,一次调用将检索您需要的所有内容
  5. 不要将access_token打印给用户
  6. 对图表进行安全调用(https
  7. 这是一个可以帮助您入门的工作代码:

    <?php 
    $app_id = "APP_ID";
    $canvas_page = "https://apps.facebook.com/appnamespace";
    
    $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" 
    . $app_id . "&redirect_uri=" . urlencode($canvas_page) . '&scope=email,user_birthday';
    
    $signed_request = $_REQUEST["signed_request"];
    list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
    $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
    
    if (empty($data["user_id"])) {
        echo("<script> top.location.href='" . $auth_url . "'</script>");
    } else {
    
        $uid = $data["user_id"];
        $token = $data['oauth_token'];
        $graph_url = 'https://graph.facebook.com/' . $uid . '?access_token=' . $token;
    
        $user_info = json_decode(file_get_contents($graph_url));
        $full_name = $user_info->name;
        $gender = $user_info->gender;
        $birthday = $user_info->birthday;
    
        echo $full_name;
        echo '<br><br>';
        echo $gender;
        echo '<br><br>';
        echo $birthday;
        echo '<br><br>';
    }