Asked  1 Year ago    Answers:  5   Viewed   11 times

I'm trying to use the PHP sdk v4.0 to get a long term access token for PAGE management.

I'm grabbing the access token from the user's login (Yes, I'm grabbing the Page-specific access token). Then sending it to the endpoint as specified in documentation, but I'm not getting any results and I'm not getting any errors.

Could I know what is the correct code snippet to use?

This is the code I'm using so far

$endpoint   =   '/oauth/access_token?';
$endpoint   .=  'grant_type=fb_exchange_token&';
$endpoint   .=  'client_id='.$this->app_id.'&';
$endpoint   .=  'client_secret='.$this->app_secret.'&';
$endpoint   .=  'fb_exchange_token='.$access_token;

try {

    $response = (new FacebookRequest(
        $this->session, 'GET', $endpoint
    ))->execute();

    // Do something with the response here but response is empty

} catch (FacebookRequestException $ex) {

    echo $ex->getMessage();

} catch (Exception $ex) {

    echo $ex->getMessage();

}

 Answers

3

There a several types of access tokens you can use with calls to Graph. Knowing which access token to use can be tricky.

User Access Token

If you want to make changes to the page and post on the page wall as the admin user, you'll need to use that user's access token.

Login

You'll need to ask that user to log in with the manage_pages permission if you're planning on performing admin-specific actions on the page.

$helper = new FacebookRedirectLoginHelper($redirect_url);
echo '<a href="' . $helper->getLoginUrl(['manage_pages']) . '">Login</a>';

Extending User Access Token

By default, you'll get a short-lived user access token from Facebook. I'm assuming you're using a database to store your access tokens. You'll need to exchange the short-lived user access token for a long-lived user access token and save the new token in the database.

$accessToken = $session->getAccessToken();
$longLivedAccessToken = $accessToken->extend();
echo (string) $longLivedAccessToken;

Using a code

If you're storing the long-lived user access token in the database, as a best practice, you should use the token to generate a code and then generate another long-lived access token. This way you're not using the same access token for all the requests on behalf of the user every time. This minimizes the chances of your app being flagged as spam.

use FacebookEntitiesAccessToken;

$longLivedAccessToken = new AccessToken('{long-lived-access-token}');
$code = AccessToken::getCodeFromAccessToken($longLivedAccessToken);
$newLongLivedAccessToken = AccessToken::getAccessTokenFromCode($code);

Page Access Tokens

If you want to post statues on the page and have the posts appear as if the page had posted the statuses you'll need to use a page access token.

Obtaining a page access token

Using a page admin's long-lived user access token, you can list the pages that that user administrates on the /me/accounts endpoint. You'll want to pull the access_token field which is the page access token. You can also pull the perms field to see which permissions the admin user has.

$request = new FacebookRequest($session, 'GET', '/me/accounts?fields=name,access_token,perms');
$pageList = $request->execute()->getGraphObject()->asArray();

Short-lived vs Long-lived page access tokens

If you use a short-lived user access token to obtain a page access token, the page access token will also be short-lived.

You could exchange the short-lived page access token with a long-lived page access token directly if you wanted to. This would give you a page access token that would last about 2 months.

$pageAccessToken = new AccessToken('{short-lived-page-access-token}');
$longLivedPageAccessToken = $pageAccessToken->extend();

However, if you use a long-lived user access token to obtain the page access token, the page access token will never expire.

Page access tokens "gotcha"

You can think of page access tokens as "sub access tokens" to the page admin user access token. This is an important concept because page access tokens are associated with the admin user you obtained the page access token from.

Since there are different page admin roles that a page admin can have, that will limit the scope of the page access token if the admin user isn't assigned the role that grants them a specific permission you need.

Saturday, May 29, 2021
 
matthy
 
5

From Facebook SDK:

  public function getAccessToken() {
    if ($this->accessToken !== null) {
      return $this->accessToken;
    }

    $this->setAccessToken($this->getApplicationAccessToken());
    $user_access_token = $this->getUserAccessToken();
    if ($user_access_token) {
      $this->setAccessToken($user_access_token);
    }

    return $this->accessToken;
  }

  protected function getApplicationAccessToken() {
    return $this->appId.'|'.$this->appSecret;
  }

Your access token will be APP ID|APP SECRET which is the application token, or A RANDOM TOKEN HERE, which is the user access token, when you have a user signed:

$facebook->getUser();

When getUser() return 0 (which is same as false, and user not signed) you need to request a login, and authorization (if have not authorized yet) for your application:

if (!$facebook->getUser())
{
    $login_url = $facebook->getLoginUrl(array(
            'scope' => 'publish_stream' // Permissions goes here
        ) 
    );
?>
    <script type="text/javascript">
        top.location.href = " <?php echo $login_url; ?>";
    </script>
<?php
    exit;
}

see available permissions types here: https://developers.facebook.com/docs/authentication/permissions/

Saturday, May 29, 2021
 
xrock
 
2

Why is this error happening?

Because you are URL-encoding the URL, before passing it to the getLoginUrl method.

The SDK takes care of that internally - so now you have a URL that has been URL-encoded twice, and that makes it unrecognizable as a valid, absolute URL.

So just pass the URL to that method without applying any extra encoding.


Edit: Additionally, the method getLoginUrl expects two parameters - first the redirect URI, and then the scope as the second one - not both as one array.

$loginUrl = $helper->getLoginUrl(
    $redirectURI,
    array('ads_management', 'read_insights')
);
Saturday, May 29, 2021
 
4

The tokens that you retrieve from the Graph Explorer are short duration User Access Tokens which are generated different for different applications and different permissions.

The Access tokens that you retrieve when navigating to /me/accounts end point are the Page Access tokens for various Pages you administer or are associated with. These access tokens do expire, but if retrieved from the /me/accounts end point using long lived access token these do not expire (documented here) and can impersonate things done by application as the Page itself.

You may further like to give the documentation about access token a read.

Saturday, May 29, 2021
 
5

@Julian. Thank you so much for the inspiration here. I was able to make this work without changing any of the core FB api files.

What happens is, the setExtendedAccessToken call sends the value to setPersistentData which then sends it into session via constructSessionVariableName.

So if we get it out of session, and then set it into the facebook object, we're all set.

Here is my code:

// ask for the extended token and get it from session ...
$facebook->setExtendedAccessToken();
$access_token = $_SESSION["fb_".FB_APP_ID."_access_token"];
// now set it into the facebook object ....
$facebook->setAccessToken($access_token);
// now our fb object will use the new token as usual ...
$accessToken = $facebook->getAccessToken();
Thursday, July 29, 2021
 
Octopus
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :