且构网

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

无缝的方式来检查用户是否喜欢页面

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

当然可以!如文档所述,Facebook将向您发送一些额外的细节, signed_request

Of course you can! As mentioned in the documentation, Facebook will send you some extra details in the signed_request:


当用户浏览到Facebook
页面时,他们会看到您的页面选项卡
添加在下一个可用的选项卡
位置。一般来说,页面选项卡的
的加载方式与
Canvas页面完全相同。当用户选择
Page Tab时,您将收到
signed_request参数,其中一个
附加参数页面。这个
参数包含一个JSON对象,
一个id(当前
页面的页面ID),admin(如果用户是页面的admin
),并且喜欢(如果用户
喜欢的页面)。与Canvas
页面一样,在
用户授权您的应用程序之前,您将不会在signed_request中收到
应用程序的所有
用户信息。

When a user navigates to the Facebook Page, they will see your Page Tab added in the next available tab position. Broadly, a Page Tab is loaded in exactly the same way as a Canvas Page. When a user selects your Page Tab, you will received the signed_request parameter with one additional parameter, page. This parameter contains a JSON object with an id (the page id of the current page), admin (if the user is a admin of the page), and liked (if the user has liked the page). As with a Canvas Page, you will not receive all the user information accessible to your app in the signed_request until the user authorizes your app.

从我的 tutorial 应该是这样的:

<?php
if(empty($_REQUEST["signed_request"])) {
    // no signed request where found which means
    // 1- this page was not accessed through a Facebook page tab
    // 2- a redirection was made, so the request is lost
    echo "signed_request was not found!";
} else {
    $app_secret = "APP_SECRET";
    $data = parse_signed_request($_REQUEST["signed_request"], $app_secret);
    if (empty($data["page"]["liked"])) {
        echo "You are not a fan!";
    } else {
        echo "Welcome back fan!";
    }
}

function parse_signed_request($signed_request, $secret) {
    list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

    // decode the data
    $sig = base64_url_decode($encoded_sig);
    $data = json_decode(base64_url_decode($payload), true);

    if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
        error_log('Unknown algorithm. Expected HMAC-SHA256');
        return null;
    }

    // check sig
    $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
    if ($sig !== $expected_sig) {
        error_log('Bad Signed JSON signature!');
        return null;
    }

    return $data;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}
?>

更新的代码:以前的代码可以工作。我没有检查请求的有效性。这意味着有人可以篡改请求并向您发送虚假信息(如将 admin 设置为 true !的)。代码已经更新,遵循 signed_request 文档方法。

UPDATED CODE: While the previous code would work. I wasn't checking the validity of the request. This means someone could tamper the request and send you false information (like setting the admin to true!). Code has been updated, following the signed_request documentation approach.