Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to login with OFFLINE_ACCESS using the new Facebook PHP SDK 3.0.0?

with the old (2.x) SDK I used this to log someone with offline_access:

$session = array
(
    'uid' => $userdata['fb_uid'],
    'sig' => $userdata['fb_sig'],
    'access_token' => $userdata['fb_access_token']
);

$facebook->setSession($session);

In the new SDK this function doesnt exist anymore. I think I need to login using:

setPersistentData($key, $value)

but this function is protected and I dont know what 'code' is? Do I need this to log the user in or not? And what's going on with 'sig'? Don't I need this anymore?

Hope someone already figured this out because the documentation really doesn't help!

like image 842
martinyyyy Avatar asked May 25 '11 11:05

martinyyyy


1 Answers

With the Facebook PHP SDK v3 (see on github), it is pretty simple. 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['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');

Hope that helps !

like image 140
Quentin Avatar answered Sep 30 '22 10:09

Quentin