【问题标题】:Facebook API integration error through phpFacebook API集成错误通过php
【发布时间】:2013-02-28 14:57:47
【问题描述】:
我最近通过一些试验和错误了解到,使用 JavaScript SDK 对 Facebook 图形 API 的请求有时会返回以下错误
{
"error":{
"message":"An active access token must be used to query information about the current user.",
"type":"OAuthException","code":2500
}
}
【问题讨论】:
标签:
php
facebook
facebook-graph-api
【解决方案1】:
快速但有点脏的解决方案是将您的 access_token 作为参数添加到每个请求中,而不是依赖 JavaScript SDK 为您完成:
//request to get profile information for the current user
FB.api("me", {
access_token: "<access-token-for-user>"
}, function(response){
//handle response here
});
更多细节
通常,您可以通过调用 FB.init 来启动客户端应用程序,并将用户的 access_token 作为参数。这是为了确保通过将您的 access_token 附加到对 Facebook 图表的 GET 请求,对任何 FB.api 请求进行身份验证。但是,在某些情况下,您的令牌可能会突然从应用程序会话中消失,并且由于对 Facebook 图表的 GET 请求中不存在令牌,因此对图表的所有请求都会失败。
一个可重现的场景是发送一个 FB.api 请求来评论已删除的 facebook 帖子。这样做会返回 OAuth Exception 错误并错误地从当前会话中删除令牌。
By adding the token manually to all of your FB.api requests, you can ensure the token is always included.
【解决方案2】:
请检查此代码,访问令牌在此处通过 url 发送:
<?php
$facebook_appid = "facebook_appid"; // Facebook appplication id
$facebook_secret = "facebook_secret"; // Facebook secret id
$facebook_pageid = "facebook_pageid"; // Facebook secret id
$redirect_uri = "https://localhost/facebook_page/events.php"; // return url to our application after facebook login ## should be SAME as in facebook application
//$redirect_uri = "https://localhost/facebook_page/fb_login.php"; // return url to our application after facebook login ## should be SAME as in facebook application
$scope = "user_photos,email,user_birthday,user_online_presence,offline_access,manage_pages,publish_stream,user_events,friends_events"; // User permission for facebook
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = time(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = @file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$account_url = "https://graph.facebook.com/".$facebook_pageid."?fields=access_token&access_token=".$params['access_token'];
$resp = @file_get_contents($account_url);
$dt = json_decode($resp);
echo $dt->access_token;
echo "<br>";
echo $dt->id;
$offer_url = "https://graph.facebook.com/".$dt->id."/feed?access_token=".$dt->access_token;
$off = @file_get_contents($offer_url);
$dto = json_decode($off);
echo "<pre>";
print_r($dto);
}
?>