How to extend access token validity since offline_access deprecation

Edit (August 14th 2012):
A week ago the official Facebook PHP SDK was updated. The function name was changed to setExtendedAccessToken, and it was decided we actually needed to destroy the session afterwards, to remove the risk of having two active sessions.
Also, the function no longer actually returns the token, but instead stores it within the persistant data. You can therefore get the new access token with the public function getAccessToken afterwards. Grab the new SDK from official Facebook PHP SDK github page to make sure you’re up to date.

Original Answer:

I have added a new public function to the base_facebook.php file, which returns an new access token which expires in 60 days. You can make a request to this function after you’ve received the normal access token. I’ve not tested, but I assume you also need to enable ‘deprecate offline_access” in your Advanced settings of the Developer App.

Just add this to your base_facebook.php inside the facebook class and make a call to it. It works for me.

 public function getExtendedAccessToken(){

    try {
        // need to circumvent json_decode by calling _oauthRequest
          // directly, since response isn't JSON format.
        $access_token_response =
            $this->_oauthRequest(
                $this->getUrl('graph', '/oauth/access_token'), array(
                    'client_id' => $this->getAppId(),
                    'client_secret' => $this->getAppSecret(),
                    'grant_type'=>'fb_exchange_token',
                    'fb_exchange_token'=>$this->getAccessToken()
                )
            );
    } catch (FacebookApiException $e) {
      // most likely that user very recently revoked authorization.
      // In any event, we don't have an access token, so say so.
      return false;
    }

    if (empty($access_token_response)) {
      return false;
    }

    $response_params = array();
    parse_str($access_token_response, $response_params);
    if (!isset($response_params['access_token'])) {
      return false;
    }

    return $response_params['access_token'];
}

Leave a Comment