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:
1FB.init({
2    appId            : '{your-app-id}',
3    autoLogAppEvents : true,
4    status           : true,
5    xfbml            : true,
6    version          : 'v2.9' // or v2.8, v2.7, v2.6, v2.5, v2.4, v2.3,
7});
Then I followed https://developers.facebook.com/docs/php/howto/example_access_token_from_javascript to log into FB as follows:
01# /js-login.php
02$fb = new Facebook\Facebook([
03  'app_id' => '{app-id}',
04  'app_secret' => '{app-secret}',
05  'default_graph_version' => 'v2.9',
06]);
07 
08$helper = $fb->getJavaScriptHelper();
09 
10try {
11  $accessToken = $helper->getAccessToken();
12} catch(Facebook\Exceptions\FacebookResponseException $e) {
13  // When Graph returns an error
14  echo 'Graph returned an error: ' . $e->getMessage();
15  exit;
16} catch(Facebook\Exceptions\FacebookSDKException $e) {
17  // When validation fails or other local issues
18  echo 'Facebook SDK returned an error: ' . $e->getMessage();
19  exit;
20}
21 
22if (!isset($accessToken)) {
23  echo 'No cookie set or no OAuth data could be obtained from cookie.';
24  exit;
25}
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:
1FB.init({
2    appId            : '{your-app-id}',
3    autoLogAppEvents : true,
4    status           : true,
5    xfbml            : true,
6    cookie           : true,
7    version          : 'v2.9' // or v2.8, v2.7, v2.6, v2.5, v2.4, v2.3,
8});
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
ADVERTISING WITH US - Direct your advertising requests to Michael