Facebook PHP SDK dealing with Access Tokens - php

I have crawled around lots of various answers but am still a bit confused with how I should be dealing with facebook access tokens.
One of the main problems I'm having is due to what information is being stored in my browser. For example, I log onto the app, the token expires, I can't logon again unless I clear cookies/app settings in browser.
I stumbled across this thread: How to extend access token validity since offline_access deprecation
Which has shown me how to create an extended access token through php.
My questions are:
1. Do I need to store the access token anywhere?
2. What happens when the access token expires or becomes invalid? At the moment, my app simply stops working when the short term access ones expire.
3. Is there a way I should be handling them to check if they have expired?
I am using the php sdk and have basically used the standard if( $user )... Like this:
require 'sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXX',
));
$user = $facebook->getUser();
if( $user ){
try{
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if (!$user){
$params = array(
'scope' => 'email',
);
$loginUrl = $facebook->getLoginUrl( $params );
echo '<script type="text/javascript">
window.open("'. $loginUrl .'", "_self");
</script>';
exit;
}
if( $user ){
$access_token = $facebook->getExtendedAccessToken();
$get_user_json = "https://graph.facebook.com/me?access_token="
. $access_token;
// Rest of my code here...
}
Is there anything else I should be doing to handle tokens?
. Should I be passing the access token between pages or is it ok to just call it again at the top of each page like this:
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXX',
'redirect_uri' => 'http://localhost:8000/',
));
$token = $facebook->getExtendedAccessToken();

Let's go through your questions:
Do I need to store the access token anywhere?
This depends on your application. First of all ask yourself, do you need to perform actions on behalf of the user while he is not present (not logged in to your app)?
If the answer is yes, then you need to extend the user token which can be done using the PHP-SDK by calling this method while you have a valid user session: setExtendedAccessToken().
Also you should refer to this document: Extending Access Tokens
What happens when the access token expires or becomes invalid? ...
Is there a way I should be handling them to check if they
have expired?
This is where the catch clause in your code comes in handy, while facebook example only logs the error (error_log($e);) you should be handling it!
Facebook already has a tutorial about this: How-To: Handle expired access tokens.
Also you should refer to the Errors table and adjust your code accordingly.
Is there anything else I should be doing to handle tokens?
See above.
Should I be passing the access token between pages or is it ok to just
call it again at the top of each page
You shouldn't need to do any of that, because the PHP-SDK will handle the token for you; have you noticed that you are calling: $user_profile = $facebook->api('/me'); without appending the user access_token?
The SDK is adding it from its end so you don't have to worry about it.

I just had the same issue, but i solve it with some of your help. I'm using the php-sdk to connect to the Facebook API, so i just made this.
$facebook = new Facebook(array(
'appId' => 'API_ID',
'secret' => 'SECRET',
));
// Get User
$user = $facebook->getUser();
// Verifing if user is logged in.
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;
}
}
// Verify if user is logged in, if it is... Save the new token.
if($user){
// Request the access_token to the
$access_token = $facebook->getAccessToken()
// Saving the new token at DB.
$data = array('access_token' => $access_token);
$this->db->where('userid',$user);
$this->db->update('facebook', $data);
}

Related

Apache2 not executing facebook's php sdk

I have just started mingling with facebook's php sdk, but to no avail. Although php works fine for all the other stuff on my ubuntu instance, facebook's php sdk doesn't (i.e. php code is not executed). All dependencies (only curl and json) are enabled and working.
I tried to look into /var/log/apache2/error.log but it seems that the file is empty - but maybe I'm not looking in the correct place.
So my question is: what would be the steps for me to debug this problem! Thanks for helping a noob!
Here is the boilerplate index.php code for from facebook:
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));
// Get User ID
$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.
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;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$statusUrl = $facebook->getLoginStatusUrl();
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>

Facebook application connection doesn't work

I have a problem with my logging into my Facebook application.
When I click "login" I get redirected to Facebook to accept the permissions then Facebook redirects me back. But it doesn't change anything. The URL down is dynamic generated. When I try the same script on an other URL that's not dynamic it's work.
Here is the URL there i try to perform a login.
http://www.testaiq.se/test_592.html
What could be the problem? PHP is behind the URL over here.
require_once("facebook/facebook.php");
// Creating our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX',
));
// Getting User ID
$user = $facebook->getUser();
// Get Access token
$access_token = $facebook->getAccessToken();
// 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.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
// Retrieving user's friend list using fb graph api
$user_profile = $facebook->api('/me','GET');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_likes'
));
}

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

