I'm trying to follow the example to create a server side login to Facebook from here, but with no luck. In step 7, when I try to exchange the code with a token and store it in a session for later use, I always get this error :
file_get_contents(): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
I know this already asked many times, but I still unable to solve this, as per this question, I tried using cURL, but it still does not work, it just returned false.
Other question told me to use the PHP SDK, but I don't know which method to use. So I'm completely lost in here.
Here's my code for calling the login form :
<a href="<?php echo LOGIN_URL; ?> ?>" class="btn btn-primary">Login with Facebook</a>
where LOGIN_URL is defined as :
define("LOGIN_URL", $facebook->getLoginUrl(array("redirect_uri" => APP_URL . "fb_login")));
in fb_login, I have this code :
$app->get("/fb_login", function() use($app, $facebook)
{
$code = $_REQUEST["code"];
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . APP_ID . "&redirect_uri=" . APP_URL . $_SESSION["request_uri"] // Previous URL
. "&client_secret=" . APP_SECRET . "&code=" . $code;
$response = file_get_contents($token_url); // Doesn't work
$params = null;
parse_str($response, $params);
$_SESSION["access_token"] = $params["access_token"];
// Let's try with cURL...
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_URL, $token_url);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// $output = curl_exec($ch); // Returns false
// curl_close($ch);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params["access_token"];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
var_dump($code); die();
});
Any help is appreciated. Thanks before.
To directly answer the question, the problem is most likely that you do not urlencode
(make safe for URL transport) the redirect URL. The fastest fix will be:
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . APP_ID . "&redirect_uri=" . urlencode(APP_URL . $_SESSION["request_uri"])
. "&client_secret=" . APP_SECRET . "&code=" . $code;
However, I would also suggest that you look at the Facebook SDK as this does this all for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With