Having Trouble Accessing Email from Facebook Oauth - facebook

I can't get the proper token to reach the extended user information (specifically email) from the Facebook API. I've correctly given my app permission to retrieve the email, so I know I have the correct permissions. I'm trying to convert a session to a token using the exchange_session method as you can see below in my code:
$url = 'https://graph.facebook.com/oauth/exchange_sessions';
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,$url);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS,'type=client_cred&client_id=' . FB_APPID . '&client_secret=' . FB_SECRET . '&sessions=' . $session->session_key);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
$tokendata = json_decode($buffer);
$user = json_decode(file_get_contents('https://graph.facebook.com/me/?wrap_access_token=' . $tokendata[0]->access_token));
print_r($user);
If I use the '/me' it always errors out with
"An active access token must be used to query information about the current user."
If I swap out '/me' with the current user ID, it will give me the basic user info, but not the extended info.
The token that I get back is indeed the full token with session info in this format:
123456789012345|6.abcdefghijklmnopqrstuv__.1234.1234567890-1234567890|abcdefghijklmnopqrstuvwxyza.
Help?
Thanks!
Andy

Should it be /me/?access_token= instead of /me/?wrap_access_token=?

Use official facebook's php sdk to avoid the headache with tokens handling

Related

Check If access_token is valid

I have A Facebook App which auto post birthday reminders.
I stored tokens in database.
But Now most of them are expired.
I am trying to make a PHP file which will find valid tokens from my database and save them.
$query = mysql_query("select fb_token from fb_user")
while ($row = mysql_fetch_array($query)) {
$url = "https://graph.facebook.com/me?access_token=".$row['fb_token']."";
}
By with this Code I'm getting each token. Need Help to Save only valid tokens.
You can create request to the following Open Graph URL, basically you need to provide your APPID and access_token.
https://graph.facebook.com/oauth/access_token_info?client_id=APPID&access_token=xxxxxxxxx
The response will contain expiry time of specified token.

Get Access Token from Facebook PHP SDK is not working properly

