【问题标题】:Why can't file_get_contents() exchange code for token with Facebook oauth.为什么 file_get_contents() 不能与 Facebook oauth 交换令牌代码。
【发布时间】:2012-12-20 20:18:18
【问题描述】:

我无法使用以下代码交换代码为令牌:

extract($_GET);
$url=urlencode('http://'.DOMAIN.'/admin/');
$app_id=FB_APPID;
$fb_token=FB_TOKEN;
$secret=FB_SECRET;

if(SEND_NEWS_TO_FB){
    if($code=='none'){
            $state=rand(100000000,9999999999999999999);
            $_SESSION['state']=$state;
            $script="
            <script type='text/javascript'>
                    var scope=encodeURI('publish_stream,user_status');
                    var app_id=$app_id;
                    var state=$state;
                    var url=$js_url;
                    window.location.href='https://www.facebook.com/dialog/oauth?                                                                                            client_id='+app_id+'&redirect_uri='+url+'&scope='+scope+'&state='+state;

            </script>";
            echo $script;
    }



if($code!='none' && $_SESSION['state']==$state && $_SESSION['fb_token']!=1){
            $_SESSION['fb_token']=1;
            $token_url="https://graph.facebook.com/oauth/access_token?"
            ."client_id=" .$app_id
            ."&redirect_uri=" .$url
            ."&client_secret=" .$secret
            ."&code=" .$code;
            $response = file_get_contents($token_url);
            $params = null;
            parse_str($response, $params);
            $token=$params['access_token'];
            $qry="UPDATE `settings` SET `FB_token`='$token'";
            $result=mysql_query($qry);
        }

将返回的 $token_url 放置在我的浏览器中会给我一个带有令牌和过期时间的页面。运行脚本会返回一条非常模糊的“抱歉,出现问题”消息。我看到的几乎所有有问题的线程都是由于重定向 uri 的差异造成的,但是登录和令牌请求都从完全相同的位置获取 uri。

【问题讨论】:

  • 我注意到您缺少 scopegrant_type 参数。也许尝试添加这些,看看它是否有效? (获取访问令牌时grant_type必须是authorization_code
  • 登录部分的格式有点混乱 client_id='+app_id+'&amp;redirect_uri='+url+'&amp;scope='+scope+'&amp;state='+state; 在登录 URL 中被推到右侧。所以我确实使用了scope。你的意思是代码/令牌交换也应该传递范围吗?你在哪里找到服务器端流程中grant_type 的文档?除了 (developers.facebook.com/docs/howtos/login/server-side-login) 之外,我无法找到有关服务器端 oauth 进程的任何文档。

标签: facebook oauth file-get-contents


【解决方案1】:

app_id 值和“&redirect_url”之间有一个空格。仅供参考,您的浏览器(至少 chromium)会自动对空格进行 urlencode,这就是 url 在浏览器中可以正常工作的原因。我仍然不确定空间是如何存在的,但 urlencode() 暂时修复了它。

【讨论】:

    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 2011-08-05
    • 2023-03-11
    • 2012-11-28
    • 2014-05-12
    • 2013-08-17
    相关资源
    最近更新 更多