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

我正在尝试创build一个Facebook的iFrame应用程序。 该应用程序应该首先显示一个图像,如果用户喜欢该页面,他将访问一些内容。

我使用RoR,因此我无法使用Facebook PhP SDK。

这是我的iFrame的HTML,当用户不喜欢的页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <link rel="stylesheet" type="text/css" href="style.css" /> <style type="text/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;} </style> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <div id="container"> <img src="welcome.png" alt="Frontimg"> </div> 

而且,如果用户喜欢该页面:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <link rel="stylesheet" type="text/css" href="style.css" /> <style type="text/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;} </style> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <div id="container"> <img src="member.png" alt="Frontimg"> <p>You liked this page</p> 

更新21/11/2012 @ALL:我已经更新了示例,以便它更好地工作,并考虑到克里斯·雅各布和FB的最佳实践的说法,看看这里的工作示例


嗨所以在这里承诺是我的答案只使用JavaScript:

页面的BODY内容:

 <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:

 $(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 } }); }); 

那么它是做什么的?

首先它login到FB(如果你已经有了用户ID,并且你确定你的用户已经login了Facebook,你可以绕过login的东西,用YOUR_USER_IDreplaceresponse.session.uid (例如从你的rails应用程序)

之后,它在page_fan表上进行FQL查询,其含义是如果用户是页面的粉丝,则返回用户ID,否则返回一个空数组,然后根据结果显示一个div或其他。

还有一个工作演示在这里: http : //jsfiddle.net/dwarfy/X4bn6/

以可口可乐页面为例,尝试一下,像可口可乐页面一样 ,再次运行。

最后是一些相关的文档:

FQL page_fan表

FBJS FB.Data.query

不要犹豫,如果你有任何问题..

干杯

更新2

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

对于document.ready,你可以将你的代码包装在一个函数中,并使用body onload="your_function"或者像这里更复杂一些: Javascript – 如何检测文档是否已经加载(IE 7 / Firefox 3),以便我们replace文档准备。

而对于显示和隐藏的东西,你可以使用类似于: document.getElementById("container_like").style.display = "none" or "block"和更可靠的跨浏览器技术,请看这里: http://www.webmasterworld的.com / forum91 / 441.htm

但jQuery是如此简单:)

UPDATE

相对于我在这里下面发布的评论,这里是一些ruby代码来解码“signed_request”,Facebook的POST到您的CANVAS的URL,当它获取它显示内facebook。

在你的动作控制器中:

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

然后它是一个检查解码的请求和显示一个或另一个页面的问题。(不知道这个,我不熟悉的ruby)

 decoded_request['page']['liked'] 

这里是相关的Canvas类(来自fbgraph ruby​​库 ):

  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 

你需要写一点PHP代码。 当用户第一次点击标签,你可以检查他是否喜欢页面或不。 以下是示例代码

 include_once("facebook.php"); // Create our Application instance. $facebook = new Facebook(array( 'appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_SECRET, 'cookie' => true, )); $signed_request = $facebook->getSignedRequest(); // Return you the Page like status $like_status = $signed_request["page"]["liked"]; if($like_status) { echo 'User Liked the page'; // Place some content you wanna show to user }else{ echo 'User do not liked the page'; // Place some content that encourage user to like the page } 

这里是一个工作的例子,这是这个答案的一个分支:

 $(document).ready(function(){ FB.login(function(response) { if (response.status == 'connected') { var user_id = response.authResponse.userID; var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id; FB.api({ method: 'fql.query', query: fql_query }, function(response){ if (response[0]) { $("#container_like").show(); } else { $("#container_notlike").show(); } } ); } else { // user is not logged in } }); }); 

我使用了FB.api方法(JavaScript SDK),而不使用FB.Data.query。 或者你可以像这个例子一样使用Graph API:

 $(document).ready(function() { FB.login(function(response) { if (response.status == 'connected') { var user_id = response.authResponse.userID; var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id; FB.api('/me/likes/'+page_id, function(response) { if (response.data[0]) { $("#container_like").show(); } else { $("#container_notlike").show(); } }); } else { // user is not logged in } }); });​ 

JavaScript代码需要进行一些更改,以便根据用户喜好来处理呈现,或者不喜欢Facebook转移到Auth2.0授权的页面。

改变相当简单: –

会话必须由authResponse和用户ID的uidreplace

而且考虑到代码的要求以及人们(包括我)在FB.login中面临的一些问题,使用FB.getLoginStatus是一个更好的select。 它将查询保存到FB以防用户login并validation了您的应用程序。

有关如何将查询保存到FB服务器的信息,请参阅“响应和会话对象”部分。 http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

FB.login的问题及其使用FB.getLoginStatus的修复。 http://forum.developers.facebook.net/viewtopic.php?id=70634

这里是上面贴出的代码,对我的改变。

 $(document).ready(function(){ FB.getLoginStatus(function(response) { if (response.status == 'connected') { var user_id = response.authResponse.userID; 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 } }); }); 

使用Javascript SDK,您可以更改代码如下,这应该在FB.init调用后添加。

  // Additional initialization code such as adding Event Listeners goes here FB.getLoginStatus(function(response) { if (response.status === 'connected') { // the user is logged in and has authenticated your // app, and response.authResponse supplies // the user's ID, a valid access token, a signed // request, and the time the access token // and signed request each expire var uid = response.authResponse.userID; var accessToken = response.authResponse.accessToken; alert('we are fine'); } else if (response.status === 'not_authorized') { // the user is logged in to Facebook, // but has not authenticated your app alert('please like us'); $("#container_notlike").show(); } else { // the user isn't logged in to Facebook. alert('please login'); } }); FB.Event.subscribe('edge.create', function(response) { alert('You liked the URL: ' + response); $("#container_like").show(); } 

这里有一篇文章描述了你的问题

http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/

  <fb:visible-to-connection> Fans will see this content. <fb:else> Non-fans will see this content. </fb:else> </fb:visible-to-connection>