Sunday, March 6, 2022

[FIXED] Get Access Token from Facebook PHP SDK is not working properly

Issue

I'm trying to retrieve an Access Token from Facebook using PHP SDK 3.2.2, being the code below what I placed in the redirect url after a sucessfull user login in Facebook. My problem is that $this->facebook->getAccessToken() is not giving back the user access token after the user gives access to the APP, just a string with the form: 'AppId|AppSecret', and I have to include code to manually get the User Access Token. This work, but I don't know WHY when I use getAccessToken is not giving back the right Token. I would also like to know how if there is any better way to retrieve User Access Token than with $code, because I don't feel this is a good way of doing it.

NOTE: I use $this->facebook because I load it as a Codeigniter library.

  $access_token  = $this->facebook->getAccessToken();

  //-------------------------------------------------------------------------
  //echo '<br/>Access Token: ' . $access_token;
  // Generare Token if not created:
  $code = $_REQUEST["code"];

  if ( isset($code) ) {
     //echo '<br/>Code Enviado: ' . $code;
     //exit();
     $appId     = $this->facebook->getAppId();
     $appSecret = $this->facebook->getAppSecret();

     $redirectTo = base_url('asociar/acc_facebook/step2/');

     $token_url="https://graph.facebook.com/oauth/access_token?client_id="
        . $appId . "&redirect_uri=" . urlencode($redirectTo)
        . "&client_secret=" . $appSecret
        . "&code=" . $code . "&display=popup";
     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     $access_token = $params['access_token'];

     //echo '<br/>Repitiendo el Token';

     $this->facebook->setAccessToken($access_token);
     //echo '<br/>Second Access Token Fijado: ' . $access_token;
  }
  //-----------------------------------------------------------------------

UPDATE:

This issue is due to I used CI with PHP SDK (check my own answer for that), but the answer is valid to anyone that have this issue with Facebook PHP SDK (Check @Imbru answer)


Solution

The response is little late, but may be it will help for other users.

I have got the same issue today.

My access_token was not correctly store in $_SESSION. Apparently, client side send juste one time the access_token. You have to store it in memory (SESSION) and reused it.

In normal time, Facebook PHP SDK do it...

EDIT : See @Chococroc response for more explanations



Answered By - Kevin ABRIOUX

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.