使用PHP-SDK的Facebook身份验证 [英] Facebook Authentication using PHP-SDK

查看:200
本文介绍了使用PHP-SDK的Facebook身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了好几天没有运气了,我设法使用了PHP-SDK附带的example.php,并且运行良好.我只需要存储返回的会话并在以后使用它,这样我就可以访问而无需重新验证.

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.

我尝试将会话存储在数据库的序列化字段中,然后还原数据,将其反序列化,并使用php-sdk中的setSession函数检索身份验证.不幸的是,这没用,

I tried storing the sessions in a serialized field 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基于存储的会话检索信息

请指教?

推荐答案

更新:

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.

使用Facebook PHP SDK v3(请参阅github ),它非常简单.要记录具有offline_access权限的用户,请在生成登录URL时询问.这是您的操作方式.

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.

首先,您检查用户是否登录:

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;
  }
}

如果他不是,则生成使用Facebook登录" URL,要求获得offline_access权限:

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("...");

现在您可以为此用户进行API调用:

And now you can make API calls for this user :

$user_profile = $facebook->api('/me');

希望有帮助!

这篇关于使用PHP-SDK的Facebook身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