App_access_token始终返回False

时间:2013-02-07 10:47:27

标签: php facebook facebook-graph-api facebook-php-sdk facebook-access-token

根据Facebook docs,使用App_access_token非常简单:

$appid = 'xxx';
$secret = 'yyyyyyyyy';
$facebook = new Facebook(array(
  'appId'  => $appid,
  'secret' => $secret,
  'cookie' => true,
));

$session = $facebook->getUser()>0;
if($session){
  $access_token = 'access_token='.$facebook->getAccessToken();
  $app_access_token = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=$appid&client_secret=$secret&grant_type=client_credentials");
}

我的问题是$access_token很好但是 $app_access_token 总是返回错误,我做错了什么?

- 编辑 -

如果我在浏览器中打开app_access_token网址,我可以看到访问令牌!似乎没有使用file_get_contents ......?

2 个答案:

答案 0 :(得分:1)

我的file_get_contents不能正常运行试试这个:

allow_url_fopen启用php ini设置,然后重新启动服务器。

以下是工作代码:

<?php

$facebook_appid         = "facebook_appid";                                 // Facebook appplication id
$facebook_secret        = "facebook_secret";                // Facebook secret id
$redirect_uri           = "https://192.168.75.44/facebook_login/fb_login.php";   // return url to our application after facebook login ## should be SAME as in facebook application
//$cancel_url             = "";                                             // redirect url if user denies the facebook login ## should be SAME as in facebook application
$scope                  = "user_photos,email,user_birthday,user_online_presence,offline_access"; // 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);

    echo $params['access_token'];
}

?>

答案 1 :(得分:1)

file_get_contents可能会产生问题,可能是由于某些php配置设置。 (在此讨论:file_get_contents returns empty string

我建议您使用cURL,类似的东西 -

function get_content($URL){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $URL);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
  }


echo get_content('http://example.com');

如果问题仍然存在,请重新检查网址中app_idsecret的值。