dongxing7530 2015-12-16 00:04
浏览 65
已采纳

Facebook PHP SDK - 图形错误“页面刷新时已使用授权代码”

I have a profile page for a site that uses facebook login. The login works fine when the page first loads, and everything seems okay. However when the profile page is refreshed, I am getting an error: "Graph returned an error: This authorization code has been used." From doing some research I understand this is probably because I need to use the current session? I searched Facebook for Developers and couldn't figure out how to do this. I also researched some other pages on here that had a similar error message but none seemed to cover when the page is refreshed. I am using the Javascript SDK for the login process, and the PHP SDK for graph requests and anything after login. The code I am using, along with the sql queries is here:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set("display_errors", 1);
// error reporting is now turned on


require('facebook-sdk-v5/autoload.php');

$fb = new Facebook\Facebook([
    'app_id' => 'app-id-here',
    'app_secret' => 'app-secret-here',
    'default_graph_version' => 'v2.2',
]);

# fb-login-callback
$jsHelper = $fb->getJavaScriptHelper();
// @TODO This is going away soon
$facebookClient = $fb->getClient();

try {
    $accessToken = $jsHelper->getAccessToken($facebookClient);

} catch(Facebook\Exceptions\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage(); /*****This is where the error is caught*****/
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
}

if (isset($accessToken)) {

    try {
        // Returns a `Facebook\FacebookResponse` object
        $_SESSION['facebook_access_token'] = (string) $accessToken;
        $response = $fb->get('/me?fields=id,name,email,gender,hometown', $_SESSION['facebook_access_token']);
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }

    //Check the database for the user
    //First connect
    require_once 'config.php';

    try {
        $mysqli= new mysqli($host, $username, $password, $dbname); 
        if ($mysqli->connect_error) {
            die('Connect Error (' . $mysqli->connect_errno . ') '
                . $mysqli->connect_error);
         }
     }
     catch (mysqli_sql_exception $e) { 
         throw $e; 
     } 
     $stmt = $mysqli->prepare( "SELECT COUNT(*) FROM users WHERE fbuid = ?");

     $stmt->bind_param("i", $id);

     //Returns a `Facebook\GraphNodes\GraphUser` collection
     $user = $response->getGraphUser();
     $id = $user['id'];

     $stmt->execute();
     $stmt->store_result();
     $stmt->bind_result($count);
     $stmt->fetch();

     //If this is a new user, insert into the users table
     if($count === 0) {
        $stmt->free_result();
        $stmt = $mysqli->prepare("INSERT INTO users (fbuid, name, email, location, profpic, gender, joined)
                                  VALUES ( ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("issssss", $id, $newName, $newEmail, $newLoc, $newPic, $newGender, $joinDate);

        //Get the date for the joinDate
        $date=getdate(date("U"));

        //Get the required information from the Graph API
        $locationObj = $user['hometown'];
        $joinDate = "$date[month] $date[mday], $date[year]";
        $newName = $user['name'];
        $newEmail = $user['email'];
        $newLoc = $locationObj['name'];
        $newPic = "http://graph.facebook.com/" . $id . "/picture?type=large";
        $newGender = $user['gender'];

        $stmt->execute();

     }
     //Retrieve their info from the users table
     $stmt->free_result();
     $stmt = $mysqli->prepare("SELECT name, email, location, profpic, gender, joined, about FROM users WHERE fbuid = ?");
     $stmt->bind_param("i", $id);
     $stmt->execute();
     $stmt->store_result();
     $stmt->bind_result($name, $email, $location, $profpic, $gender, $joined, $about);
     $stmt->fetch();

} 
else {
    // Unable to read JavaScript SDK cookie
}
?>

My question is, how can I change the code I have provided in order to prevent this error. If it has to do with using the current session, how to I go about checking and using this. Thank you.

  • 写回答

1条回答 默认 最新

  • douyong6585 2015-12-17 06:29
    关注

    Use session_start(); at the beginning of the PHP script and then Check if(!isset($_SESSION['fbuid'])) and if true(not set), then make a call to the API graph, and after the first call to the graph, set the $_SESSION['fbuid'] to the facebook user id retrieved from the call, and also insert all the user information into the users table in MySQL. Then on page refresh, it recognizes the session variable being set, skips the API call and just takes the information from the database for the user with facebook UID matching $_SESSION['fbuid']

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1