-1

After I login in my application using facebook sdk I am getting the facebook user id but after some time it automatically gets destroyed . This is happening frequently . I need to refresh the page every now and then . Can anyone help me to find the solution why this is happening ? I am using both javascript and php sdk . I have searched for the same but i have not got any proper solution .

Plz someone help me with this...

Here is the code I am using to login :

<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);
            }());
            function loginfb()
            {
                FB.login(function(response) {
                    if (response.authResponse) {
                        //alert('Success!');
                    } else {
                        //alert('Login Failed!');
                    }
                }, {scope: 'manage_pages,publish_actions,email'});
            }
            (function(d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id))
                    return;
                js = d.createElement(s);
                js.id = id;
                js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=<?php echo APP_ID_KEY; ?>";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));

and here is the php code which i am using to get the facebook user id :

require_once('facebook.php');


$facebook = new Facebook(array(
  'appId'  => APP_ID_KEY,
  'secret' => APP_SECRET,
));

$site_url = CALLBACK_URL;
// Get User ID

$user = $facebook->getUser();


if ($user) {
  try {

        // Proceed knowing you have a logged in user who's authenticated.
        $user_profile = $facebook->api('/me');
        $friends = $facebook->api('/me/friends');

    $token=$facebook->getAccessToken();

  } catch (FacebookApiException $e) {
    error_log($e);`enter code her`enter code here`e`
    $user = null;
  }
}

Now when I login for the first time I am getting the facebook user id but after some time automatically it becomes zero so i need to click on login button again to get the user id this is happening very frequently and its very annoying..

CBroe
  • 91,630
  • 14
  • 92
  • 150

2 Answers2

0
  1. Session garbage collector can delete session file if is not modified
  2. Probably you are using short life access token so when you call FB api you receive exception where FB session is cleared
  3. I had problem with using JS and PHP SDK on site, PHP was interpreting JS cookie (shared session == false, in JS auth you are receiving short life access token) and i resolved it by diseabling cookie in JS init.

PS check what Facebook exception is saying

  • I tried setting cookie: false in JS init but now I am not able to login and I am not getting user ID also . Strange it does not gives me any error when logging in but After login the page is not redirecting . When I keep cookie : true it works fine – Sanket Parghavi Sep 26 '13 at 06:42
  • Yes becouse you are fetching user via JS SDK so you must have shared session or as i did it ajax call with JS login response and set PHP session manually with extended access token. – Rafał Dziędzioł Sep 26 '13 at 07:06
  • How can i set the php session with extended access token and how can i get the extended access token ? – Sanket Parghavi Sep 26 '13 at 07:13
  • How it works for me JS side: in init only status is true, i can login user via JS (ajax call with response), JS is working fine. PHP side: shared session false, everything works fine with extended access token. Why this way? When i had shared session false and enabled cookie in JS that %&^%# PHP SDK gets information from that cookie so session was destroyed on expire or on exception caused expired access token taken from that cookie. PS PHP SDK have function setExtendedAccessToken() to obtain and save to session extended access token. – Rafał Dziędzioł Sep 26 '13 at 07:17
  • I tried setting setExtendedAccessToken() but the problem is that I am getting facebook ID '0' so anything I do will not reflect until the facebook ID keeps on changing to '0' . – Sanket Parghavi Sep 26 '13 at 08:49
  • $user = $facebook->getUser(); if ($user) { try { $facebook->setExtendedAccessToken(); // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); $friends = $facebook->api('/me/friends'); $token=$facebook->getAccessToken(); } catch (FacebookApiException $e) { error_log($e); $user = null; } This code is executed after I login with js sdk but still the session times out as i get $user '0' – Sanket Parghavi Sep 26 '13 at 12:41
  • also check this link:http://stackoverflow.com/questions/15140130/getting-the-facebook-session-at-the-server-side-if-we-login-using-js-sdk – Sanket Parghavi Sep 26 '13 at 12:44
0

This is JS side

window.fbAsyncInit = function() {
    FB.init({
    appId      : app_id, 
    status     : true,
    });         
};
(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/pl_PL/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));


//callback - function called after succeed login 
//opts - The same opts as in FB.login().
function login(callback, opts)
{
    //opts must be an object
    if (!opts || typeof(opts) !== "object") {
        opts = null;
    }

    FB.getLoginStatus(function(statusResponse) { //check login status
        if(statusResponse.status === 'connected') { //user logged in
            if(opts !== null && opts.scope !== null) {
                //if there is scope opt check that user grant access to all permissions
                FB.api('/me/permissions?fields='+opts.scope, 'get', {access_token : statusResponse.authResponse.accessToken }, function(response) { 
                    var perms = opts.scope.split(',');
                    for(var i=0;i<perms.length;i++) {
                        if(response.data[0][perms[i]] !== 1) {
                            //one of permissions fails - do login and break loop
                            FB.login(function(loginResponse) {
                                if(loginResponse.status === 'connected')
                                    proceedLogin(loginResponse.authResponse,callback); //ajax call
                            }, opts);
                            return;
                        }
                    }

                    //every perm is granted, great so let's proceed user login
                    proceedLogin(statusResponse.authResponse,callback);//ajax call
                });
            } else {
                //there's no opts or no perms to check
                proceedLogin(statusResponse.authResponse,callback);//ajax call
            }
        } else { //user not logged in :(
            FB.login(function(loginResponse) {
                if(loginResponse.status === 'connected')
                    proceedLogin(loginResponse.authResponse,callback);//ajax call
            }, opts);
        }

    });
}
function proceedLogin(authResponse,callback) {
    $.post('/ajax/login', authResponse, function(data) {
        if (data.user && callback && typeof(callback) === "function") {
            callback();
        }   
    });
}

and this is PHP side

function login() {
    //FB() your facebook instance
    FB()->setAccessToken( $_POST['accessToken'] ); //set access token from JS
    FB()->setAccessToken( FB()->setExtendedAccessToken() );
    $user = FB()->getUser();

    echo json_encode(array( 'user' => $user ));

}