I've been trying for couple days now without luck, I managed to use the example.php that comes with PHP-SDK and worked perfectly. I just need to store the returned session and use it later on so I could access without re-authenticating.
I tried storing the sessions in a serialized fi开发者_Python百科eld in a database and then, restoring the data, unserializing it and using setSession function in the php-sdk to retrieve the authentication. Unfortunately, that did not work,
Here is a link to a previous question with the code samples..
Facebook OAuth retrieve information based on stored session
Please advice?
Update: Offline Access in now deprecated. Use something else instead.
If you want to use the access token of the user even after he has logged out of your app, you have to ask for the offline_access
permission.
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) {
$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 :
if ($user) {
$token = $facebook->getAccessToken();
// store token
}
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 !
精彩评论