且构网

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

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

更新时间:2023-12-01 19:04:58

最简单的方法是调用图形API 获取 / me / likes 连接(注意你必须要求 user_likes 权限。然后浏览每个并将 id 与您的页面ID进行比较。

The simplest way would be to call the Graph API to get the /me/likes connections (note you have to require the user_likes permission). Then go through each and compare id with the ID of your page.

假设您正在使用官方Facebook PHP SDK ,并拥有 Facebook的实例对象设置(参见上述页面中的 Usage 部分),以下代码可用于查明用户是否是 Daft Punk 的粉丝:

Assuming you're using the official Facebook PHP SDK, and have an instance of the Facebook object set up (see Usage section in the aforementioned page), the following code can be used to find out if the user is fan of 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;
    }
}

现在,您可以继续使用 $ user_is_fan 变量。

Now, you can further work with the $user_is_fan variable.

在JavaScript中,代码非常相似。使用官方 JavaScript SDK 的方法 FB.api (再次,假设你已经拍摄了身份验证):

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

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

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

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