Follow this Blog!

Jun 25, 2017

f Comment

Facebook PHP SDK Error: Invalid $accessToken. Solve it in SECONDS!

Amazon Recently I upgraded my FB app to the latest version, version 2.9. I was using Javascript SDK to log people in and PHP SDK to handle my web app's business logic. I followed https://developers.facebook.com/docs/javascript/reference/FB.init/v2.9 to initialize FB as follows:
FB.init({
    appId            : '{your-app-id}',
    autoLogAppEvents : true,
    status           : true,
    xfbml            : true,
    version          : 'v2.9' // or v2.8, v2.7, v2.6, v2.5, v2.4, v2.3,
});
Then I followed https://developers.facebook.com/docs/php/howto/example_access_token_from_javascript to log into FB as follows:
# /js-login.php
$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.9',
]);

$helper = $fb->getJavaScriptHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (!isset($accessToken)) {
  echo 'No cookie set or no OAuth data could be obtained from cookie.';
  exit;
}
Everything is good, right? No. I kept getting invalid access token but there's nowhere to find errors. There's no log. What do I do to get a valid $accessToken that is set and can be used to log a Facebook user into my web app?

Solution #1

Make sure you include "cookie: true" in your FB.init's parameters. Why such important information isn't mentioned on https://developers.facebook.com/docs/javascript/reference/FB.init/v2.9 beats me. Your FB.init() parameters should look like the following:
FB.init({
    appId            : '{your-app-id}',
    autoLogAppEvents : true,
    status           : true,
    xfbml            : true,
    cookie           : true,
    version          : 'v2.9' // or v2.8, v2.7, v2.6, v2.5, v2.4, v2.3,
});
Try again.

Solution #2

Delete all cookies in the web browser for your web app and try again.

Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael