OAuthException : An active access token must be used to query information about the current user - facebook

I'm trying to run the sample code for Facebook connect that I downloaded from http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
I get this error message :
[error] => Array
(
[message] => An active access token must be used to query information about the current user.
[type] => OAuthException
[code] => 2500
)
You can try on my website : http://facebook.oliverjordan.net/thinkdiff
Here is the fbmain.php code :
<?php
//facebook application
$fbconfig['appid' ] = "463007877113xxx";
$fbconfig['secret'] = "-sensor-";
$fbconfig['baseurl'] = "http://facebook.oliverjordan.net/thinkdiff/index.php"; //"http://thinkdiff.net/demo/newfbconnect1/php/sdk3/index.php";
//
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
}
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown',
'redirect_uri' => $fbconfig['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user){
//get user basic description
$userInfo = $facebook->api("/$user");
//Retriving movies those are user like using graph api
try{
$movies = $facebook->api("/$user/movies");
}
catch(Exception $o){
d($o);
}
//update user's status using graph api
//http://developers.facebook.com/docs/reference/dialogs/feed/
if (isset($_GET['publish'])){
try {
$publishStream = $facebook->api("/$user/feed", 'post', array(
'message' => "I love thinkdiff.net for facebook app development tutorials. :)",
'link' => 'http://ithinkdiff.net',
'picture' => 'http://thinkdiff.net/ithinkdiff.png',
'name' => 'iOS Apps & Games',
'description'=> 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
d($e);
}
$redirectUrl = $fbconfig['baseurl'] . '/index.php?success=1';
header("Location: $redirectUrl");
}
//update user's status using graph api
//http://developers.facebook.com/docs/reference/dialogs/feed/
if (isset($_POST['tt'])){
try {
$statusUpdate = $facebook->api("/$user/feed", 'post', array('message'=> $_POST['tt']));
} catch (FacebookApiException $e) {
d($e);
}
}
//fql query example using legacy method call and passing parameter
try{
$fql = "select name, hometown_location, sex, pic_square from user where uid=" . $user;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}?>
Can anyone help me?

You must ensure that your access token is active. Or maybe you're in logout condition. Or try to clean the cookies and cache from your browser (ctrl+shift+del)

Please check if you are getting any Facebook exceptions like
An active access token must be used to query information about the
current user.
which causes 0 as user id in return from $facebook->getUser().
So please check with getAccessTokenFromCode() from base_facebook.php and verify access_token_response format as it may be in JSON format.
So try to use appropriate decoding method to get $response_params['access_token'] from $access_token_response.

Related

fb login error in php

I am creating fb login with the php ,
the problem is that the email of user is not returning from facebook,
FBID and USER NAME is returning.
The same code i have done for another project is working but for the new one is not working
the code is like this
require 'src/facebook.php'; // Include facebook SDK file
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXX', // Facebook App ID
'secret' => 'XXXXXXXXXXXXXXXXX', // Facebook App Secret
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
$fbid = $user_profile['id']; // To Get Facebook ID
$fbuname = $user_profile['username']; // To Get Facebook Username
$fbfullname = $user_profile['name']; // To Get Facebook full name
$femail = $user_profile['email']; // To Get Facebook email ID
/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['USERNAME'] = $fbuname;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
header("location:fblogin.php");
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email', // Permissions to request from the user
));
header("location: " . $loginUrl);
}
$user_profile = $facebook->api('/me?fields=name,email');
It´s called "Declarative Fields", see changelog. Btw, you can´t get the username anymore.

Facebook authenticating issue , 500 server erorr

