简体   繁体   中英

Facebook login link works but not the login button, any ideas why?

I'm trying to create a php page where the user can login and then like my page. If I use the login_url in a block, it works great.

However I'd like to use the official facebook login button, particularly because it allows the locale to be passed in, and then it will be localized to the right language.... and it looks nice!

Doing some research, it seems as though the login state in php is not in synch with the login state in js, but I have only seen bits and pieces of code (most of it with obsolete versions of the api).

Can anyone please point me in the right direction as to what I need to do here to make the facebook login button do the same thing as the $login_url?

Right now I observe the following behavior:

  1. I open up the page and the Login button and link is visible because the php code thinks the user is not logged in
  2. I click the Login Button and log in
  3. The php code still thinks the user is not logged in, so it still shows the login button
  4. Only until I click the Login link do I get logged in correctly and the login button disappears on reload.

Right now clicking the button just reloads the page and doesn't even ask the user to login. And if the user is logged in using the login-button, the php part of the page thinks the user is not logged in...

<?php 

require("facebook/facebook.php");

$locale = "en_US"; // TODO

$connect_facebook_url = "'//connect.facebook.net/" . $locale . "/all.js#xfbml=1&appId=XXXXXXXXXXXXXXXXXXXXXXX'";

$facebook = new Facebook(array(
  "appId"  => "XXXXXXXXXXXXXX",
  "secret" => "XXXXXXXXXXXXXXXXX",
  "cookie" => true,
));

$access_token = $facebook->getAccessToken(); 

// Get User ID
$user_id = $facebook->getUser();

if($user_id) 
{
  // We have a user ID, so probably a logged in user.
  // If not, we'll get an exception, which we handle below.
  try 
  {
    $user_profile = $facebook->api('/me','GET');

    $likes = $facebook->api(array( 
      'method' => 'fql.query',
      'query' => 'SELECT page_id FROM page_fan WHERE uid = "'
                 . $user_profile['id']
                 . '" AND page_id="XXXXXXXXXXXXX"', )); 

  } 
  catch(FacebookApiException $e) 
  {
    // If the user is logged out, you can have a 
    // user ID even though the access token is invalid.
    // In this case, we'll get an exception, so we'll
    // just ask the user to login again here.
    $login_url = $facebook->getLoginUrl(); 
    error_log($e->getType());
    error_log($e->getMessage());
  }   
} 
else 
{
  // No user, print a link for the user to login
  $login_url = $facebook->getLoginUrl();
}

if(count($likes) > 0) 
{
  $likes_result = "User likes this page"; 
}
else 
{
  $likes_result = "User doesnt like this page";
}

if($login_url)
{
  $login_string = '<a href="' . $login_url . '">' . 'IDST_MENUITEM_SIGN_IN' . '</a>';
}

?>

<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> 
<div id="fb-root"></div>
<script>
  (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 = 
    <?php echo $connect_facebook_url; ?>
    ;
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
</script>

<body bgcolor="#000000">

<div align="center">
  <table>
  <tbody>
  <tr>
    <td>    
      <img src="http://www.myapp.com/wp-content/uploads/2012/05/MyApp-logo.png"/>
    </td>
    <td style="align:left; vertical-align:middle">
      <p style="font-family:segoe ui;color:white;font-size:40px;">MyApp</p>
    </td>
  </tr>
  </tbody></table>
</div>

<p>&nbsp<p>

<div align="center" style="font-family:segoe ui;color:white;font-size:20px;">
  <?php if ($login_string) : ?>
    <div class="fb-login-button" size="xlarge" data-width="200"></div>
  <?php else: ?>
    <div class="fb-like" 
         data-href="https://www.facebook.com/MyApp" 
         data-width="200" 
         data-colorscheme="dark" 
         data-show-faces="true" 
         data-send="true">
    </div>
  <?php endif; ?>

  <br>

  <p>
    <?php echo $likes_result; ?>
  </p>
  <p>
    <?php echo 'Please <a href="' . $login_url . '">login.</a>'; ?>
  </p>
</div>

</body>
</html>

There You Go. Hope this helps

<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <style type="text/css">
      div#container_notlike, div#container_like {
        display: none;
      }
    </style>
  </head>
  <body>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId      : 'YOUR_APP_ID', // App ID
          channelUrl : 'http(s)://YOUR_APP_DOMAIN/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
        });

        FB.getLoginStatus(function(response) {
          var page_id = "YOUR_PAGE_ID";
          if (response && response.authResponse) {
            var user_id = response.authResponse.userID;
            var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
            FB.Data.query(fql_query).wait(function(rows) {
              if (rows.length == 1 && rows[0].uid == user_id) {
                console.log("LIKE");
                $('#container_like').show();
              } else {
                console.log("NO LIKEY");
                $('#container_notlike').show();
              }
            });
          } else {
            FB.login(function(response) {
              if (response && response.authResponse) {
                var user_id = response.authResponse.userID;
                var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
                FB.Data.query(fql_query).wait(function(rows) {
                  if (rows.length == 1 && rows[0].uid == user_id) {
                    console.log("LIKE");
                    $('#container_like').show();
                  } else {
                    console.log("NO LIKEY");
                    $('#container_notlike').show();
                  }
                });
              } else {
                console.log("NO LIKEY");
                $('#container_notlike').show();
              }
            }, {scope: 'user_likes'});
          }
        });
      };

      // Load the SDK Asynchronously
      (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 id="container_notlike">
      YOU DON'T LIKE ME :(
    </div>

    <div id="container_like">
      YOU LIKE ME :)
    </div>

  </body>
</html>

Replace the "YOUR_PAGE_ID" with your page id.

if (rows.length == 1 && rows[0].uid == user_id) {
                        console.log("LIKE");
                        $('#container_like').show();
                        //window.location=YOURPHP.php    

If you use window.location you will be redirected to YOURPHP.pho, if you dont want that

use ajax here in the code.

$.post("database.php",{userid: user_id, likes:1"},
  function(data,status){
  console.log(data);
console.log("LIKE");
  $('#container_like').show();
  posttofacebook(caption);
  document.getElementById("captionresult").innerHTML=data;
}); 
                      }

If you have any suggesstion queries or doubts on this.. Feel free to contact.

Try using session

if($user_id) {
    try {
        $user_profile = $facebook->api('/me','GET');
        $_SESSION['user'] = $user_profile['id'];
    }
}

Then on your html page, you can add:

<?php if(isSet($_SESSION['user'])) { ?>
         Your html content here
    <?php } ?>

In case session not started, just add session_start() at the begging of page. Hope this will help

I had the same problem and solved it with a simple one line setting:

in FB.init you have no xbmfl default value set, so it's defaulting to false and thus not rendering any social icons. Simply add

$facebook = new Facebook(array(
  "appId"  => "XXXXXXXXXXXXXX",
  "secret" => "XXXXXXXXXXXXXXXXX",
  "cookie" => true,
  "xbmfl" => true
));

According to the facebook initialization documentation : XBMFL: Determines whether XFBML tags used by social plugins are parsed, and therefore whether the plugins are rendered or not. Defaults to false.

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