So I'm fairly new to Facebook dev and PHP dev so please bare with.
I've created an iframe Facebook application. I have no trouble grabbing a signed request and using that information to do basic tasks on my page.
The real problem happens when I start navigating around my application within Facebook. I seem to lose my signed request information.
I have my PHP code included on every page and I still can't retain my signed request or session.... whatever its called.
I've pasted my basic PHP code below.
<?php
include_once "../lib/facebook.php";
$facebook = new Facebook(array(
"appId" => FACEBOOK_APP_ID,
"secret" => FACEBOOK_SECRET_KEY,
"cookie" => true,
"domain" => SERVER_DOMAIN
));
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, "-_", "+/"));
}
session_start();
if (isset($_开发者_StackOverflowSESSION['fb_data'])) {
$data = $_SESSION['fb_data'];
} else {
$data = parse_signed_request($_REQUEST["signed_request"], FACEBOOK_SECRET_KEY);
$_SESSION['fb_data'] = $data;
}
session_write_close();
$page_id = $data["page"]["id"];
$like_status = $data["page"]["liked"];
?>
The signed_request is only passed into your page when it is first loaded as a Facebook Canvas page. The signed_request is passed in as a POST variable. If you are navigating to different pages at the iframe level instead of the top level, you will lose that signed_request parameter.
For example, when user loads this page:
http://apps.facebook.com/test_app/
Facebook will load this inside its IFrame:
http://yourserver.com/test_app/
- while passing in signed_request as a POST variable.
If you then navigate to different pages using the following tag:
<a href="http://yourserver.com/test_app/page2"> Page 2 </a>
signed_request parameter will be lost.
Instead, you can either pass through the signed_request parameter as a GET variable:
<a href="http://yourserver.com/test_app/page2?signed_request=xxxxx"> Page 2 </a>
Or reload the page at top level:
<a target="_top" href="http://apps.facebook.com/test_app/page2"> Page 2 </a>
In case someone stumbles on this, the latest version of Facebook's php-sdk automatically uses $_SESSION variables to persist the signed_request when it isn't passed in on a Canvas page or Tab request. https://github.com/facebook/php-sdk
精彩评论