且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Facebook如何检查用户是否喜欢页面和显示内容?

更新时间:2023-12-01 20:14:52

更新21/11/2012
@ALL:我已经更新了这个例子,以便它更好地工作,并从Chris Jacob和FB Best Practices中获得了评论,看看工作示例 here

所以承诺这里是我的答案只使用javascript:

Hi So as promised here is my answer using only javascript :

页面的BODY的内容:

The content of the BODY of the page :

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
  FB.init({
    appId  : 'YOUR APP ID',
    status : true, 
    cookie : true, 
    xfbml  : true  
  });
</script>

<div id="container_notlike">
YOU DONT LIKE
</div>

<div id="container_like">
YOU LIKE
</div>

CSS:

body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}

#container_notlike, #container_like {
    display:none
}

最后javascript:

And finally the javascript :

$(document).ready(function(){

    FB.login(function(response) {
      if (response.session) {

          var user_id = response.session.uid;
          var page_id = "40796308305"; //coca cola
          var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
          var the_query = FB.Data.query(fql_query);

          the_query.wait(function(rows) {

              if (rows.length == 1 && rows[0].uid == user_id) {
                  $("#container_like").show();

                  //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

              } else {
                  $("#container_notlike").show();
                  //and here you could get the content for a non liker in ajax...
              }
          });


      } else {
        // user is not logged in
      }
    });

});

那么该怎么办?

首先它登录到FB(如果你已经有USER ID,并确定你的用户已经登录到Facebook,可以绕过登录的东西,并替换 response.session.uid 与YOUR_USER_ID(例如,您的rails应用程序)

First it logins to FB (if you already have the USER ID, and you are sure your user is already logged in facebook, you can bypass the login stuff and replace response.session.uid with YOUR_USER_ID (from your rails app for example)

之后,它在 page_fan上的FQL查询表,其含义是,如果用户是页面的风扇,则返回用户标识,否则返回一个空数组,然后根据结果显示一个div或另一个。

After that it makes a FQL query on the page_fan table, and the meaning is that if the user is a fan of the page, it returns the user id and otherwise it returns an empty array, after that and depending on the results its show a div or the other.

此外还有一个工作演示: http:// jsfiddle。 net / dwarfy / X4bn6 /

Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/

以可可可可页面为例,尝试像/不像可口可乐页面并再次运行...

It's using the coca-cola page as an example, try it go and like/unlike the coca cola page and run it again ...

最后一些rela ted docs:

Finally some related docs :

FQL page_fan表

FBJS FB.Data.query

如果您有任何问题,请不要犹豫。

Don't hesitate if you have any question ..

欢呼

更新2

正如有人,jQuery是JavaScript版本的工作,但你可以轻松地删除它(它只用于document.ready和显示/隐藏)。

As stated by somebody, jQuery is required for the javascript version to work BUT you could easily remove it (it's only used for the document.ready and show/hide).

对于文档您可以将代码封装在一个函数中,并使用 body onload =your_function或者像这样更复杂的东西: Javascript - 如何检测文档是否加载(IE 7 / Firefox 3)所以我们替换文件r eady。

For the document.ready, you could wrap your code in a function and use body onload="your_function" or something more complicated like here : Javascript - How to detect if document has loaded (IE 7/Firefox 3) so that we replace document ready.

为了显示和隐藏东西,你可以使用以下的东西: document.getElementById(container_like)。style.display =没有或阻止,更可靠的跨浏览器技术参见: http://www.webmasterworld.com/forum91/441.htm

And for the show and hide stuff you could use something like : document.getElementById("container_like").style.display = "none" or "block" and for more reliable cross browser techniques see here : http://www.webmasterworld.com/forum91/441.htm

但jQuery很简单:)

But jQuery is so easy :)

更新

相对于我在这里发布的评论,是一些ruby代码来解码signed_request在POST中将其提取到CANVAS网址,以便在Facebook中显示。

Relatively to the comment I posted here below here is some ruby code to decode the "signed_request" that facebook POST to your CANVAS URL when it fetches it for display inside facebook.

在您的操作控制器中:

decoded_request = Canvas.parse_signed_request(params[:signed_request])

然后它是检查解码的请求并显示一页或另一个..(不确定这个,我不舒服的红宝石)

And then its a matter of checking the decoded request and display one page or another .. (Not sure about this one, I'm not comfortable with ruby)

decoded_request['page']['liked']

此处是相关的Canvas类(从 fbgraph ruby​​库):

And here is the related Canvas Class (from fbgraph ruby library) :

 class Canvas

    class << self
      def parse_signed_request(secret_id,request)
        encoded_sig, payload = request.split('.', 2)
        sig = ""
        urldecode64(encoded_sig).each_byte { |b|
          sig << "%02x" % b
        }
        data = JSON.parse(urldecode64(payload))
          if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
          raise "Bad signature algorithm: %s" % data['algorithm']
        end
        expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
        if expected_sig != sig
          raise "Bad signature"
        end
        data
      end

      private

      def urldecode64(str)
        encoded_str = str.gsub('-','+').gsub('_','/')
        encoded_str += '=' while !(encoded_str.size % 4).zero?
        Base64.decode64(encoded_str)
      end
    end  

 end