So this is working fine... But when I refresh the page twice(or click on two pages who include this script fast) it gives this error
OAuthException: An active access token must be used to query information about the current user.
Any ideas?
<?php
$app_id = '***************';
$app_secret = '**************';
$app_namespace = '****************';
$app_url = 'http://apps.facebook.com/' . $app_namespace . '/';
$scope = 'email,publish_actions';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get the current user
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Login Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me', 'POST');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
//<img src="https://graph.facebook.com/?php echo $user; ?/picture">
//?php print_r($user_profile); ?
?>
I personally find it easier to manage the access_token myself. Facebook's Graph API secures protected endpoints by requiring that an access_token be passed in. The PHP SDK abstracts this away, but I have never been comfortable with Facebook handling the information because sometimes it just doesn't work. This isn't to say that the library is bad, but only that I haven't been using it correctly. Keep this caveat in mind.
It looks like you're working with a Facebook Canvas App. When the user successfully authenticates for the first time, Facebook will send an access_token in $_GET. At this point, you should save this to your database, since that access token is good for 3 months or so.
At the point, from then on, you can pass in the access_token in the call parameters:
try {
$user_profile = $facebook->api('/me', 'POST', array(
"access_token" => '' // access token goes here
));
} catch (FacebookApiException $e) {
// error handling
}
Given that Facebook is returning the error that you need an access token in order to call the /me resource, it looks like $facebook->getUser(); is returning something. You may want to double-check what it is.
While I'm here, you're using this logic:
if (!conditional) {
// do something
}
if (conditional) {
// do something else
}
Confusing. Use else:
if (conditional) {
// do something
} else {
// do something else
}

Facebook api('/me') not authenticating

