简体   繁体   中英

Facebook SDK getUser() method returns 0 after successful authorization

I recently changed my host and noticed that Facebook login is no longer working. It is not throwing any errors, but it's simply not working.

My code: Tested with the given example

My workflow:

  1. User clicks on the login button (getLoginUrl() method).
  2. Facebook authorization window pops up
  3. User accepts it and gets redirected back to my page with ?code=..&state=..
  4. getUser() returns 0, but it should return the users ID

I tried googling for answers. This is what I tried:

  1. To change the getCode() method -> _REQUEST problem
  2. Turn on/off cookies

Is there anything else I can do to fix this problem?

Try following, add the JS code below the page where you are doing authentication

<div id="fb-root"></div>

<script type="text/javascript">
    window.fbAsyncInit = function()
            {
                FB.init
                ({
                    appId   : 'your fb 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
                });
                FB.Event.subscribe('auth.login', function()
                {
                    window.location.reload();
                });
            };

          (function()
          {
            var e = document.createElement('script');
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
            }());
</script>

Make sure you add a div with id = "fb-root" within the HTML and closed that, best practice is to add that above your JS code as above.

Then use the PHP script to generate the login button and add the following code on the top of your page so that when the page reloads the code gets executed

require_once 'src/facebook.php'; //include the facebook php sdk
$facebook = new Facebook(array(
    'appId'  => 'XXXXXXXXXXXXXX',    //app id
    'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX', // app secret
));

$user_id = $facebook->getUser();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM