I have now finished my facebook app and it works, But, when a user first autherises to use the app, i then redirect them to http://apps.facebook.com/myapp/ as given in the facebook documentation.
$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();
The problem is that in the browser url it looks similar to the following:
http://apps.facebook.com/myapp/?code=saydyab7da976dgas976gdas6gdas6gd06asgd86ags0d6g...etc
What is the "code" parameter and why is it there and how do i get rid of it?
Regards
You need to use that code
to get an access token. Until then, you have not yet finished the authentication process.
From the documentation, after you obtain that code, you need to send it to the 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
To summarize, Facebook OAuth authentication is a two step process, you have only done one of the steps.
Thanks!
精彩评论