facebook->getUser() returning 0 - php

Whenever I try to login a prompt opens asking for the basic permissions, after that its being redirected to my redirect_uri with an URL
=">http://localhost/demo/?code=AQDwzia3Wx1BktixF59jVHbm0ViGVJm8Xhb2tNZDyYreZh0KoSJhrSsJ8Aa2KX3gocwR0XNQjQz7ZlBh26_nBi-3iOMByhVO2cxwJ8maC4IHxBacfqXjzqIyBaZQbWKUUxPI6VBrqBgFXQasj7PEtmug7lt93dK4fmMC2A4i2dUYU-gSvzn0f0ZdB3eT_aSvgR1KoLCmQgLh3xix4H05QR6LCP9nLtQC4l9rMJW83kS0PNmWq0COZYvGfuX1R7519Fn3iXRB9F0MTsK1KQ_ulpK84PUCkuMu8et88Lln0ZwuzaPo0oERelkPWYnrrTKa-5w&state=ed66ea618d8076d9e72c15d9a65a6312#=
Even though facebook->getUser() returns 0
Here is my code
<?php
require_once('php-sdk/facebook.php');
$facebook = new Facebook (array(
'appId' => '1234',
'secret' => '12313',
'cookie' => true
));
?>
<html>
<head> <title> Warming Up with FB API </title> </head>
<body> <h1> Hello World </h1> </body>
</html>
<?php
$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo'
));
$user = $facebook->getUser();
//echo $user. '</br>';
if ($user) {
echo '<em>User Id: </em> '.$user;
} else {
$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo'
));
echo 'Login Here ';
}
?>
I know its a very trivial question but I am kinda stuck at this and unable to proceed further. Kindly suggest what to do.
*UPDATE*
Leaving the App Domain empty solved my problem.

if someone is still banging their head over this here is what is wrong now. I was hired to fix this mess!
Check App domain in fb panel , must match with the domain where your app is.
edit base_facebook.php find:
public function getAccessToken() {
if ($this->accessToken !== null) {
// we've done this already and cached it. Just return.
return $this->accessToken;
}
// first establish access token to be the application
// access token, in case we navigate to the /oauth/access_token
// endpoint, where SOME access token is required.
$getApplicationAccessToken = $this->getApplicationAccessToken();
$this->setAccessToken($getApplicationAccessToken);
$user_access_token = $this->getUserAccessToken();
if ($user_access_token) {
$this->setAccessToken($user_access_token);
}
return $this->accessToken;
}
to::
public function getAccessToken() {
if ($this->accessToken !== null) {
// we've done this already and cached it. Just return.
return $this->accessToken;
}
// first establish access token to be the application
// access token, in case we navigate to the /oauth/access_token
// endpoint, where SOME access token is required.
$getApplicationAccessToken = $this->getApplicationAccessToken();
$this->setAccessToken($getApplicationAccessToken);
$user_access_token = $this->getUserAccessToken();
if ($user_access_token) {
//$this->setAccessToken($user_access_token);
$this->accessToken = $user_access_token; //edit; msolution
}
return $this->accessToken;
}
Next find the function: getAccessTokenFromCode()
find the line:
parse_str($access_token_response, $response_params);
replace it with:
//parse_str($access_token_response, $response_params); //edit:: msolution;;
$response_params = json_decode($access_token_response, true );
commenting the original and adding json_decode
thats it!

If User is logged in and still getting $user = 0
I faced this issue on different occasions but SDK issue is not happening to everyone. So I'm not sure what goes wrong here. But I dig in to it little bit and found solution as mentioned below.
SOLUTION : This worked for me after trying for many solutions for this issue.
In base_facebook.php file, find the makeRequest() method and check for following Line.
$opts = self::$CURL_OPTS;
Immediately following it, add this line
$opts[CURLOPT_SSL_VERIFYPEER] = false;
More details can be found here - http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/

Change this
$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo'
));
to
$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo/index.php'
));
And see if this works !!

