Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook PHP SDK - Graph returned an error: Invalid OAuth access token

Here is my code:

login.php:

<?PHP
require_once __DIR__ . '/Facebook/autoload.php';

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

$helper = $fb->getRedirectLoginHelper();
$permissions = ['email','public_profile']; // optional
$loginUrl = $helper->getLoginUrl('http://www.sportsector.bg/login-callback.php', $permissions);

echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';

Here is my login-callback.php:

<?PHP
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require_once __DIR__ . '/Facebook/autoload.php';
$fb = new Facebook\Facebook([
  'app_id' => '',
  'app_secret' => '',
  'default_graph_version' => 'v2.2',
  ]);


try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->get('/me?fields=id,name', '{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;
}

$user = $response->getGraphUser();

echo 'Name: ' . $user['name'];

When i click the Login with Facebook! link i get redirected to Facebook where i have to click continue. After that i get back on my website receiving the following error:

Graph returned an error: Invalid OAuth access token.

Can somebody tell me where is my mistake and how can i fix this?

like image 564
Venelin Avatar asked Nov 23 '15 09:11

Venelin


People also ask

How do I fix an invalid access token on Facebook?

Please click on Facebook Ads Extension, Manage Settings, go to Advanced options and click on Update token.

How can I check if my Facebook access token is valid?

You can simply request https://graph.facebook.com/me?access_token=xxxxxxxxxxxxxxxxx if you get an error, the token is invalid. If you get a JSON object with an id property then it is valid. Unfortunately this will only tell you if your token is valid, not if it came from your app.


1 Answers

You didn't retrieve the valid access token.

Change:

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


$helper = $fb->getRedirectLoginHelper();  

try {  
  $accessToken = $helper->getAccessToken();  
  $response = $fb->get('/me?fields=id,name', $accessToken );
  ....
} catch(Facebook\Exceptions\FacebookResponseException $e) { 
...

Have a look here

like image 177
Axel Amthor Avatar answered Oct 05 '22 03:10

Axel Amthor