如何使用PHP续订/扩展facebook访问令牌


How to renew/extend facebook access tokens with PHP?

Facebook已经删除了offline_access令牌功能,现在每当用户访问您的网站时,都必须续订令牌以保持其活动状态。

假设有人已经允许您访问网站,并且您为他们存储了一个令牌。你会使用Facebook的PHP库中的哪些代码来续订该令牌?

您可以通过以下方式扩展您的令牌:

原始场景

  • 你的应用程序向用户请求权限
  • 您提示用户登录/授予权限
  • 您可以获得用户的代币(短期代币),并通过CURL或其他方式使用grant_type=fb_exchange_token兑换60天的代币
  • 您将令牌持久化

现在你有了这个代币,可以随心所欲地使用它长达60天。到,因为用户可以更改密码、取消应用程序的授权等,令牌将变为无效。您可以扩展令牌的方法是,每次用户访问您的页面时,您都可以检查他们是否通过javascript登录,如果是,则向您的服务器发出ajax调用,从今天起将现有令牌扩展60天。你可以打任意多个电话,只有第一个有效。我是这样做的:

  1. 在加载事件期间的某个页面上,添加以下内容:

     FB.getLoginStatus(function (response) {
         if (response.status === 'connected') {
            $.ajax({
                type: "POST",
                async: false,
                url: YOUR_URL,
                dataType: "text",
                data: {token  : response.authResponse.accessToken }
             });
         }
     });
             //rest of jquery ajax call here
    

这将为用户获得一个新的客户端访问令牌,并将其发送到服务器

  1. 然后,服务器可以获取该代币并将其兑换为60天一次的

    $token_url = "https://graph.facebook.com/oauth/access_token?client_id=".FACEBOOK_CLIENT_ID."&client_secret=".FACEBOOK_SECRET."&grant_type=fb_exchange_token&fb_exchange_token=".$token;
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($c, CURLOPT_URL, $token_url);
    $contents = curl_exec($c);
    $err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
    curl_close($c);
    $paramsfb = null;
    parse_str($contents, $paramsfb);        
    

参考:

https://developers.facebook.com/roadmap/offline-access-removal/

只有当用户在60天内返回您的网站时,才会延长代币。如果没有,您将需要再次提示权限。

更新

是的@zerkms是正确的,如果应用程序有权限,则不需要access_token。

With this permission, you can publish content to a user's feed at any time. However, please note that Facebook recommends a user-initiated sharing model. Please read the Platform Policies to ensure you understand how to properly use this permission. Note, you do not need to request the publish_stream permission in order to use the Feed Dialog, the Requests Dialog or the Send Dialog.

所有扩展权限都具有类似的权限:https://developers.facebook.com/docs/authentication/permissions/

以下是我目前正在做的

public function setExtendAccessToken($accessToken = NULL) {
enter code here
    if(!$accessToken) return;
    $graphUrl = 'https://graph.facebook.com/oauth/access_token?client_id='.$facebookAppId.
                '&client_secret='.$facebookSecret.
                '&grant_type=fb_exchange_token&fb_exchange_token='.$accessToken;
    $accessToken = @file_get_contents($graphUrl);
    parse_str($accessToken); //get the access_token param in the string and would be named $access_token
    if(!$access_token) $access_token = $accessToken; //if cannot be extended then just return the access token with 2 hours expiry
    return $access_token;
}
use Facebook'FacebookSession;
use Facebook'GraphSessionInfo;
use Facebook'FacebookRequest;
use Facebook'GraphUser;
use Facebook'FacebookRequestException;
use Facebook'FacebookRedirectLoginHelper;
    FacebookSession::setDefaultApplication('YOURAPPID', 'SECRET');
    $user_accessToken = $_COOKIE['access_token_facebook']
    $session = new FacebookSession($user_accessToken);
    try {
        $session->validate();
    } catch (FacebookRequestException $ex) {
        // When Facebook returns an error
        echo $ex->getMessage();
    } catch ('Exception $ex) {
        // When validation fails or other local issues
        echo $ex->getMessage();
    }
    if ($session) {
        // Exchange token for long token
        $longToken = $session->getExchangeToken();
        // ... your other stuff
    }

参考编号:https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokenshttps://developers.facebook.com/docs/facebook-login/access-tokens#extending