Javascript 如何使用 Facebook 的 API 检查用户是否喜欢我的 Facebook 页面或 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5093398/
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
How to check if a user likes my Facebook Page or URL using Facebook's API
提问by Patrik
I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame
app.
我想我快疯了。我无法让它工作。
我只是想检查用户是否喜欢我在iFrame
应用程序中使用 javascript 的页面。
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!
这将返回: False
但我是我的页面的粉丝,所以它不应该返回 true 吗?!
采纳答案by Jason Siffring
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
我也把我的头发扯掉了。您的代码仅在用户授予了不理想的扩展权限时才有效。
In a nutshell, if you turn on the OAuth 2.0
for Canvas advanced option, Facebook will send a $_REQUEST['signed_request']
along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
简而言之,如果您打开“OAuth 2.0
画布”高级选项,Facebook 将$_REQUEST['signed_request']
随您的标签应用程序中请求的每个页面一起发送。如果您解析该 signed_request,您可以获得有关用户的一些信息,包括他们是否喜欢该页面。
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
回答by Tom Roggero
You can use (PHP)
你可以使用(PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
这将返回三个之一:
- string true string false json
- formatted response of error if token
- or page_id are not valid
- 字符串真字符串假json
- 错误的格式化响应,如果是令牌
- 或 page_id 无效
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
我想实现这一目标的唯一不使用令牌的方法是使用刚刚发布的签名请求 Jason Siffring。我的帮手使用 PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
回答by dinjas
You can do it in JavaScript like so (Building off of @dwarfy's response to a similar question):
您可以像这样在 JavaScript 中执行此操作(基于@dwarfy 对类似问题的回答):
<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>
Where the channel.html file on your server just contains the line:
服务器上的 channel.html 文件只包含以下行:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
那里有一些代码重复,但你明白了。这将在用户第一次访问页面时弹出一个登录对话框(这并不理想,但有效)。在随后的访问中,什么都不应该弹出。
回答by DrColossos
Though this post has been here for quite a while, the solutions are not pure JS. Though Jasonnoted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
虽然这篇文章已经有一段时间了,但解决方案并不是纯 JS。尽管Jason指出请求权限并不理想,但我认为这是一件好事,因为用户可以明确拒绝它。我仍然发布此代码,尽管(几乎)在ifaour 的另一篇文章中也可以看到相同的内容。认为这是 JS 唯一版本,没有过多关注细节。
The basic code is rather simple:
基本代码相当简单:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me
with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes
) As noted, you need more than the basic permission:
或者,替换me
为其他人的正确用户 ID(您可能需要更改以下权限才能执行此操作,例如friends_likes
) 如前所述,您需要的不仅仅是基本权限:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });
回答by Agent_x
i use jquery to send the data when the user press the like button.
当用户按下“赞”按钮时,我使用 jquery 发送数据。
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example: url: http://mywebsite.com/post/22/some-tittle
注意:您可以使用一些隐藏的输入文本来获取按钮的 id。在我的情况下,我从“var fbl_id=h_fbl[4];”中的 url 本身获取它 因为有 id 示例: url: http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file. in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.
所以我解析 url 以获取 id,然后将其插入到我的数据库中的 like.php 文件中。通过这种方式,您无需请求权限即可知道是否有人按下了赞按钮,但如果您想知道是谁按下了它,则需要权限。