How to renew/extend facebook access tokens with PHP?

后端 未结 4 1886
失恋的感觉
失恋的感觉 2020-12-25 08:52

Facebook has removed the offline_access token functionality, now tokens have to be renewed whenever the user visits your website to keep them active.

Say someone has

相关标签:
4条回答
  • 2020-12-25 09:39

    You can extend your token the following way:

    Original scenario

    • Your app requests permissions from the user
    • You prompt user to log in / grant permissions
    • You get user's token (short-lived one) and exchange via CURL or other means for a 60 day one using grant_type=fb_exchange_token
    • You persist the token

    Now you have that token to do what you wish with it for up to 60 days. Up to, because user can change password, de-authorize app, etc and token would become invalid. What you can do to extend the token is EVERY TIME user comes to your page(s), you can check if they are logged in via javascript and if they are, make an ajax call to your server to extend existing token for 60 days from today. You can make as many calls as you want, only the first one is valid. Here's how I do it:

    1. On your page somewhere during load event, add something like:

       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
      

    That will get a new client-side access token for the user and send it to the server

    1. Server can then take that token and exchange it for a 60 day one

      $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);        
      

    Reference:

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

    That would only extend the token if the user comes back to your site within 60 days. If not, you will need to prompt for permissions again.

    0 讨论(0)
  • 2020-12-25 09:47

    Here's what im currently doing

    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;
    }
    
    0 讨论(0)
  • 2020-12-25 09:47
    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
        }
    

    Ref: https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens https://developers.facebook.com/docs/facebook-login/access-tokens#extending

    0 讨论(0)
  • 2020-12-25 09:55

    Updated

    Yes @zerkms is right, no access_token is needed if the application has permission.

    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.

    All extended permissions have similar privileges: https://developers.facebook.com/docs/authentication/permissions/

    0 讨论(0)
提交回复
热议问题