Facebook javascript login for PHP SDK
I am using the facebook-php-sdk-v4-5.0-dev.zip FB API files.
I am trying to make javascript and php SDK files to work on Facebook. I have a working find FB.login, I can do graph queries, etc. Now I want to pass an access token to my PHP code and continue from there. I am initializing FB in javascript:
window.fbAsyncInit = function() {
FB.init({
appId : appId, //my appId
cookie : true, // enable cookies for session access
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
And now that the FB is in initialized, I do some other work using the API, after which I push my php code with:
window.location.replace(<my url>.php);
Inside my PHP application, I have the following:
$fb = new Facebook\Facebook([ 'app_id' => <my app_id>,
'app_secret' => <my app_secret>
'default_graph_version' => 'v2.2',
]);
$jsHelper = $fb->getJavaScriptHelper();
try
{
$accessToken = $jsHelper->getAccessToken();
}
catch(Facebook\Exceptions\FacebookResponseException $e)
{
// When Graph returns an error
print('Graph returned an error: ' . $e->getMessage() );
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e)
{
// When validation fails or other local issues
print( 'Facebook SDK returned an error: ' . $e->getMessage() );
exit;
}
if (isset($accessToken))
{
print("Logged in already");
}
else
{
print("Not logged in");
}
What I see is "not logged in". From what I can tell, the cookie is not being generated (I threw out the $ _COOKIE at the top of my PHP file). I also tracked network calls and can't see the cookie coming down from Facebook on my oauth requests ... this is where I assume such a cookie would be generated.
Thanks, Andy
source to share
I would recommend that you update the v5.0.0 PHP SDK, or is there a specific reason why you are using this deprecated version?
Also, take a look at the example in
Copied example code:
# /js-login.php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
$_SESSION['fb_access_token'] = (string) $accessToken;
// User is logged in!
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');
source to share