From yesterday my web site getting 500 server error from facebook server side while trying to log in to the site,Im sure I have done nothing updating my code,I searched everything but havent found any solutions.
please check my code and help me.
<?php
session_start();
require 'config/fbconfig.php';
require 'facebook/facebook.php';
include"core.php";
connectdb();
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if (!empty($user_profile )) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
$username = $user_profile['name'];
$uid2 = $user_profile['id'];
$email = $user_profile['email'];
$validated = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM users WHERE email='".$email."'"));
if($validated[0]== 1){
$get_data = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE email='".$email."'"));
$visits = $get_data['visits'];
$visits2 = $get_data['visits']+1;
$sid= keygen(30);
mysql_query("UPDATE users SET fbid='".$uid2."', visits= '".$visits2."', sid='".$sid."' WHERE email='".$email."'");
$_SESSION['sid'] = $sid;
$expire=time()+60*60*24*30;
setcookie("sid", $_SESSION['sid'], $expire);
if($get_data['cat_sec']==0){
header('Location: cat_select.php');
exit();
}else{
if(isset($_SESSION['curl'])){
header('Location:'.$_SESSION['curl']);
}else{
header('Location: index.php');
}
exit();
}
}else{
$sid= keygen(30);
$register = mysql_query("INSERT INTO users SET fname='".$username."', email='".$email."', fbid='".$uid2."', active='1' , sid='".$sid."'");
include_once"reg_fb_mail.php";
header('Location: cat_select.php');
exit();
}
$permissions = $facebook->api("/me/permissions");
if (array_key_exists('publish_stream', $permissions['data'][0])) {
$attachment = array(
'message' => 'my web site message',
'name' => 'www.mywebsite.com!',
'caption' => "caption.",
'link' => 'http://www.website.com',
'description' => 'website description gose here ',
'picture' => 'http://website.com/images/fb.png',
'actions' => array(
array(
'name' => 'www.website.com',
'link' => 'http://www.website.com'
)
)
);
$result = $facebook->api('/me/feed/', 'post', $attachment);
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl(array( 'scope' => 'email,publish_stream'));
header("Location: " . $login_url);
}
?>
I have attached all the code.Please help me to sort this issue .
Thank you.
Error figure outs ! The issue was not at this code.In facebook settings page I found there is a single space before the APP ID . its now fixed..
Facebook dosent trim or remove white spaces from get parameters in Authentication.
If there is a invalid character its getting a 500 server error in facebook.
I think this is a critical security issue.
Hal Rotholz - Thanks for your clue..

Facebook. Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user