I've recently been trying to get my app working with the PHP SDK 3.0 and been having some trouble with it seeing that I am actually logged in. I have the "example.php" from the 3.1.1 download that doesn't acknowledge that I'm logged in. The file "with_js_sdk.php" also doesn't acknowledge that I'm logged in when you first run it. After it has been run, however both that file and the "example.php" will see that I'm logged in. Once I log out, "example.php" doesn't work and "with_js_sdk.php" fails on the first run, but all subsequent runs both files (and some other files I'm testing this with) will all authenticate correctly. When not working, all files give an "OAuthException" with the message: "An active access token must be used to query information about the current user." even when I'm logged in. So my question is, is there something in the "with_js_sdk.php" that I can set in my other files? I'm guessing it has something to do with the "oauth:true" in that file from what I've read, although I'm not a Facebook coding expert so I'm not sure. And I have an iframe app, so I don't have the "FB.init" part in my application (that worked incidentally until the change in the sdk). Here's the minimum code I'm testing that's giving the error:
<?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => '11111111111111111',
'secret' => 'abcdefghijk etc...',
'cookie'=>true
));
// See if there is a user from a cookie
$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) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
The getuser always comes back correctly, but the $facebook->api('/me') call always fails until I run a file with the fbml in it. And before you ask, yes I changed the appID and secret in the files. Thanks.
Darryl
Instead of me pass $user. Eg:
$user_profile = $facebook->api('/'.$user);
I had the same problem and suffered for the longest time, and solved it by simply getting the new PHP SDK files from https://github.com/facebook/php-sdk.
Reference: http://developers.facebook.com/docs/reference/php/
Have you tried print_r($user_profile) to see what comes out? Also, the cookie parameter is not used with the latest SDK.
You have to be aware of the scope of variables, $user_profile will be only inside the scope of you if statement, so If you want to access from outer scope it will be not available remember you can always declare your variable outside and then initialize it, this way it will be available through your php file.
?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => '11111111111111111',
'secret' => 'abcdefghijk etc...',
'cookie'=>true
));
// See if there is a user from a cookie
$user = $facebook->getUser();
$user_profile; // variable being declare outer scope
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
THIS WORKS FOR ME
$user_profile = $facebook->api('/'.$user);
And here is my full php fb connect script example: `
$fbconfig['appid' ] = " id ";
$fbconfig['secret'] = " secret ";
$fbconfig['appBaseUrl'] = "https://apps.facebook.com/ example /";
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// 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,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$me = $facebook->api('/'.$user);
} 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) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//get user basic description
$me = $facebook->api("/$user");
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}`
Have a nice day ! :)
when the token is invalid, kick off the authentication flow.
also, to get jssdk to work with php sdk v3.x, make sure you have upgrade your js sdk code to use OAuth 2.0.
you are missing with something.To have an active access token you must present it inside a session variable.And you are not even creating a session in your code.
YOU MUST HAVE AN ACCESS TOKEN FIRST
try this->
$access_token =$facebook->getAccessToken();
if ($user) {
if( session_id() ) {}
else {session_start();}
Now you should store $_SESSION['access_token']=$access_token ; for later use.

Issues getting the Facebook PHP SDK to work on my application

I was making a facebook application in which i have to show news feeds of the user who is using it. I am using graph API to do this. The problem is that its not getting me feeds.
I used it to show friends like this:
$friends = $facebook->api('/me/friends');
and it is working fine.
For news feeds i use this:
$feeds = $facebook->api('/me/home');
it shows me an error:
Fatal error: Uncaught IDInvalidException: Invalid id: 0 thrown in
/home/content/58/6774358/html/test/src/facebook.php on line 560
when i try to get Profile feed (Wall) by using this:
$feeds = $facebook->api('/me/feed');
it shows me an empty array.
These API calls are showing me results in the graph API page but don't know why not working in my application.Can any one help me please..
My full code is as follows
require_once 'src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'xxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if (!empty($session)){
$fbme = $facebook->api('/me');
}
if ($fbme) {
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
}else{
$loginUrl = $facebook->getLoginUrl();
echo 'Logout';
}
$friends = $facebook->api('/me/friends?access_token='.$session["access_token"]);
$feeds = $facebook->api('/me/feed?access_token='.$session["access_token"]);
print('<pre>Herere:');print_r($feeds);die;
Did you ask for the read_stream permission during authentication?
What type of Authentication / "Allow" process did you go through?
JavaScript SDK? Facebook PHP SDK? XFBML Login Button?
EDIT- Here are helpful link that will get you started up:
Facebook PHP SDK
Authentication Process
Building Apps on Facebook.com
These are all official docs in Facebook and github.
EDIT: Follow this step by step:
From your original code, look for:
$loginUrl = $facebook->getLoginUrl();
Change it to:
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream'));
Uninstall your application first from your account:
http://www.facebook.com/settings/?tab=applications
Then try it again to show new Allow pop-up
EDIT:
It's also about the arrangement of code in the if statements. Use this code:
<?php
require_once 'src/facebook.php';
$session = $facebook->getSession();
$fbme = null;
if($session){
$fbme = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
$feeds = $facebook->api('/me/feed');
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
echo "<pre>".print_r($feeds,TRUE)."</pre>";
}else{
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream','canvas'=>1,'fbconnect'=>0));
echo '<script> top.location.href="'.$loginUrl.'"; </script>>';
}
Uninstall your app again from
http://www.facebook.com/settings/?tab=applications
and re-open the application
The Facebook PHP SDK should handle your access token for you, you don't need to append it to your graph API endpoint in you Facebook::api() call.
As #dragonjet pointed out, you need to request the read_stream extended permission from your FB User in order to get access to their feed. Though, the exception you pasted doesn't really match that kind of problem, and your request to /me/home doesn't throw a similar exception (or one about not having access).
I still think this is a permissions issue, so start here for trying to fix it. Here's an example of how to request the appropriate permission.
$facebook = new Facebook(array(
'appId' => FB_APP_ID, //put your FB APP ID here
'secret' => FB_APP_SECRET, //put your FB APP SECRET KEY here
'cookie' => true
));
$session = $facebook->getSession();
if ($session)
{
//check to see if we have friends_birthday permission
$perms = $facebook->api('/me/permissions');
}
//we do this to see if the user is logged & installed
if (empty($session) || empty($perms['read_stream']))
{
//get url to oauth endpoint for install/login
$loginUrl = $facebook->getLoginUrl(array(
//put the URL to this page, relative to the FB canvas
//(apps.facebook.com) here vvv
'next' => 'http://apps.facebook.com/path_to_your_app/index.php',
'req_perms' => 'read_stream'
));
//use javascript to redirect. the oauth endpoint cant be loaded in an
//iframe, so we have to bust out of the iframe and load it in the browser
//and tell the oauth endpoint to come back to the fb canvas location
echo "<script>window.top.location='{$loginUrl}';</script>";
exit;
}
print_r($facebook->api('/me/home'));
print_r($facebook->api('/me/feed'));

Categories