Facebook访问令牌

时间:2012-05-28 14:44:20

标签: php facebook

我试图让Facebook访问令牌使用以下代码: 我之前创建了自己的函数,但它返回时出现了同样的错误,我无法解决问题所在。

function getAccessToken(){
        $app_id = FB_APP_ID;
        $app_secret = FB_SECRET_ID;
        $my_url = FB_PAGE_URL;
        $code = $_REQUEST["code"];   


        if(empty($code)) {
       $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
       $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
         . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
         . $_SESSION['state'];

       echo("<script> top.location.href='" . $dialog_url . "'</script>");
     }      
    if($_REQUEST['state'] == $_SESSION['state']) {
       $token_url = "https://graph.facebook.com/oauth/access_token?"
         . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
         . "&client_secret=" . $app_secret . "&code=" . $code;

       $response = file_get_contents($token_url);
       $params = null;
       parse_str($response, $params);

       $graph_url = "https://graph.facebook.com/me?access_token=" 
         . $params['access_token'];

       $user = json_decode(file_get_contents($graph_url));
       echo("Hello " . $user->name);
     }
     else {
       echo("The state does not match. You may be a victim of CSRF.");
     }
}

取自Server-Side Authentication,但我一直收到此错误:

    Warning: file_get_contents(https://graph.facebook.com/oauth/access_token?
client_id=ID HERE&redirect_uri=URLHERE&cli
ent_secret=SECRECT&code=AQCI5rNgw9zCPHWGozeT59asg7_022u5tVc5XSef49BiX
IaF5_MAMqFwsqOAquUHgjOu_99ONwUV6IC7k-jV6DsWf9ni3jm8t59aHCBp1jrFaDthPbIKLNLQ-
fZgB5MLh1le5BAPKj_l57jhTLTBfOdxRU30mFCMYzMch8MYFpCmJ9GrjSSGwt0OKb_LNqMoRf8) [function.file-
get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

有人知道修复吗?

3 个答案:

答案 0 :(得分:0)

file_get_contents方法可能存在问题,因为您构建的网址看起来不错。

如果你搜索"facebook file_get_contents failed to open stream",你会得到很多关于这个问题的结果,这里有很多关于堆栈溢出的结果。
这个线程中的file_get_contents状态似乎是一个HTTPS问题:[function.file-get-contents]: failed to open stream

也许尝试一些其他方法发出http请求?也许卷曲?
只是为了测试一下,尝试使用你尝试使用php脚本的相同url从命令行使用curl,看看你得到了什么。

答案 1 :(得分:0)

查看请求回复,您尚未定义Facebook应用程序设置。

当您请求令牌时,您正在使用FB_APP_IDFB_SECRET_IDFB_PAGE_URL,但在回复中我可以看到这些定义为:“ID HERE”,“SECRECT”和“URLHERE”分别。

答案 2 :(得分:0)

我已设法使用PHP SDK修复此问题, 经过与SDK的长期斗争,让它做我想做的事。

我也用同样的想法打开了另一个问题,但又遇到了另一个问题。 这个问题现在已经解决了。

请查看此问题以获得此问题的答案:Facebook Access Token Server Side Authentication