简体   繁体   中英

Why does facebook $user_id = $facebook->getUser(); return 0 in-spite of being logged in?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM