0

Issue : The users access token is available from $params['access_token'] but $facebook->getUser() returns 0.

The user is logged in with the

session_start();
$code = $_REQUEST["code"];
if(empty($code)) 
{
    $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
    $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
    . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
    . $_SESSION['state'] . "&scope=";
    echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['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);
    $_SESSION['access_token'] = $params['access_token'];
    $graph_url = "https://graph.facebook.com/me?access_token=" 
    . $params['access_token'];
    $user = json_decode(file_get_contents($graph_url));
}
else 
{
    echo("Please clear your facebook cookie and re login.  The state id we use to check the authenticity of the session does not match.");
}
$access_token = $params['access_token'];

At this point, the access token is available.

Later in the code, I check if $facebook->getUser() returns the user id. It does not.

    $facebook = new Facebook($config);
    $user_id = $facebook->getUser();

Instead, if I use the $facebook->getLoginUrl(), and let the user click it once (fb detects the user is logged in and does not popup the login box, instead just returns back to app url), $facebook->getUser() does return the id, from then on.

Please let me know if you need more info reg the issue.

Rahul
  • 1,266
  • 1
  • 15
  • 18
  • Possible Duplicate of http://stackoverflow.com/questions/6790272/why-is-facebook-php-sdk-getuser-always-returning-0 – The Alpha Oct 16 '12 at 02:45
  • @SheikhHeera : I had gone through that question and a few more similar ones before posting this question. In all those questions, they've used js sdk for the authentication. I'v used only php. Also, I am getting the access token. Still, had tried few of the answers in those questions, to no avail. Hence, Iv asked this, so that in case some one know what exactly went wrong, they can help. – Rahul Oct 16 '12 at 03:15

1 Answers1

2

The function _accessServer opens another request back to your server, sending the access token.

The function _loginPopup should open the Facebook login popup requesting the appropriate permissions for the user to "allow access" to your application.

The PHP application should then pass the access token back to the Facebook API