facebook 开发者博客上有一个更详细的示例,但它是在 php 中。我同意,尽管似乎缺少文档。
来源:https ://developers.facebook.com/blog/post/539/
以下 PHP 示例演示了如何访问 signed_request 参数、应用访问令牌并提示用户向您的应用授权 publish_actions 权限:
<?php
$app_id = 'YOUR_APP_ID';
$app_secret = 'YOUR_APP_SECRET';
$canvas_page_url = 'YOUR_CANVAS_PAGE_URL';
// Authenticate the user
session_start();
if (isset($_REQUEST["code"])) {
$code = $_REQUEST["code"];
}
if(empty($code) && !isset($_REQUEST['error'])) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = 'https://www.facebook.com/dialog/oauth?'
. 'client_id=' . $app_id
. '&redirect_uri=' . urlencode($canvas_page_url)
. '&state=' . $_SESSION['state']
. '&scope=publish_actions';
print('<script> top.location.href=\'' . $dialog_url . '\'</script>');
exit;
} else if(isset($_REQUEST['error'])) {
// The user did not authorize the app
print($_REQUEST['error_description']);
exit;
};
// Get the User ID
$signed_request = parse_signed_request($_POST['signed_request'],
$app_secret);
$uid = $signed_request['user_id'];
echo 'Welcome User: ' . $uid;
// Get an App Access Token
$token_url = 'https://graph.facebook.com/oauth/access_token?'
. 'client_id=' . $app_id
. '&client_secret=' . $app_secret
. '&grant_type=client_credentials';
$token_response = file_get_contents($token_url);
$params = null;
parse_str($token_response, $params);
$app_access_token = $params['access_token'];
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, '-_', '+/'));
}
?>
发布用户分数
https://graph.facebook.com/USER_ID/scores?
score=USER_SCORE&access_token=APP_ACCESS_TOKEN