Facebook php-sdk-如何在网站上自动登录我的应用程序


Facebook php sdk - how to auto-login my app on website

我不想在我的网页上显示登录按钮,而是让它自动显示,这样如果有人访问我的网站,它会直接向他显示来自facebook的内容,而无需每次单击登录按钮。你能帮我吗?

我使用的是Facebook PHP SDK4 API。

以下是我的代码:

<?php
// Must pass session data for the library to work (only if not already included in your app)
session_start();
// Autoload the required files
require_once('phpsdk4/autoload.php');
use Facebook'FacebookSession;
use Facebook'FacebookRedirectLoginHelper;
use Facebook'FacebookRequest;
use Facebook'FacebookResponse;
use Facebook'FacebookSDKException;
use Facebook'FacebookRequestException;
use Facebook'FacebookAuthorizationException;
use Facebook'GraphObject;
use Facebook'GraphUser;
use Facebook'Entities'AccessToken;
use Facebook'HttpClients'FacebookCurl;
use Facebook'HttpClients'FacebookCurlHttpClient;
use Facebook'HttpClients'FacebookHttpable;
// Facebook app settings
$app_id = '123456';
$app_secret = 'appsecretpassword';
$redirect_uri = 'mywebpageaddress';
// Initialize the SDK
FacebookSession::setDefaultApplication( $app_id, $app_secret );
?>
<!DOCTYPE html>
<html lang="it">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<title>Facebook SDK test</title>
</head>
<body>
<?php
$helper = new FacebookRedirectLoginHelper($redirect_uri, $app_id, $app_secret);
try {
    $session = $helper->getSessionFromRedirect();
}
catch(FacebookRequestException $ex) { } 
catch('Exception $ex) { }
$loggedIn = false;
if (isset($session))
{
    if ($session) 
    {
        $loggedIn = true;
        try 
        {
            // Logged in
            $user_photos = (new FacebookRequest($session, 'GET', '/me/statuses'))->execute()->getGraphObject(GraphUser::className());
            $user_photos = $user_photos->asArray();
            echo "<pre>";
            print_r($user_photos);
            echo "</pre>";
        } 
        catch(FacebookRequestException $e) 
        { 
            echo "Exception occured, code: " . $e->getCode();
            echo " with message: " . $e->getMessage();  
        }           
    }
}
if (!$loggedIn)
{
  //$loginUrl = $helper->getLoginUrl();
  $loginUrl = $helper->getLoginUrl(array('user_status'));
  echo '<a href="' . $loginUrl . '">Login</a>';
}
?>
</body>
</html>

我建议使用JavaScript SDK的FB.getLoginStatus-这是检查返回用户是否已获得授权的最简单方法:https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus

它刷新用户令牌而不需要进行页面刷新——这将需要使用PHPSDKafaik来完成。

此外,FB.login更容易处理登录。只有当您需要在服务器上做一些事情,并且JavaScript SDK没有其他方法时,才可以使用PHP SDK。如果您使用JavaScript SDK btw.,您也不需要更新任何库

关于你网站上的订阅源:不要使用用户配置文件,扩展用户访问令牌的有效期只有60天,之后你必须手动刷新它。没有用户交互就无法做到这一点,所以使用PHP SDK还是JS SDK都无关紧要。最好创建一个Facebook页面,并使用扩展页面访问令牌读取该页面的状态(永远有效)。有关访问令牌的更多信息:

  • https://developers.facebook.com/docs/facebook-login/access-tokens/
  • http://www.devils-heaven.com/facebook-access-tokens/
  • http://www.devils-heaven.com/extended-page-access-tokens-curl/