javascript 检查用户是否已经喜欢粉丝专页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6830497/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:00:29  来源:igfitidea点击:

Check if user already likes fanpage

phpjavascriptfacebook

提问by Simon Thomsen

Is it possible to check if a user already likes my facebook fanpage from my website with Javascript or PHP?

是否可以使用 Javascript 或 PHP 检查用户是否已经喜欢我网站上的 Facebook 粉丝专页?

EDIT: I need a solution, so the user doesn't need to authenticate / allow some persmissions first

编辑:我需要一个解决方案,因此用户不需要先进行身份验证/允许某些权限

回答by Miguel Acu?a

<?php
require '../src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId' => 'APP_ID',
  'secret' => 'APP_SECRET',
));

$user = $facebook->getUser();
$page_id = "123456789";
$page_name = $facebook->api("/".$page_id)['name'];
$page_link = $facebook->api("/".$page_id)['link'];



if ($user) {
  try {
    $likes = $facebook->api("/me/likes/".$page_id);
    if( !empty($likes['data']) )
        echo "I like!";
    else
        echo "not a fan!";
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(array(
    'scope' => 'user_likes'
  ));
}

// rest of code here
?>

回答by Matěj G.

The simplest way would be to call the Graph APIto get the /me/likesconnections (note you have to require the user_likespermission). Then go through each and compare idwith the ID of your page.

最简单的方法是调用Graph API来获取/me/likes连接(注意你必须需要user_likes权限)。然后遍历每个并id与您的页面的 ID进行比较。

Assuming you're using the official Facebook PHP SDK, and have an instance of the Facebookobject set up (see Usagesection in the aforementioned page), the following code can be used to find out if the user is fan of Daft Punk:

假设您使用的是官方 Facebook PHP SDK,并Facebook设置了一个对象实例(请参阅上述页面中的用法部分),以下代码可用于确定用户是否是Daft Punk 的粉丝:

$our_page_id = '22476490672'; // This should be string
$user_is_fan = false;
$likes = $facebook->api( '/me/likes?fields=id' );
foreach( $likes['data'] as $page ) {
    if( $page['id'] === $our_page_id ) {
        $user_is_fan = true;
        break;
    }
}

Now, you can further work with the $user_is_fanvariable.

现在,您可以进一步使用该$user_is_fan变量。

In JavaScript, the code would be very similar. Using the official JavaScript SDK's method FB.api(again, assuming you have taken of the authentication):

在 JavaScript 中,代码将非常相似。使用官方JavaScript SDK的方法FB.api(再次假设您已进行身份验证):

FB.api('/me/likes?fields=id', function(response) {
    var our_page_id = '22476490672';
    var user_is_fan = false;
    var likes_count = response.data.length;
    for(i = 0; i < likes_count; i++) {
        if(response.data[i].id === our_page_id) {
            user_is_fan = true;
            break;
        }
    }
});

Note that here we're using an asynchronous request and callback, so the code using the user_is_fanvariable must be inside the function.

请注意,这里我们使用的是异步请求和回调,因此使用user_is_fan变量的代码必须在函数内部。

回答by Nadeem Khan

In case you are OK with user giving the permissions, for a PHP based website it can be done this way easily:

如果您同意用户授予权限,对于基于 PHP 的网站,可以通过以下方式轻松完成:

1- Create a new Facebook app here.

1-在此处创建一个新的 Facebook 应用程序。

2 - Download Facebook PHP SDK from here. Extract the files and place it in the same folder with the file in which you will paste the code given below!

2 - 从这里下载 Facebook PHP SDK 。提取文件并将其与您将粘贴下面给出的代码的文件放在同一文件夹中!

3 - Get your Facebook Page ID using this tool.

3 - 使用此工具获取您的 Facebook 页面 ID 。

4 - Generate Facebook like box code for your page from here.

4 - 从这里为您的页面生成 Facebook 喜欢框代码。

After 1, 2, 3 and 4 steps are complete, you can check if user has liked a page or not with the following code:

完成 1、2、3、4 步后,您可以使用以下代码检查用户是否喜欢某个页面:

<?php
    require('facebook.php');
    $config = array(
         'appId' => 'your facebook app id',
         'secret' => 'your facebook app secret code',

        'allowSignedRequest' => false
    );
    $facebook = new Facebook($config);
    $user_id = $facebook->getUser();
    if (isset($user_id)) {
        try {           
            $likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');             

            if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
            {
                echo 'Thank you for liking our fan page!';                   

            }
            else {
                echo 'You have not liked our fan page! Like it now:';
                ?>                   
                <iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fchillopedia&amp;width&amp;height=290&amp;colorscheme=light&amp;show_faces=true&amp;header=true&amp;stream=false&amp;show_border=true&amp;appId=1392604484339363" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:290px;" allowTransparency="true"></iframe> //replace this with your own Facebook like box code
                <?php
            }
        } catch (FacebookApiException $e) {
            $login_url = $facebook->getLoginUrl();
            echo '<a href="' . $login_url . '">Please click here to login into your Facebook account.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
        }
    } else {
        $login_url = $facebook->getLoginUrl();
        echo '<a href="' . $login_url . '">Please lick here to login into your Facebook account</a>';
    }
    ?>

The user will click on the "Please click here to login into your Facebook account." text which will redirect it to Facebook app permissions page, once user allows the permission to your app the code will fetch user's data and will display the likebox if user hasn't liked your fan page.

用户将单击“请单击此处登录您的 Facebook 帐户”。文本会将其重定向到 Facebook 应用程序权限页面,一旦用户允许您的应用程序的权限,代码将获取用户的数据,并在用户不喜欢您的粉丝页面时显示点赞框。

回答by Tarun

<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR_APP_ID_WITHIN_QUOTES', //Change this to your app id
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>



$signed_request = $_REQUEST["signed_request"];

list($encoded_sig, $payload) = explode('.', $signed_request, 2);

$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$has_liked = $data["page"]["liked"];

now check the $has_liked param to see if user likes ur page or not!

现在检查 $has_liked 参数,看看用户是否喜欢你的页面!

回答by Ethan Liu

seems like "/me/likes/[page_id]" doesn't always return the record even there is one. recently I request by "/me/likes/[page_id]", it will return 0, but if I request without page_id, but grab a bunch of record by "/me/likes/", and you will see the page_id is actually there, can't figure why.

似乎“/me/likes/[page_id]”即使有记录也不总是返回记录。最近我通过“/me/likes/[page_id]”请求,它会返回0,但是如果我请求没有page_id,但是通过“/me/likes/”抓取一堆记录,你会看到page_id实际上是在那里,想不通为什么。

when checking with graph.facebook.com/[page_id], only suspicious thing is its "can_post" is false, and others which "/me/likes/[page_id]" do works, is true.

在与 graph.facebook.com/[page_id] 核对时,唯一可疑的是它的“can_post”是假的,而其他“/me/likes/[page_id]”确实有效。

but looping is not good in this situation, especially some crazy people has millions of likes. is there any kinda privacy setting related to the page_id owner account would cause the problem?

但是这种情况下循环就不好说了,尤其是一些疯子有百万点赞。是否有任何与 page_id 所有者帐户相关的隐私设置会导致问题?