这个问题真的很令人沮丧,因为我可以看到导致它的原因但找不到解决方案。
尝试获取 facebook 访问令牌时,首先获取我的 url:
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$app_id."&redirect_uri=".urlencode($my_url)."&client_secret=".$app_secret."&code=".$code;
接下来我尝试url_decode
像这样使用和卷曲:
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$response = curl_exec($ch);
curl_close($ch);
使用 curl,响应为空(即使 returntransfer 设置为 true)。
所以接下来我尝试使用 file_get_contents,如下所示:
$response = file_get_contents($token_url);
echo $response;
然后这会产生一个错误,表明它没有正确解析 url。
Warning : file_get_contents(https://graph.facebook.com/oauth/access_token?client_id=XXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F&client_secret=XXXXXXXXXXXXXXXXXX&code=AQAw8Y3fehv2IWxhmQs9M28IsP4hAzwL5pnvSJkb2v_9H61Gpt659IgMHLgvgRH46tXl8BAL0SRyilKqVay4b4Su68nzT2OmbVK88eNHdGQqIaR_N7X8noIkQTeq_HuEImLlxQwbFcg_PJ5EGh9l392KL2OFqi8qplgOE5m21qlKOvVvUE3cZrcfk_mmr9FUm5eQXIvEp8sUYHxHAXvvyNmV [function.file-get-contents]: failed to open流:HTTP 请求失败!第65行C:\Users\Mark\workspace\Never\aqueous-sands-5942\index.php中的 HTTP/1.0 400 Bad Request
通过删除"amp;"
网址,您可以通过直接在浏览器中打开网址来查看正确的响应。
如何防止"amp;"
成为网址的一部分?我在任何地方都看不到任何多余的空格,并且我已经对我的网址进行了编码(http://localhost:8000/)
我究竟做错了什么?
更新:
更大的代码示例:
require 'sdk/src/facebook.php';
$app_id = "123456778";
$app_secret = "XXXXXXXXXXXXX";
$my_url = "http://localhost:8000/";
session_start();
@$code = $_REQUEST["code"];
if (!isset($_REQUEST["code"])) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . $my_url . "&state=" . $_SESSION['state'] . "&scope=email";
echo("<script>top.location.href='" . $dialog_url . "'</script>");
}
if( $_SESSION['state'] && ( $_SESSION['state'] === $_REQUEST['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;
echo "value of token:";
echo $token_url;
/* curl section (commenting out) */ /*
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$response = curl_exec($ch);
curl_close($ch); */
echo "command:";
echo $token_url;
echo "value:";
$response = file_get_contents($token_url);
echo $response;
$params = null;
parse_str($response, $params);