Get and use Facebook offline_access tokens
Quentin Pleplé – 2011With the Facebook PHP SDK v3 (see on github), it is pretty simple to deal with offline_access access tokens. To log someone with the offline_access permission, you ask it when your generate the login URL. Here is how you do that.
Get the offline access token
First you check if the user is logged in or not :
require "facebook.php"; $facebook = new Facebook(array( 'appId' => YOUR_APP_ID, 'secret' => YOUR_APP_SECRET, )); $user = $facebook->getUser(); if ($user) { try { $user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { // The access token we have is not valid $user = null; } }
If he is not, you generate the « Login with Facebook » URL asking for the offline_access permission :
if (!$user) { $args = array('scope' => 'offline_access'); $loginUrl = $facebook->getLoginUrl($args); }
And then display the link in your template :
<?php if (!$user): ?> <a href="<?php echo $loginUrl ?>">Login with Facebook</a> <?php endif ?>
Then you can retrieve the offline access token and store it. To get it, call :
$facebook->getAccessToken()
Use the offline access token
To use the offline access token when the user is not logged in :
require "facebook.php"; $facebook = new Facebook(array( 'appId' => YOUR_APP_ID, 'secret' => YOUR_APP_SECRET, )); $facebook->setAccessToken("...");
And now you can make API calls for this user :
$user_profile = $facebook->api('/me');
I wrote this page after an answer I made on Stackoverflow.
Feel free to ask questions right here ↓