Ad

Facebook PHP SDK - Graph Error "Authorization Code Has Been Used" On Page Refresh

- 1 answer

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.

Ad

Answer

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

Ad
source: stackoverflow.com
Ad