I'm trying to retrieve an Access Token from Facebook using PHP SDK 3.2.2, being the code below what I placed in the redirect url after a sucessfull user login in Facebook. My problem is that $this->facebook->getAccessToken() is not giving back the user access token after the user gives access to the APP, just a string with the form: 'AppId|AppSecret', and I have to include code to manually get the User Access Token. This work, but I don't know WHY when I use getAccessToken is not giving back the right Token. I would also like to know how if there is any better way to retrieve User Access Token than with $code, because I don't feel this is a good way of doing it.
NOTE: I use $this->facebook because I load it as a Codeigniter library.
$access_token = $this->facebook->getAccessToken();
//-------------------------------------------------------------------------
//echo '<br/>Access Token: ' . $access_token;
// Generare Token if not created:
$code = $_REQUEST["code"];
if ( isset($code) ) {
//echo '<br/>Code Enviado: ' . $code;
//exit();
$appId = $this->facebook->getAppId();
$appSecret = $this->facebook->getAppSecret();
$redirectTo = base_url('asociar/acc_facebook/step2/');
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $appId . "&redirect_uri=" . urlencode($redirectTo)
. "&client_secret=" . $appSecret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
//echo '<br/>Repitiendo el Token';
$this->facebook->setAccessToken($access_token);
//echo '<br/>Second Access Token Fijado: ' . $access_token;
}
//-----------------------------------------------------------------------
UPDATE:
This issue is due to I used CI with PHP SDK (check my own answer for that), but the answer is valid to anyone that have this issue with Facebook PHP SDK (Check #Imbru answer)
#Imbru pointed me in the solution, if any credit, give it to him.
Take this into account: when using Codeigniter, it saves all the session data in the cookie and send it to the browser, not storing it in the server. Yes, they do it, and it leads to many other problems (as losing of session when you store a lot of data, and the browser only sends you back part of them, but that is another history).
With CI, the solution is overwrite the session core class, with another session class which manages the session with PHP $_SESSION, as for example, https://bitbucket.org/xperez/core-session-storage-for-codeigniter (I use it in my projects, and work like a charm). In that way, when using PHP-sdk you'll save the values in the session, and when Facebook class will try to retrieve them back, it'll be able of doing it.
And of course, if you're having issues with the Facebook PHP SDK, check if $_SESSION is storing the values you want, as the problem is you don't have the value in the server when you want to retrieve it, leading you to an error of not authentication.
The response is little late, but may be it will help for other users.
I have got the same issue today.
My access_token was not correctly store in $_SESSION. Apparently, client side send juste one time the access_token. You have to store it in memory (SESSION) and reused it.
In normal time, Facebook PHP SDK do it...
EDIT : See #Chococroc response for more explanations

How to retrieve User Token with server side app integration

The objective is extremely simple, yet there are no examples on how to retrieve the user token associated to the currently running app.
My objective is to just pull my public facebook page (business page with complete open access) with the app I have created in facebook that I mere created just to get an app id and secret so I can have PHP perform the request for the data and then iterate it on my homepage. Very simple, yet the documentation on the site mainly deals with facebook logins which I have no intention of doing. I just want my feeds from the public business page on the site.
This is where I think Facebook goes horribly wrong. Here is my code so far that queries properly but generates an empty data set:
$app_id = "APP_ID";
$app_secret = "APP_SECRET";
$app_token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&grant_type=client_credentials";
$response = file_get_contents($app_token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/202978003068170/feed?access_token=".$params['access_token'];
$app_details = json_decode(file_get_contents($graph_url), true);
echo '<pre>';
var_dump($app_details);
echo '<pre>';
Now let my clarify what the actual access_token value is because Facebook is vague ambiguous about this. There are actually two types of access tokens and the app I have created has both types which if you are logged in and working on your app you can see here:
https://developers.facebook.com/tools/access_token/
The major problem is the access_token value that oauth returns from the code above is the "App Token" which has no problem querying for User Profile data (which is kinda scary) but returns blank data when I try to query my Public business page {"data":[]} that I have enabled all the permissions for. After a week of trying out different methods and slamming my head on the desk and only finding partial salvation through third party sources of information did I figure out the difference between these two.
I have ran across a post on here that said I have to do a 2nd OAUTH query to pull the App's "user token" (which I have tested the user token associated to the app token from the token debugger in fbook and it works) to Facebook but what does that query consist.
Please someone help. This should not be this difficult, I am not wanting users to login to my site with fbook. I just want to display by business events, feeds and pictures on my business website.
Thank you

Using facebook SDK for php for an FQL query?

I would like to know how to use the following fql query to get a single message from my facebook inbox using facebook sdk for php (or another way if it's possible )
https://graph.facebook.com//fql?q=SELECT+body+FROM+message+WHERE++mssage_id="XXXXXXXXXXXXXXXXX_XXX"&access_token=...
(returns a JSON result)
OR
https://api.facebook.com/method/fql.query?query=SELECT+body+FROM+message+WHERE+message_id="XXXXXXXXXXXXXXXXX_XXX"&access_token=...
(returns an XML result)
both methods need an access token for a read_mailbox permission. All i need is to get the result using php. Any help ?
Thanks.
The most flexible way is to use the api method of the PHP SDK. The Facebook documentation site has examples of this.
If you already have an access token, this code will get you the data into a php array:
<?php
$query = 'SELECT body FROM message WHERE message_id = "?????????????_??"';
$token = '????';
$result = json_decode( file_get_contents('https://graph.facebook.com/fql?q=' .
urlencode($query) . '&access_token=' . $token) );
printf('<pre>%s</pre>', print_r($result, true) );
Yes you need an access token for this. If you're trying to read the mailbox of a random user, you need an app, and you'll have to follow one of the authentication workflows to get them to log into your app and give you the read_mailbox permission.

Is there a way to check if Facebook access token is still valid?

My site utilizes lifetime access tokens (offline_access). However, if the user changes his/her password, the access token gets reset. Is there a method to check if the current access token is valid before making calls to the Graph API? Thanks for your time.
Offline, without sending anything to facebook - I don't think so. The easiest way is probably to send a request to:
https://graph.facebook.com/me?access_token=...
Facebook also supports subscriptions for real-time updates, but I am not sure how to apply them to this situation.
If you want to know the token expiry time you can pass a open graph url using appid and token as below it will work .
https://graph.facebook.com/oauth/access_token_info?client_id=APPID&access_token=xxxxxxxxx
Basically, FB wants you to poll for it, or to detect the case and redirect the user to get a reauth to occur. Annoying, but official:
(Old, out of date link. See below) https://developers.facebook.com/blog/post/500/
Edit: Facebook changed their link structure without redirects. Not surprised.
https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/
You can check the token using the token debug service , take a look here
https://graph.facebook.com/debug_token?input_token=INPUT_TOKEN&access_token=ACCESS_TOKEN
https://developers.facebook.com/docs/howtos/login/debugging-access-tokens/
The real time updates would allow you to solve this problem, but it would be pretty complicated. Basically, you can subscribe to updates that will tell you 1) if the user removed the app or 2) if the user removed permissions. You could use this to store the current permissions of the faceboook user. This way, if the user removed your app you would know that the access token is expired.
Real time updates is actually facebooks recommended way of handling permissions. Many apps make api calls every time a page is loaded to check for permissions. This tends to be slow and unreliable.
I went through these posts, bud I found very good solutions like this:
GET graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app_id}|{app_secret}
Response from this request provides you everything you need:
your app ID - this verifies that token is from your application
application name - which can be also checked
expires_at - token expiration time
is_valid - boolean for check up
user_id - which you can also compare and check
Just note that "|" sign must be there as a letter
//When user access token expires user must be logged in and renew the access token him self.it is a Facebook policy
//you can overcome this by sending email to users who have expired access token.
//create a table of successful sending to monitor sending process
//if any failure happened with the user an email is sent to him to ask him to activate there account again.with a link to your subscription page.
//and here is the code should be written on that page.
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_POST_LOGIN_URL";
// known valid access token stored in a database
$access_token = "YOUR_STORED_ACCESS_TOKEN";
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP's
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
Offline - it is not possible
Ask that user has given permission or not:
https://graph.facebook.com/{facebook-id}/permissions?access_token={access-token}
If access token is invalid then it will give error:
{
error:{
message:"The access token could not be decrypted",
type:"OAuthException",
code:190
}
}
Otherwise it will give list of permission that user has given:
data:[
{
installed:1,
...... permission list.........
bookmarked:1
}
]
Updating this as things have changed since OP:
You can debug access tokens here: https://developers.facebook.com/tools/debug/accesstoken?version=v2.5&q={access_token}
Otto's answer of the facebook post seems to be the official response on this question, however it uses straight PHP instead of the SDK and also uses JS to resolve the issue instead of PHP. If you are using PHP to check for a valid session you often need a PHP method of ensuring a valid session in order to continue.
The following code checks for the me object with the graph API. If an exception is thrown it destroys* the current Facebook session.
try{
$facebook->api('/me');
}
catch( FacebookApiException $e ){
$facebook->destroySession();
}
This forces later graph calls to instantiate a new Facebook session. This at least gives you access to public data so that you can render pages do not require FB user permissions:
$facebook->api('/userName');
To reobtain user permission access the user will need to login to your app (this is distinct from being logged into Facebook itself). You can do this with JS or with PHP:
$facebook->getLoginUrl();
*Note the destroySession() call is not in a tagged release of the PHP SDK yet. Use the master branch or patch it in.