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']

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

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录