After several hours, the solution for me was (Let's say my site is http://www.site123.com):
Settings # https://developers.facebook.com
App Domain: site123.com (even blank it will work though)
Site URL: http://site123.com IMPORTANT : NOT http://www.site123.com
PHP Code - fb_config.php
//Declarations
$app_id = "{you AppID}";
$app_secret = "{your App Secret}";
$site_url = "http://site123.com/receive_data_from_facebook.php";
//New Facebook
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => TRUE, /* Optional */
'oath' => TRUE /* Optional */
));
//Login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,user_birthday',
'redirect_uri' => $site_url,
));
//Get FacebookUserID
$fbuser = $facebook->getUser();
Important Note Also: I had some issues with Firefox $facebook->getUser() was 0 even my code was working on Chrome. But after cleaning Firefox cache, it worked nicely!
Hope it helps.

It might be Worked using
$opts[CURLOPT_SSL_VERIFYPEER] = false; after $opts = self::$CURL_OPTS; on file base_facebook.php.

Related

$facebook->getUser(); returning 0 and throwing OAuthException: An active access token must be used to query information about the current user

Before i state my problem i must say that i have visited all these SO 1 , SO 2 , SO 3 , SO 4 links and many others and none of them solving my query
with facebook-php-sdk i am trying to login a user. on first few occasions it was working perfectly fine (2 to 3 days ago.). Today when i started again working with my project its not working any more.whenever i am trying to login a user $facebook->getUser(); throwing Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. i have also noted that getuser() is also returning 0` though few days back it was working fine.
MY CODE :: 0auth_provided_by_facebook.php
include_once $_SERVER['DOCUMENT_ROOT'].'dist/facebook-php-sdk/src/facebook.php';
$config = array(
'appId' => '***********',
'secret' => '*********',
'allowSignedRequest' => false, // optional but should be set to false for non-canvas apps
'cookie' => true,
'oauth' => true
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl(array(
scope'=>'email,user_location,user_photos,publish_actions,publish_stream,basic_info',
'redirect_uri' => 'http://localhost/dist/include/0auth_provided_by_facebook.php'
));
echo "EXCEPTION at place 1";
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
//$login_url = $facebook->getLoginUrl();
$login_url = $facebook->getLoginUrl(array(
'scope' => 'email,user_location,user_photos,publish_actions,publish_stream,basic_info',
'redirect_uri' => 'http://localhost/dist/include/0auth_provided_by_facebook.php'
));
echo "Exception at place 2";
}
It is always throwing the error mentioned above and and printing Exception at place 2. which means $user_id = $facebook->getUser();if($user_id) returnin false...
EDIT :
as mentioned in the now i have used getAccessToken and setAccessToken after $user_id = $facebook->getUser();
now my code
include_once $_SERVER['DOCUMENT_ROOT'].'dist/facebook-php-sdk/src/facebook.php';
$config = array(
'appId' => '234360450080751',
'secret' => '38189c40cec699c7c0deee2377a2c0a2',
'allowSignedRequest' => false, // optional but should be set to false for non-canvas apps
'cookie' => true,
'oauth' => true
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
//....REST ARE SAME
How to solve it these two problem ??? what is the reason ??
i am giving more details it may help you to answer my query.
my fb app settings :
APP DOMAIN : kept it blank according to the comments
SITE URL : http://localhost/dist/include/0auth_provided_by_facebook.php
Native or desktop app? Disabled (i tried by enabling but no help)
Deauthorize Callback URL : http://localhost:80/dist/
Valid OAuth redirect URIs http://localhost/dist/include/0auth_provided_by_facebook.php
Stream post URL security : ENABLED
Normalize all publish scopes to 'publish_actions :' Enabled
I had this exact same issue with this same error being thrown. I also looked everywhere for a solution, none of which seemed to solve my particular problem.
Finally, I read Abhik Chakraborty's comment and realized that my OAuth redirect URI wasn't set within my FB App's settings. The user was authenticated but the URI didn't match when the user's info was sent back to my site, which resulted in getUser returning 0.
Here's the catch: this fix didn't work while I was using localhost, even though it was setup the same as my server. I'll update my answer if I get it working with localhost.

Facebook Php SDK - getUser() return always 0

I read all threads on this forum but I can't find my solution..
I use the last Php SDK by facebook : v3.2.2 .
So I used this:
//start fb
$facebook = new \Facebook(array(
'appId' => $fb_app_id,
'secret' => $fb_app_secret,
'cookie' => true,
));
// get id user-fb
$fbUser = $facebook->getUser();
if ($fbUser) {
try {
$fbUserProfile = $facebook->api('/me'); // take user-infos
$friends = $facebook->api('/me/friends'); // take his friend
} catch (FacebookApiException $e) {
error_log($e);
$fbUser = null;
}
}
if ($fbUser) {
$logoutUrl = $facebook->getLogoutUrl(array( 'next' => ('my-url') ));
} else {
$loginUrl = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'email,offline_access,publish_actions',
'req_perms' => 'publish_stream,email',
'redirect_uri' => 'my-redirect-url'
));
}
So I don't understand what is wrong..
When I test it, first time I can click on the loginUrl and get authorization . but when I try to getUser again, the function $facebook->getUser() return 0 again and I got the loginUrl again but when I click on the link, I'm just redirect on the callback url..
I'm not sure if the application facebook need special parameters for this. My app_id and app_secret are 100% sure.
I solved this issue using $facebook->getLoginUrl(array(
'scope' => 'public_profile',
'redirect_uri' => 'http://www.your_domain/current_page.php'
));
where 'http://www.your_domain/current_page.php' is the same page where i am running this code
N.B using Facebook php sdk 3.2.3
(Question answered in the comments. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
OK I solved the error: the callback url was wrong, I needed to call the current url and not a special one.

Facebook php sdk 3.2.2 GetUser() always return 0 [duplicate]

This question already has answers here:
Why is Facebook PHP SDK getUser always returning 0?
(26 answers)
Closed 8 years ago.
i spent all day searching for an answer.. but it seems that nothing can fix it.
i guess every version had a different issue...
well it's pretty simple, i have this code:
<?php
include_once("facebook.php"); //include facebook SDK
######### edit details ##########
$appId = '****'; //Facebook App ID
$appSecret = '****'; // Facebook App Secret
##################################
//Call Facebook API
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
'cookie' => true
));
$fbuser = $facebook->getUser();
if ($fbuser) {
// Do Something
}
else{
//Show login button for guest users
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions));
echo '<img src="images/facebook-login.png" border="0">';
}
?>
i get 0 in get user every time.
when i go to "login on facebook" and im not logged in, i get facebook login screen.
when i go to "login on facebook" and im logged in, facebook redirect me to my page and i get 0 in get user again.
i'm tring to run it on my localhost, maybe thats the problem?
hope someone can help..
thx
I had a similar problem using the same simple login script. I tried almost anything but nothing helped. (the weird thing was that the day before everything was working fine).
So started debugging the "base_facebook.php" and found that the function getAccessTokenFromCode failed without an exception (silently).
It turned out that the response of _oauthRequest gave an error message reply instead of the expected token reply:
$access_token_response =
$this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array ('client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'redirect_uri' => $redirect_uri,
'code' => $code));
So by adding echo $access_token_response; directly after this function a found my problem.
The response error was that my app was configured as a Native/Desktop app.
After I changed it to Internet the getUser(); gave the correct user id.
I hope this helps.
Try this, it's a piece of code a classmate of mine wrote because I was struggling with FB login aswell. Worked for me.
<?php
session_start();
require_once 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => '3525325', <- fake appID ofcourse, enter your own
'secret' => 'fauuf983f9f', <- fake secret, enter your own
));
$user = $facebook->getUser();
if ($user) {
try {
$_fb['user'] = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$_fb['user'] = null;
}
}
if ($user)
{
$_fb['logouturl'] = $facebook->getLogoutUrl();
$_fb['authed'] = true;
echo '<h1>Logged in</h1>';
echo 'Fbid: '.$user;
echo "<br /><br /><pre>";
print_r($_fb['user']);
echo "</pre>";
}
else
{
$_fb['loginurl'] = $facebook->getLoginUrl(array('scope' => 'email'));
$_fb['authed'] = false;
echo 'Login with Facebook';
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
</body>
</html>
Hope it's of use to you. Good luck :) Facebook login caused me a lot of irritation :p

PHP loop issues with facebook app auth

I am using the latest PHP-SDK(3.11) and i have issues when users come on my app for the first time. The application make infinite loops.
When the user have to give permissions to the application, he is redirected to :
https://www.facebook.com/connect/uiserver.php?app_id=**myappId**&method=permissions.request&display=page&next=http%3A%2F%2Fapps.facebook.com%2F**myApp**%2F&response_type=code&state=**theSate**&canvas=1&perms=user_birthday%2Cuser_location%2Cuser_work_history%2Cuser_about_me%2Cuser_hometown
and when he accept i have the following link returned :
http://apps.facebook.com/**myApp**/?error_reason=user_denied&error=access_denied&error_description=***The+user+denied+your+request.***&state=**theSate**#_
i don't understand why the access is denied when the user click on "allow".
if ($this->fbUser) {
.... Do Somthing
} else {
$this->loginUrl = $this->fb->facebook->getLoginUrl(array(
'scope' => implode(',', sfConfig::get('app_facebook_perms')
), 'next' => 'http://apps.facebook.com'. sfConfig::get('app_facebook_app_url')));
$this->logMessage($this->loginUrl, 'info');
sfConfig::set('sf_escaping_strategy', false);
}
<script type='text/javascript'>
top.location.href = "echo $this->loginUrl ";
</script>
Try something like this, since you need to store the access token, one way or another. Hard to know what you are doing (or not doing) from that snippet.
<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'APP_ID_HERE',
'secret' => 'APP_SECRET_HERE',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getUser();
if(empty($session)) {
# There's no active session, let's generate one
$url = $facebook->getLoginUrl(array(
"response_type"=>"token", //Can also be "code" if you need to
"scope" => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos' ,
"redirect_uri"=> "http://test.com" //Your app callback url
));
header("Location: $url");
exit;
}
// user is logged in

Facebook App: Where do i put offline_access request?

I need my app to request the offline_access permission (detailed here), but as ever I'm baffled by the Facebook documentations.
It says I need a comma separated list of my permission demands, like 'publish_stream,offline_access' etc
where do i put this list in the interface below????
It's used with the API, as follows
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => false,
));
$facebook_login_url = $facebook->getLoginUrl(array(
'next' => '',
'cancel_url' => '',
'req_perms' => 'email,publish_stream,status_update'
));
Where $facebook_login_url is the URL tha the user needs to follow to grant you access.
Does that help?
You can't do this with that interface. You need to set scope parameter when redirecting user to facebook.
x=y&scope=email,user_about_me,user_birthday,user_photos,publish_stream,offline_access
First define which permissions you will need:
$par['req_perms'] = "friends_about_me,friends_education_history,friends_likes,friends_interests,friends_location,friends_religion_politics,
friends_work_history,publish_stream,friends_activities,friends_events,
friends_hometown,friends_location,user_interests,user_likes,user_events,
user_about_me,user_status,user_work_history,read_requests,read_stream,offline_access,user_religion_politics,email,user_groups";
$loginUrl = $facebook->getLoginUrl($par);
Then, check if the user has already subscribed to app:
$session = $facebook->getSession();
if ( is_null($session) ) {
// no he is not
//send him to permissions page
header( "Location: $loginUrl" );
}
else {
//yes, he is already subscribed, or subscribed just now
echo "<p>everything is ok";
// write your code here
}

Categories