facebookarchive / php-graph-sdk

The Facebook SDK for PHP provides a native interface to the Graph API and Facebook Login. https://developers.facebook.com/docs/php
Other
3.18k stars 1.96k forks source link

Uncaught FacebookSDKException although I am actually catching #1092

Open tafelnl opened 5 years ago

tafelnl commented 5 years ago

I have the following code (simplified) for a login flow through Facebook.

try
{
    $helper = $fb->getRedirectLoginHelper();
}
catch (FacebookSDKException $e)
{

}
catch(Exception $e)
{

}

// Try to get access token
try
{
    $accessToken = $helper->getAccessToken();
}
catch (FacebookResponseException $e)
{
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
}
catch (FacebookSDKException $e)
{
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

When I try to login for the first time (the second time the flow goes perfectly) I get the following error message:

PHP Fatal error:  Uncaught Facebook\Exceptions\FacebookSDKException: Cross-site request forgery validation failed. Required param "state" missing from persistent data. in Facebook/Helpers/FacebookRedirectLoginHelper.php:244

Stack trace:

#0
Facebook/Helpers/FacebookRedirectLoginHelper.php(221): Facebook\Helpers\FacebookRedirectLoginHelper->validateCsrf()

#1 my-callback-file.php(25):
Facebook\Helpers\FacebookRedirectLoginHelper->getAccessToken()

#2 {main}
  thrown in Facebook/Helpers/FacebookRedirectLoginHelper.php on line 244

It's weird, because I actually am catching the error.

Besides, it's weird that the error is thrown anyway, because I don't think I implemented anything wrong. And when I try to login a second time, it does not give any errors.

Only when I completely start a new session the error is thrown. (when going incognito for example)

But it's getting even weirder: When I go incognito, and first go to https://facebook.com and login, and afterwards go to my site and login through Facebook, it also does not give any errors.

So really only when you start a completely fresh session and login for the first time.

Henridv commented 5 years ago

Did you add a use Facebook\Exceptions\FacebookSDKException statement? If not, that's probably why it isn't catching the Exception.

tafelnl commented 5 years ago

Yes I did, that is the weird part.

tafelnl commented 5 years ago

Hmm, now that I am thinking about it. I have added this statement in a configfile.

I include this configfile in the callbackfile.

So I should maybe redeclare the usestatement in the callbackfile?

If so, is there another way in PHP to avoid copy- and pasting the same use statements throughout every file needed? Because that is what I was trying to achieve by adding the use statement in a configfile