How do I make a logout using Facebook's api log me out of my app (a website), but keep me logged into facebook.com?
This logs me in alright:
window.fbAsyncInit = function()
{
FB.init({
appId : '<?= APP_ID ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function(response)
{alert(response);
window.location = 'http://reviewsie.com/accounts/facebook';
});
};
(function(d)
{
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
But then I click logout on my site which I kill my session to my app. Then when you click on the fb:login-button again, it just opens and closes and doesn't do anything because I'm still connected to facebook. I want it to redirect.
But if when I logout I also use Facebook::logoutUrl it logs me out of my app AND facebook which is not what I want.
A bit late but might help someone. You can revoke app permissions which effectively logs them out of your app. Here's the code:
FB.api('/me/permissions', 'delete', function(response) {
console.log(response.status); // true for successful logout.
});
This works for me:
window.fbAsyncInit = function() {
FB.getLoginStatus(function(response) {
FB.api("/me/permissions", "delete", function(response){
});
});
}
Are you sure you want to only logout of your app, and not fb too, if you logged in using fb? What kind of app could want to do something like that? And why? What's the benefit of doing so?
But if you really want to (hack), in index.php:
<?php
require 'init.php'; // general init
require 'init_fb.php'; // sets $fb_id if logged in to fb
if (isset($fb_id) and !isset($_SESSION['do_not_auto_login'])) {
echo "<a href='/logout'>Logout</button>";
include 'app.php';
return;
}
if (isset($_SESSION['do_not_auto_login'])
echo "<a href='/re_login'>FB Login</button>";
else include 'html_and_js_fb_login_code_and_button.php';
include 'startpage.php';
?>
and in logout.php:
$_SESSION['do_not_auto_login'] = true;
// destroy-code
and in re_login.php:
unset($_SESSION['do_not_auto_login']);
header("location: /"); // re-direct back to index.php
Not perfect, but works somewhat good. Hope you get the hack!
But still, why?? If you don't think your user would like to come back, ask "How to remove my fb-app from user?" or something instead or try #DMCS's answer.. Why?
You need to use destroySession for Facebook to do
www.example.com?act=logout
<?php
php sdk blah blah
if($_GET['act'] =='logout'){
$facebook->destroySession();
}
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'https://www.myapp.com/post_login_page'
);
$loginUrl = $facebook->getLoginUrl($params);
?>
Maybe you need to set param to make it redirect.
When the user is logged into your app, send an HTTP DELETE call to /me/permissions using their current access token. This will log them out of your app requiring them to re-authenticate if they want to play some more. Also be sure to destroy the php session using normal php session clearing code.
Related
I’m new to PHP and tying to set up a page as so users can login using Facebook PHP SDK and JavaScript SDK. I keep getting the fallowing error and I don’t seem to be able to find a solution.
I saw a similar post in here but I couldn’t give solution to the error.
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /homepages/9/d321009915/htdocs/kno_login/login.php on line 2
Here is my code:
<?php
echo '<div id='fb-root'></div>';
require_once("facebook.php");
$config = array();
$config['appId'] = 'some id';
$config['secret'] = 'something here';
$facebook = new Facebook($config);
?>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '293441190799565', // App ID
channelUrl : '//www.reyesmotion.com/kno_login/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked.
Learn more about options for the login button plugin:
/docs/reference/plugins/login/ -->
<?php
echo '<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>';
?>
Just change the outer single quotes to double
echo "<div id='fb-root'></div>";
Possible duplicate of facebook Uncaught OAuthException: An active access token must be used to query information about the current user
But I did not get a proper solution.
I am using facebook sdk with codeigniter it is working properly. but sometimes it throws exception OAuthException: An active access token must be used to query information about the current user.
Here is the code of Controller file
$config = array(
'appId' => 'XXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
'fileUpload' => true,
);
$this->load->library('facebook/Facebook', $config);
$fbme = null;
$user = $this->facebook->getUser();
if ($user) {
try {
$fbme = $this->facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
//if user is logged in and session is valid.
if ($fbme){
//do some stuff...
//redirecting to user home page (my site's)
}
In view file, I am using js sdk. Code for view file is
<div id="fb-root"></div>
<script type="text/javascript">
var button2;
window.fbAsyncInit = function() {
FB.init({ appId: 'XXXXXXXX',
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
button1 = document.getElementById('fb-login'); //login button
button2 = document.getElementById('fb-logout'); //logout button
if (response.authResponse) {
//user is already logged in and connected
button2.onclick = function() {
FB.logout(function(response) {});
};
} else {
//user is not connected to your app or logged out
button1.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'email,user_birthday,user_about_me,user_likes,user_interests,user_education_history,user_work_history'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
PROBLEM:
Sometimes the it throws "OAuthException: An active access token must be used to query information about the current user." to the error log file.
Case: user is logged in facebook and has already authenticated my app
If a user is logged in facebook and authenticated my app and tries to logged in to my site,
rather redirecting the user to my site (php sdk is not working in this case), it is loading the view file. In view file also I am checking whether the user is logged in in facebook or not. (in view) if the user is logged in it will reload the page, same controller script will run and it redirects the user to user's home page(php sdk is working in this case.).
But first time it is not working. Don't know where I am making the mistake.
Also that logout button (in view file) is also sometimes not working. Means on clicking it is not logging out the user from facebook. (It is only happening in one of my colleague's browser. She is using chrome in windows 7)
I was having a similar problem while using PHP-SDK + JS-SDK together. I temporarily solved it by removing the FB.init "cookie:true" option.
By some reason that I couldn't find, an invalid signedRequest cookie is being shared between PHP and JS, then, the valid access_token of the PHP Session was being override with an invalid access_token, thus, destroying the previously valid PHP token.
The difference between my problem and yours is that you're logging via JS and trying to access the same session on PHP (I was doing it backwards, logging on PHP and trying to use the JS-SDK).
This bug is apparently fixed on this pull request:
https://github.com/facebook/facebook-php-sdk/pull/48
I am integration Facebook connect in my website using php SDK.. Everything is working fine except that I want that instead of redirecting to facebook for authentication, I want to open OAuth Dialog.. Currently Im using following url for authentication,.. It redirects to facebook but doesn't open OAuth Dailog..
https://www.facebook.com/dialog/oauth?client_id=XXXXXXXXXXX&redirect_uri=http%3A%2F%2Fwww.setsail2nz.com.au%2Fmicrosite%2Ffbalbums.php%3Fpid%3D1&state=ad89eddd7f71e7337785f604710c97e8&scope=user_photos%2Cpublish_stream%2Cmanage_friendlists%2Cemail&display=popup
Any ideas?
EDIT:
I know how to do it with Facebook JS SDK.. But is there a way to do it with php?
Edit 2: Okay now im using JS SDK but still its not opening the dialog.. Here is my code
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // enables OAuth 2.0
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
function fblogin()
{
FB.login(function(response)
{
alert(response);
},{perms: "user_photos,publish_stream,manage_friendlists,email"});
}
</script>
Use Javascript SDK
https://developers.facebook.com/docs/reference/javascript/
And FB.login, passing your required permissions
To answer your question about detecting the dialog response with PHP SDK:
The problem is that getloginURL only takes one URL parameter that it uses on success or error. I needed to detect if the user clicked OK or Cancel on the permissions dialog, so I could either redirect to a pre-permissions dialog page, or show the correct logged-in content.
All I did was check if 'error_reason' existed in the url parameters, and if the error was 'user_denied', and took appropriate action. There might be a better way, but this worked for me.
<?php
//Facebook Authentication
$user = $facebook->getUser();
//Get Login URL
$loginUrl = $facebook->getLoginUrl();
//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;
}
}
//User is not logged in
if (!$user) {
//Check if error_reason was generated and if the user denied login
if (isset($_REQUEST['error_reason']) && ($_REQUEST['error_reason']=='user_denied')) {
//user cancelled permissions dialog thus not logged in to app, redirect elsewhere
echo "<script type='text/javascript'>top.location.href = 'YOUR REDIRECT URL';</script>";
exit;
} else {
//user not logged in so initiate permissions dialog
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
}
//get user basic description
$userInfo = $facebook->api("/$user");
?>
This question already has an answer here:
Codeigniter, Facebook javascript SDK, PHP SDK Redirect after facebook login doesn't getUser() until refresh
(1 answer)
Closed 5 years ago.
I am implementing Facebook login using the PHP SDK with Codeigniter. I get the Facebook login popup, hit login, but I am unable to retrieve the user's id - it always returns 0.
I have put the facebook.php and base_facebook.php files in my libraries file and included it as a library in Codeigniter following a tutorial here.
Can anyone tell me what they think is going on? I am using the following code -
View - Facebook login button
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $this->config->item('facebook_app_id'); ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function() {
window.location='<?php echo base_url(); ?>auth_other/fb_signin/';
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div class="fb-login-button">Login with Facebook</div>
Controller - auth_other/fb_signin
function fb_signin()
{
$fb_user = null;
$fb_config = array(
'appId' => $this->config->item('facebook_app_id'),
'secret' => $this->config->item('facebook_app_secret')
);
$this->load->library('facebook',$fb_config);
$fb_user = $this->facebook->getUser();
echo $fb_user;
I was stuck up with similar issue, here is the solution that may help you.
$facebook = new Facebook(array(
'appId' => 'xxxx',
'secret' => 'xxxxx',
"redirect_uri" => "set the uri to point to the same page"
));
$user = $facebook->getUser();
if($user)
{
//your task
} else {
header('location:'. $facebook->getLoginUrl());
}
$user = $facebook->getUser();
if($user)
{
//your task
} else {
header('location:'. $facebook->getLoginUrl());
}
Came across a situation where getUser() was returning 0 when it really shouldn't be, the application was still sandboxed. Turns out the user hadn't accept the request to be developer of the application.
I've encountered a similar problem. I used an example project, and couldn't figure out why it keeps returning 0. tried nearly all related links here but none solved it.
The solution was to update Facebook's SDK files in the example project.
Simple and easily missed,
I had same issue, After long time of trying to figure out what the issue is,
I found that you need access token to get user ID.
To get access token form the signed_request, user must authorize (to get permissions) you app firstly.
I hope this will help
If App domain is real domain but site url is localhost, getUser function return 0
I am trying to migrate to the new Facebook API for websites, and just can't get it to work smoothly. I would like to use the Javascript and PHP SDKs together, but am having problems. I can authenticate, but the page doesn't refresh automatically.
I have searched throughout SO and the Facebook documentation, but still can't get this to work correctly. I have read through http://developers.facebook.com/blog/post/534/, dowloaded the latest PHP SDK (3.1.1), and basically copied the example on the aforementioned post from facebook. I have made what I think are the correct settings in my app 'Migration' settings, but this could be where the problem lies. I can't post an image, so here are the setting:
Remove Deprecated API's: Enabled
Forces use of login secret: Enabled
Encrypted Access token: Enabled
Enhanced Auth Dialog: Enabled
(Everything else is disabled)
Here is the code:
<?php
require 'php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// 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;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user_profile) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
I was going to write this as a comment but it got a bit long... :)
A couple of pointers using the PHP SDK:
$facebook->getUser();
This will work regardless of authentication. getUser() pulls publicly available data that does not require an access token, HOWEVER if you do have an access token and the user has provided email permissions for example, this method will also contain their email address.
A better test for an authenticated user:
$code = $_REQUEST['code'] ? true : false;
if (!$code) {
echo ("<script>window.top.location=\"...\"</script>");
}
will check if a user has authorised your app.
$access = $facebook->getAccessToken();
Make sure that you always request the Access Token (priority!) You will only ever recieve a signed request when you have been redirected from a facebook dialogue to your app. (i.e.) oAUTH dialogue. This method of the SDK will also save your Access Token to a session variable. You can call the getAccessToken() method on any subsequent app page where a PHP session is active EVEN WHEN no signed request has been issued.
Now that you have your valid access token for the logged in user, you can proceed with:
$user = $facebook->api('/me');
or, simpler still:
$user = $facebook->getUser();
I tend to reserve API calls for more complex requests such as posting to a users feed / friends feed.
So to recap:
-> check for $code
-> get signed request on first page after oAuth dialogue.
-> If browser cookies are disabled (likely in ie) don't forget to pass your session to the next page with the SID constant. If you don't, you will loose your stored access token (not good!).