I'm trying to write PHP code that will display the logged in user's name. So far I've got it to display the user's id but I can't get the name to show.
<?php
$app_id = "...";
$canvas_page = "...";
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
开发者_如何转开发 . $app_id . "&redirect_uri=" . urlencode($canvas_page);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode($payload), true);
if (empty($data["user_id"])){
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data['user_id']);
}
?>
Changing 'user_id' to 'name' or 'first_name' doesn't show anything.
You need to hit the /me
API to get user data.
If using PHP, why don't you check out the PHP SDK?
Recommend to use with Facebook PHP SDK.
You can call like that
try {
$me = $facebook->api('/me');
print_r($me);
echo $me['name'];
} catch (FacebookApiException $e) {
error_log($e);
}
It is also much shorter and easy to use PHPforFB framework (http://www.phpforfb.com/en).
The code looks like this:
include(‘phpforfb_framework.php’);
$FacebookAPP = new PHPforFB($structInit);
//Query basic permissions.
if(($res = $FacebookAPP->ForcePermissions('basic')) === FALSE){
//An error occurred when querying the permissions
echo "PHPforFB Error: ".$FacebookAPP->lastErrorCode." -> ".$FacebookAPP->lastError;
exit;
}else{
//Evaluate the result
if($res==0){
//The user declined.
}else{
//The user accepted to grant permissions to the application.
$res = $FacebookAPP->GetUserInfo();
print_r($FacebookAPP->userData);
}
}
精彩评论