with my app's administrator acount on facebook my app work normally, but with other account I get error: Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
I had this problem before with other app (publish text on the user's wall), but fixed after i added
$user = $facebook->getUser(); What's wrong here? I have added offline_access permission... Help me, please if you can, Thank you very much.
<?php
require_once('images/Facebook.php');
$facebook = new Facebook(array(
'appId' => '456080124457246',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
$user_profile = $facebook->api('/me','GET');
$accessToken = $facebook->getAccessToken();
# Get User ID
$user = $facebook->getUser();
$facebook->setAccessToken($accessToken);
$facebook->api(456080124457246);
if ($user) {
try {
# Photo Caption
$photoCaption = $user_profile['name'] . ' patarimų plaukams sužinojo čia http://goo.gl/otwhf';
# Absolute Path to your image.
$imageUrl = 'http://padekime.wu.lt/plaukai/images/PlaukaiNeuzvedus.jpg'; // Example URL
# Post Data for Photos API
$post_data = array(
'message' => $photoCaption,
'url' => $imageUrl
);
$apiResponse = $facebook->api('/me/photos', 'POST', $post_data);
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload'
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
?>
In this case it's not even getting to your $facebook->getUser() call -- it's throwing an exception as soon as it reaches this line:
$user_profile = $facebook->api('/me','GET');
$facebook->api() is a bit of a tricky thing to work with because it throws an exception immediately if it doesn't know who "/me" is...even if you try to fix it later.
The trick, I think, is to wrap the entire thing in a try...catch block. Like so:
<?php
require_once('images/facebook.php');
$facebook = new Facebook(array(
'appId' => '456080124457246',
'secret' => 'xxxxx',
));
try {
$user_profile = $facebook->api('/me','GET');
# Get User ID
$user = $facebook->getUser();
if ($user) {
try {
# Photo Caption
$photoCaption = $user_profile['name'] . ' patarimų plaukams sužinojo čia http://goo.gl/otwhf';
# Absolute Path to your image.
$imageUrl = 'http://padekime.wu.lt/plaukai/images/PlaukaiNeuzvedus.jpg'; // Example URL
# Post Data for Photos API
$post_data = array(
'message' => $photoCaption,
'url' => $imageUrl
);
$apiResponse = $facebook->api('/me/photos', 'POST', $post_data);
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload'
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
} catch (Exception $e) {
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload'
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
?>
That'll redirect the user to the login url pretty much immediately, then come back with everything in tow. You don't have to set the accessToken with this setup.
This may actually unnecessarily repeat some functionality, but hopefully it's something to start with.
By the way, for what it's worth the offline_access permission is being phased out.
I stopped using "me" keyword to get the logged in user's profile.
instead of $facebook->api('/me','GET'), I changed to $facebook->api('/the facebook ID of the user','GET');
this reduce the need to do second try catch
If you do
if (!empty($user)) {}
That should help...

Facebook Connect works offline, but not online "This webpage has a redirect loop"

Access to my developed website is done using facebook connect.
Everything is OK offline, but not online. I get a navigation error (using Chrome) "This webpage has a redirect loop" :
The webpage at https://www.facebook.com/dialog/oauth?client_id=209633612480053&redirect_uri=http%3A%2F%2Fwww.bluward.com%2Faccess%2Flogin_facebook&state=299262ddf89afbf382452df89c9a2ce8&scope=email%2C+user_birthday%2C+user_about_me%2C+user_location%2C+publish_stream&fbconnect=1#= has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
Here is the PHP code (using CodeIgniter framework):
public function login()
{
// Get the FB UID of the currently logged in user
$uid = $fb->getUser();
// If the user has already allowed the application, you'll be able to get his/her FB UID
if($uid) {
try {
$profile = $fb->api(array(
'method' => 'users.getinfo',
'uids' => $uid,
'fields' => 'uid, first_name, last_name, pic_square, pic_big, sex, birthday_date, current_location, email'
));
// Only the first user.
$profile = $profile[0];
} catch (FacebookApiException $e) {
return false;
}
// Do stuff when already logged in.
return $profile;
} else {
// If not, let's redirect to the ALLOW page so we can get access
redirect($this->getLoginUrl(array(
'scope' => 'email, user_birthday, user_about_me, user_location, publish_stream',
'fbconnect' => 1
)));
}
}
And depending on the profile info, I check if the user already exists on database, then log him/her, and if not exists on database, signup him/her.
Update:
When I clear Facebook cookies, the redirect to login page is successful, and I'm able to fill email/password.
Unfortunately, when I click "log in" button, I get the same error message as I displayed above.
It looks like your using and older version? Here is how i would handle issue with php-sdk 3.1.1 "the most current version".
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => '135669679827333',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$params = array(
scope => 'read_stream,publish_stream,publish_actions,read_friendlists',
//redirect_uri => $url
);
$loginUrl = $facebook->getLoginUrl($params);
echo '<script> top.location.href=\''.$loginUrl.'\'</script>';
};

Facebook login to site bugs

When users come to my site they have the option to log in through facebook. If they are logged in to facebook, and hit the fb login button, it will show all the appropriate logged in dialog. However, if you log out of facebook (either through my site or through facebook itself) and then try to log in through my site again, it will bring you to facebook to sign in, then bring you back to my site. The url changes from x.net/index.php to x.net/index.php?state=... bunch of letters / numbers, but then doesn't return logged in dialog. Hit the button once again after that, and the page refreshes with a different (but similar) url, and returns all the logged in dialog.
Any ideas on how to fix this?
Here is the code I use to connect to facebook and get the login and logout urls.
//facebook application
$fbconfig['appid' ] = "myAppId";
$fbconfig['secret'] = "myAppSecret";
$fbconfig['baseurl'] = "http://myNeatSite.net/index.php";
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
}
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream',
'redirect_uri' => $fbconfig['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
As far as I see, you only process the case $user is not null (which means the user is already logged in), but ignore the other case.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}