Trying to use oauth with facebook problems
Im trying to use this code to start building a simple facebook app but I cant seem to get to grips with the access token part so i can get the users birthday etc.
Can someone please take a look and let me know what im doing wrong :
<?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=开发者_如何学Pythonhttp://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'];
}
Okay, obviously you just copied the above code from somewhere...here are a couple of tips:
- Read the Canvas Tutorial
- The second OAuth request is not needed (
$token_url
) since if the user authorized your app you'll have theaccess_token
in thesigned_request
- Don't do multiple graph calls, one call will retrieve everything you need
- Don't print the
access_token
to the user - Make secure calls to the graph (
https
)
Here is a working code to get you started:
<?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>';
}
精彩评论