简体   繁体   English

使用PHP-SDK的Facebook身份验证

[英]Facebook Authentication using PHP-SDK

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. 我已经尝试了好几天没有运气了,我设法使用了PHP-SDK附带的example.php,并且运行良好。 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 field in a database and then, restoring the data, unserializing it and using setSession function in the php-sdk to retrieve the authentication. 我尝试将会话存储在数据库的序列化字段中,然后还原数据,将其反序列化,然后在php-sdk中使用setSession函数检索身份验证。 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 Facebook OAuth基于存储的会话检索信息

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. 如果即使在用户退出应用程序后仍要使用该用户的访问令牌,则必须请求offline_access权限。

With the Facebook PHP SDK v3 ( see on github ), it is pretty simple. 使用Facebook PHP SDK v3( 请参阅github ),这非常简单。 To log someone with the offline_access permission, you ask it when your generate the login URL. 要记录具有offline_access权限的人,请在生成登录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 : 如果他不是,则生成“使用Facebook登录” URL,以请求offline_access权限:

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 : 现在,您可以为此用户进行API调用:

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

Hope that helps ! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM