Facebook PHP SDK dealing with Access Tokens

烈酒焚心 提交于 2019-12-04 07:58:59

Let's go through your questions:

Do I need to store the access token anywhere?

This depends on your application. First of all ask yourself, do you need to perform actions on behalf of the user while he is not present (not logged in to your app)?
If the answer is yes, then you need to extend the user token which can be done using the PHP-SDK by calling this method while you have a valid user session: setExtendedAccessToken().

Also you should refer to this document: Extending Access Tokens

What happens when the access token expires or becomes invalid? ... Is there a way I should be handling them to check if they have expired?

This is where the catch clause in your code comes in handy, while facebook example only logs the error (error_log($e);) you should be handling it!

Facebook already has a tutorial about this: How-To: Handle expired access tokens.

Also you should refer to the Errors table and adjust your code accordingly.

Is there anything else I should be doing to handle tokens?

See above.

Should I be passing the access token between pages or is it ok to just call it again at the top of each page

You shouldn't need to do any of that, because the PHP-SDK will handle the token for you; have you noticed that you are calling: $user_profile = $facebook->api('/me'); without appending the user access_token?

The SDK is adding it from its end so you don't have to worry about it.

I just had the same issue, but i solve it with some of your help. I'm using the php-sdk to connect to the Facebook API, so i just made this.

$facebook = new Facebook(array(
          'appId'  => 'API_ID', 
          'secret' => 'SECRET',
        ));

// Get User
$user = $facebook->getUser();

// Verifing if user is logged in.
if ($user) {
    try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
    }
}

// Verify if user is logged in, if it is... Save the new token.
if($user){

   // Request the access_token to the 
   $access_token = $facebook->getAccessToken()

   // Saving the new token at DB.
   $data = array('access_token' => $access_token);
   $this->db->where('userid',$user);            
   $this->db->update('facebook', $data);

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!