php - 删除facebook app URL中的“code”param

时间:2011-08-10 14:50:28

标签: php facebook url parameters

我现在已经完成了我的Facebook应用程序并且它可以工作,但是,当用户首先使用该应用程序时,我会将它们重定向到facebook文档中给出的http://apps.facebook.com/myapp/

$app_id = "123456789";

$canvas_page = "http://apps.facebook.com/myapp/";

$auth_url = "http://www.facebook.com/dialog/oauth?client_id=".$app_id."&redirect_uri=".urlencode($canvas_page)."&scope=email,publish_stream";
$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 {
    echo "Welcome User: " . $data["user_id"]."<br/>";
    // UPDATE CODE START
    // below code from facebook docs
    $app_secret = "asdfghjkl1234567890qwerty";
    $my_url = "http://apps.facebook.com/myapp/";

    session_start();
    $code = $_REQUEST["code"];

    if(empty($code)) {
        $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
        $dialog_url = "http://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.");
    }
    // UPDATE CODE END
}
die();

问题是在浏览器网址中它看起来类似于以下内容:

http://apps.facebook.com/myapp/?code=saydyab7da976dgas976gdas6gdas6gd06asgd86ags0d6g...etc

什么是“代码”参数以及它为什么存在,我该如何摆脱它?

此致

1 个答案:

答案 0 :(得分:1)

您需要使用code来获取访问令牌。在此之前,您还没有完成身份验证过程。

从文档中获取该代码后,您需要将其发送到Facebook Graph API:

https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE

总而言之,Facebook OAuth身份验证是一个两步过程,您只完成了其中一个步骤。

谢谢!