(错误)试图获取非对象的属性(Facebook PHP SDK)

时间:2013-04-18 08:25:59

标签: php facebook properties oauth

我试图回应我的名字,但我收到一个错误:试图获得非对象的属性。请帮忙。虽然获取应用访问令牌没有问题,但我也无法获得用户访问令牌。

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
</head>
<body>
<?php 

require_once('facebook.php');
$config = array();
$config['appId'] = "MY_APP_ID";
$config['secret'] ="MY_APP_SECRET";
$facebook = new Facebook($config);

$app_id = "MY_APP_ID";
$app_secret = "MY_APP_SECRET";
$my_url = "http://localhost:8080/samplewebsite/index.php/";



$code = $_REQUEST['code'];

if(empty($code))
{
    $_SESSION['state'] = md5(uniqid(rand(),TRUE));
    $dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
               . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state']
               . "&scope=publish_actions,read_stream";
    header("Location: " . $dialog_url);
}
else 
{
    echo "Hello, your OAuth code is " . $code . "<br>";           
}

if ($_REQUEST['state'] == $_SESSION['state'])
{
    $facebook->api('oauth/access_token',array(
       'client_id' => $app_id,
       'client_secret' => $app_secret,
       'type' => 'client_cred',
       'code' => $code,
    ));

    $token = $facebook->getAccessToken();
    echo "<br>" . "Hello, Your access_token is: " .  $token;


    $graph_url = "https://graph.facebook.com/me?access_token=" . $token;
    //$user = json_decode(file_get_contents($graph_url));
    //echo $user->name;

    function curl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
        curl_setopt($ch, CURLOPT_URL, $url);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;

    }
    $user = json_decode(curl($graph_url));
    echo $user->name;
}




?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您正在尝试echo $user->name,但json_decode默认情况下不会返回对象。它返回一个关联数组,除非您将TRUE作为第二个参数传递。

所以,如果你改变:

$user = json_decode(curl($graph_url));

为:

$user = json_decode(curl($graph_url), TRUE);

它可能会按照您的意愿运作。如果没有,请尝试查看curl()调用返回的内容,然后查看$user实际包含的内容var_dump()