我通过javascript SDK检索访问令牌,并通过windows.location将其传递给服务器:
<script src='https://connect.facebook.net/en_US/all.js'></script>
<!-- Load javascript facebook connector -->
<script>
FB.init({
appId : '<?=$app_id;?>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
<script type="text/javascript">
function getToken(){
FB.login(function(response) {
if (response.authResponse) {
var access_token = response.authResponse.accessToken;
window.location="<?=$_SERVER['PHP_SELF'];?>?accessToken="+access_token;
} else {
return false;
}
}, {scope:'user_likes,friends_likes'});
}
</script>
PHP代码:
<?php
$app_id = 'MY_APP_ID';
$app_secret = 'MY_APP_SECRET';
$page_id= 'MY_PAGE_ID';
if(isset($_GET['accessToken'])){
// Run fql query
$fql_query_url = 'https://graph.facebook.com/'
. '/fql?q=SELECT+uid+FROM+page_fan+WHERE+page_id='.$page_id.'+AND+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1=me())&'.$_GET['accessToken'];
echo $fql_query_url;
$fql_query_result = file_get_contents($fql_query_url);
$fql_query_obj = json_decode($fql_query_result, true);
//display results of fql query
foreach($fql_query_obj as $v1){
foreach($v1 as $v2){
$x++;
}
}
echo "You have ".$x." friends who 'like' us";
}
当我回显$ fql_query_url并浏览浏览器中的url时,facebook graph api answers
{
"error": {
"message": "An access token is required to request this resource.",
"type": "OAuthException",
"code": 104
}
}
我做错了什么?我得到一个访问令牌,但似乎没有效果?
答案 0 :(得分:2)
您在实际请求中遗漏了access_token
,因为您只是将access_token
添加到网址而未实际命名该参数。在将access_token=
添加到网址之前添加$_GET['accessToken']
。
让您的源可读以发现此类事情真的很棒:
$query = <<<FQL
SELECT uid FROM page_fan WHERE page_id = {$page_id} AND uid IN (
SELECT uid2 FROM friend WHERE uid1 = me()
)
FQL;
$fql_query_url = 'https://graph.facebook.com/fql?q=' . rawurlencode($query);
$fql_query_url .= '&access_token=' . rawurlencode($_GET['accessToken']);
顺便说一下,通过GET参数传递access_token
是一个非常糟糕的方法,试着避免这种情况。