Javascript Facebook如何检查用户是否喜欢页面并显示内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6246449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Facebook how to check if user has liked page and show content?
提问by Rails beginner
I am trying to create a Facebook iFrame app. The app should first show an image and if the user likes the page, he will get access to some content.
我正在尝试创建一个 Facebook iFrame 应用程序。该应用程序应首先显示图像,如果用户喜欢该页面,他将可以访问某些内容。
I use RoR, therefore I can't use the Facebook PhP SDK.
我使用 RoR,因此我不能使用 Facebook PhP SDK。
Here is my iFrame HTML when the user has not liked the page:
当用户不喜欢该页面时,这是我的 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>
And, if the user has liked the page:
并且,如果用户喜欢该页面:
<!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>
回答by dwarfy
UPDATE 21/11/2012@ALL : I have updated the example so that it works better and takes into accounts remarks from Chris Jacob and FB Best practices, have a look of working example here
2012 年 11 月21日更新 @ALL:我已经更新了示例,以便它更好地工作,并考虑了 Chris Jacob 和 FB Best Practices 的评论,看看这里的工作示例
Hi So as promised here is my answer using only javascript :
嗨,正如所承诺的,这是我仅使用 javascript 的答案:
The content of the BODY of the page :
页面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>
The CSS :
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
}
And finally the javascript :
最后是 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
}
});
});
So what what does it do ?
那么它有什么作用呢?
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)
首先它登录到 FB(如果您已经拥有 USER ID,并且您确定您的用户已经登录到 Facebook,您可以绕过登录内容并替换response.session.uid
为 YOUR_USER_ID(例如来自您的 rails 应用程序)
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.
之后它对表进行 FQL 查询page_fan
,意思是如果用户是页面的粉丝,它返回用户 id,否则返回一个空数组,然后根据结果显示一个 div或另一个。
Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/
这里还有一个工作演示:http: //jsfiddle.net/dwarfy/X4bn6/
It's using the coca-cola page as an example, try it go and like/unlike the coca cola pageand run it again ...
它以可口可乐页面为例,尝试去喜欢/不喜欢可口可乐页面并再次运行它......
Finally some related docs :
最后是一些相关的文档:
Don't hesitate if you have any question ..
如果您有任何问题,请不要犹豫..
Cheers
干杯
UPDATE 2
更新 2
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).
正如某人所说,javascript 版本需要 jQuery 才能工作,但您可以轻松删除它(它仅用于 document.ready 和显示/隐藏)。
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.ready,您可以将代码包装在一个函数中并使用body onload="your_function"
或更复杂的东西,例如:Javascript - 如何检测文档是否已加载(IE 7/Firefox 3),以便我们替换文档准备就绪。
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
对于显示和隐藏的东西,你可以使用类似的东西:document.getElementById("container_like").style.display = "none" or "block"
以及更可靠的跨浏览器技术,请参见此处:http: //www.webmasterworld.com/forum91/441.htm
But jQuery is so easy :)
但是 jQuery 太简单了 :)
UPDATE
更新
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.
相对于我在下面发布的评论,这里有一些 ruby 代码,用于解码 facebook POST 到您的 CANVAS URL 的“signed_request”,当它获取它以在 facebook 内显示时。
In your action controller :
在您的动作控制器中:
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)
然后就是检查解码的请求并显示一页或另一页..(不确定这个,我对 ruby 不满意)
decoded_request['page']['liked']
And here is the related Canvas Class (from fbgraph ruby library) :
这是相关的 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
回答by Inam Abbas
You need to write a little PHP code. When user first click tab you can check is he like the page or not. Below is the sample code
您需要编写一些 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
}
回答by Alexey Khrenov
Here's a working example, which is a fork of this answer:
这是一个工作示例,它是这个答案的一个分支:
$(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
}
});
});
I used the FB.api method (JavaScript SDK), instead of FB.Data.query, which is deprecated. Or you can use the Graph API like with this example:
我使用了 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
}
});
});?
回答by karora
There are some changes required to JavaScript code to handle rendering based on user liking or not liking the page mandated by Facebook moving to Auth2.0 authorization.
需要对 JavaScript 代码进行一些更改,以根据用户喜欢或不喜欢 Facebook 迁移到 Auth2.0 授权所强制要求的页面来处理呈现。
Change is fairly simple:-
改变相当简单:-
sessions has to be replaced by authResponse and uid by userID
session 必须由 authResponse 替换,uid 由 userID 替换
Moreover given the requirement of the code and some issues faced by people(including me) in general with FB.login, use of FB.getLoginStatus is a better alternative. It saves query to FB in case user is logged in and has authenticated your app.
此外,考虑到代码的要求以及人们(包括我)在使用 FB.login 时面临的一些问题,使用 FB.getLoginStatus 是更好的选择。如果用户已登录并已验证您的应用程序,它会将查询保存到 FB。
Refer to Response and Sessions Object section for info on how this might save query to FB server. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
有关如何将查询保存到 FB 服务器的信息,请参阅响应和会话对象部分。http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
Issues with FB.login and its fixes using FB.getLoginStatus. http://forum.developers.facebook.net/viewtopic.php?id=70634
FB.login 的问题及其使用 FB.getLoginStatus 的修复。 http://forum.developers.facebook.net/viewtopic.php?id=70634
Here is the code posted above with changes which worked for me.
这是上面发布的代码,其中包含对我有用的更改。
$(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
}
});
});
回答by Sofia Khwaja
With Javascript SDK, you can change the code as below, this should be added after FB.init call.
使用 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();
}
回答by Modatheus
There is an article here that describes your problem
这里有一篇文章描述了您的问题
http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/
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>