I have a fully functional FQL query, but when it is triggered for the second time i get an error code 102: Requires user session
On my app i have an Autocomplete Search for Friends.
I am using jquery ui autocomplete with a dynamic source using AJAX.
This is my PHP Function:
function fb_buscarAmigosAutocomplete($term='',$app_user=false){
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret'=> APP_SECRET
));
$term=trim(strtolower($term));
//Buscar usuarios
try{
$fql = " SELECT uid,name,first_name,last_name,pic_square
FROM user
WHERE uid IN (
SELECT uid2
FROM friend
WHERE uid1=me()
)
AND strpos(lower(name),'".$term."') >=0
";
if($app_user)
$fql .= " AND is_app_user";
$fql .= " LIMIT 5";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$result = $facebook->api($param);
} catch(FacebookApiException $e){
$error=$e->getMessage();
var_dump($e);
}
if(!empty($result)) {
$return['amigos']=$result;
$return['valido']=true;
}else
$return['valido']=false;
return $return;
}
The weird thing is that this was working fine for the last 2-3 weeks, and all of a sudden it stopped. Even "weirder", it still works the first time it is triggered, but not the second time. Since this is asynchronous, i dont understand what difference does it make if is the first, second, third, fourth time it is triggered..
Any ideas?
Edit 1
With further research i think i got a workaround.
This may be because a bug reported here ans discused here
My workaround was to catch the first access_token i get with the Object Facebook, then attach it to every single instance of the Class, something like this
First connection:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret'=> APP_SECRET
));
$uid = $facebook->getUser();
if($uid){
$_SESSION['access_token']=$facebook->getAccessToken();
}
Any other use of the api:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret'=> APP_SECRET
));
$facebook->setAccessToken($_SESSION['access_token']);
try{
$user_info = $facebook->api('/'.$uid.'?fields=id,name,first_name,last_name,email,picture');
} catch(FacebookApiException $e){
$error = $e->getMessage();
}
So far it has solved the problem
Edit 2
it did not... sometimes my access token is a valid alphanumeric +100 characters String and those times it works.
Sometimes it is a 48 only numbers String, and it doesn't... i'm really stucked here
The reason this is likely happening is because of the December 5, 2012 "Breaking Changes" that Facebook has rolled out. Specifically:
New security restrictions for OAuth authorization codes
We will only allow authorization codes to be exchanged for access tokens once and will require that they be exchanged for an access token within 10 minutes of their creation. This is in line with the OAuth 2.0 Spec which from the start has stated that "authorization codes MUST be short lived and single use". For more information, check out our Authentication documentation.
This is why your first request works, your second doesn't. On the 2nd attempt, the SDK attempts to exchange your the user's auth code for an access token. But due to these changes, this can only be done once. Your code looks like it should be working properly, since you are explicitly saving and then setting the access_token after you first receive it. Make sure that that is the case (confirm that the $_SESSION var is being saved/retrieved properly). If for some reason it is not, the 102 error is what you will see.
Cheers
Related
I am developing a php script for retrieving messages from a page (not user) in facebook. I have access to that page (it is mine) so if I must to modify something in config, I can.
I tried the FQL query in graph api webpage from Facebook and it works. I get the file with all messages.
But whenever I try it in my php script, it fails. I am trying it in a localhost server and calling the script : "localhost/testServer/phpScript.php" I don't know if I have to add a parameter.
I have checked many examples and tutorials and all are similar but in my case, they don't work.
I always get an exception with this message:
Fatal error: Uncaught Exception: 100: Requires user session thrown in C:\xampp\htdocs\testServer\base_facebook.php on line 1271
If I surround it in try/catch and print what I get, it tells it is an exception with getType() and an array with getResult().
My code is quite simple:
<?php
require_once("facebook.php");
//Get Facebook SDK Object
$config = array(
'appId' => '*******',
'secret' => '*******',
'cookie' => true,
);
$facebook = new Facebook($config);
//$fql = "SELECT message FROM status WHERE uid = 169070991963 ORDER BY time DESC";
$fql = "SELECT message FROM status WHERE uid = 169070991963";
//Create Query
$param = array(
'method' => 'fql.query',
'query' => $fql,
'access_token'=>'*******|******-*******',
'ext_perm' => "read_stream",
);
$result = $facebook->api($param);
print_r($result);
?>
I just deleted my appId, secret and access_token.
I read something about read_stream permissions using status table. But adding access_token and ext_perm tags has no effect. I leave the uid of the webpage because it is public so you can test the code on your own.
If I can't do this query with php fql, I have no problem in using normal api if I can get the same result.
I am expending many days doing this script and I am completely lost with the problem.
I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use
I have to post on a users wall when he is offline. I went through number of posting and checked the code written below seems ok and also not throwing error and complete successful yet I am unable to see posting on users wall. Pl help.
$facebook = new Facebook(
array(
'appId' => "446262598768110",
'secret' => "<REMOVED>",
)
);
$facebook->setAccessToken("<REMOVED>");
//create message with token gained before
echo " lets try posting";
$access_token = $facebook->getAccessToken();
$user_id = $facebook->getUser();
echo "\ndone3..... $access_token.-----.$user_id.----new\n";
$post = array(
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//and make the request
$res = $facebook->api("/me/feed", 'GET', $post); //have tried both Post and Get method but result remain same
offline access was removed quite a few months ago. also, you do have to "POST" to facebook graph, everytime you want to publish something.
without seeing the result of the facebook graph, it's kind of impossible to help you at all.
nevertheless: double check, that you're using the correct access token. you have to extend the short lived access tokens by your own (https://developers.facebook.com/docs/howtos/login/extending-tokens/), so that the access token itself is still valid when you want to post by cron-job.
if you're trying to post by using the app access token, you can't use "/me/feed" at all.
I'm trying to grab data about a user in Facebook that can only be fetched if the app is authenticated (for example /likes).
However, I can't seem to grab this data despite the fact that the user has authenticated the Facebook app (and the applicable specific permissions). I can only get data from a public context.
I'm assuming I must be missing some sort of authentication step, but I can't figure out how. When I call $fb->getAccessToken(), it returns a string value, so it seems like it does get an access token for making requests. I see some solutions to force the user to click on a login URL to authenticate, but hasn't that already been done if they have authenticated the FB dialog previous (via Javascript)?
Besides that, I need the script to run without any input from the user.
Current code:
$fbConfig = array(
'appId' => 'xx',
'secret' => 'xx',
);
//get facebook configuration parameters defined in admin backend
$fb = new facebook($fbConfig);
$access_token = $fb->getAccessToken();
$fbUid = '123456789'; // Known Facebook User Id
$likes = $fb->api('/' . $fbUid . '/likes&access_token=' . $access_token);
var_dump($likes);
// Result is always: array(0) { }
Here you just want to get a likes of user of your application, i m giving you some code which have been created from me and it's working, i test it. you don't have need to get access token because it will be taken at every time.
<?php
set_time_limit(0);
include_once '../src/facebook.php';
$config=array(
'appId'=>"xxxxxxx",
'secret'=>"xxxxxxx",
'cookie'=>true
);
$facebook = new Facebook($config);
$user=$facebook->getUser();
$accessToken=$facebook->getAccessToken();
$likes=$facebook->api('/me/likes');
var_dump($likes);
?>
Here, set time limit=0 because it'll take more time to get a every likes of user.
I'm writing a facebook application in PHP with the facebook SDK.
The important parts in my code are:
$facebook = new Facebook(array(
'appId' => $ApplicationID,
'secret' => $ApplicationSecret,
'cookie' => true, // enable optional cookie support
));
$user = $facebook->getUser();
$post = $facebook->api('/' . $user . '/feed', 'post', array(
stuff
));
$_SESSION['finish'] = false;
$_SESSION['inside'] = 'yes';
$_SESSION['uid'] = $user;
$token = $facebook->getAccessToken();
echo 'Access token: ' .$token;
$_SESSION['friends'] = $facebook->api('/me/friends?access_token'.$token);
You can see I am echoing the access token.
At first, I haven't added the access_token into the query - I just added it for checking.
The problem is that the last like (with the /me/friends/) throws an exception:
OAuthException: An active access token must be used to query information about the current user.
Although I did a login, and the feed post did work (I checked at my wall, it's there). Then, my try catch block handles the exception by redirecting to the login link, this way:
catch(Exception $e) {
$login_url_params = array(
'scope' => 'stuff',
'fbconnect' => 1,
'redirect_uri' => $ApplicationURL
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
echo ("EXCPETION! " . $e . "<script> top.location.href='" . $login_url . "'</script>");
exit();
}
The code writing the exception is obviously only for debugging purposes.
Well, the first time I run the application a similar code is executed by a if(!$user) condition. Then it asks for my permission and I give it. Then, again, it says the access token is invalid (but does post to my wall).
Please note that I've compared the access_tokens, and even after removing the application and doing it all again - it stayed the same.
This is very awkward behavior and I fail to understand it. May anyone please shred some light on this?
Edit: For some weird reason, the token doesn't change even after going to a different user. But the post on the wall is still made... (And the exception thrown when accessing the friends list)
For some weird reason, the token doesn't change even after going to a different user. But the post on the wall is still made... (And the exception thrown when accessing the friends list)
That sounds to me as if you don’t actually have a user currently logged in, so the SDK is just using your app access token, which is always the default token it will use before it receives another, more “specific” one.
What format does your access token have – does is look something like your_app_id|your_app_secret or your_app_id|some_random_characters? If it’s starting with your app id, it’s most definitively an app access token.