老话题,但想参与进来,因为我最近学到了很多关于如何做到这一点的知识,并且不得不将其付诸实践。
查看此链接:http://nickring.com/blog/2012/11/facebook-fan-gate-using-php/。它使用 signed_request 变量,正如其他一些响应所示,但它显示了它如何不需要通过 $_REQUEST 请求 signed_request 变量。
要记住的一件主要事情是,signed_request 仅在访问 signed_request 的 PHP 脚本在 Facebook 中运行时可用。 如果您在 Facebook 之外的脚本中运行此脚本,试图使用 Facebook API,它将返回一个空数组。
这是一个示例 - 当您转到此地址时,将运行以下脚本:https://www.facebook.com/yourFacebookPage/app_xxxxxxxxxxxxxxx,其中 'xxxxxxxxxxxxxxx' 是应用 ID。
// Check if the user has liked us on Facebook, require the Facebook SDK
require_once('linked/facebook/facebook.php');
// Setup the Config
$config = array(
'appId' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy',
'cookie' => true
);
// Create a Facebook SDK instance
$facebook = new Facebook($config);
// Get the signed_request variable that we so desparately need
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
// Make sure that it worked
if (!empty($signed_request))
{
// Get the signed_request information
if ($like_status == 1)
{
// Wo0t! Show the FB fan only page stuff here
}
else
{
// Show the 'Please like us page'
$page = file_get_contents('pages/facebookLikeUs.html');
// Finish the page
echo $page;
exit();
} // End if ($like_status == 1) ELSE Clause and IF
} // End if (!empty($signed_request)) IF Clause
else
{
// Damn, it didn't work. Show an error
}
上述脚本是从应用设置的“Facebook 上的应用”部分的画布 URL 中设置的 URL 调用的脚本。 facebookLikeUs.html 页面只是一个页面,要求他们单击“喜欢”以继续。如果我希望将它们重定向回需要 Facebook 的网站,我只需将 // Wo0t! 部分替换为以下内容:
// Wo0t! They're all set, establish some cookies, get a cookie, and redirect back to the PHD program site
setcookie('fbls', $signed_request['page']['id'] . '-' . $signed_request['user_id'], time() + 300);
$redirectURL = "http://www.myurl.com/theScriptIWantToReceiveTheUserFromFB.php";
// Since Facebook really wants to keep us in the page, we need to create a page that will automatically break out of FB
$page = file_get_contents('pages/facebookRedirectBack.html');
// Replace some stuff
$page = str_replace('$redirectURL', $redirectURL, $page);
// Output the page
echo $page;
exit();
facebookRedirectBack.html 页面是这样的:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
window.top.location.href = '$redirectURL';
</script>
</body>
</html>
如果您希望对此有更高的安全性,您可以让重定向 PHP 脚本编写一些 cookie 并将它们附加到 URL,以便接收脚本必须比较 cookie 和 URL 参数,然后删除 cookie读完之后。
希望这会有所帮助,因为我个人还没有找到关于这个主题的任何一致信息。