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

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度