Facebook API – Access Tokens

There are 3 different Access Tokens, each one with a specific purpose while dealing with the Facebook API. The Facebook docs cover the basics to get you started, it´s all about the Web here, so i will not cover the fourth one in the list: the “Client Token”.

App Access Token

This is the basic token, it´s for getting access to data “as App“. You will not get any user data with this one, but you can read the stream, the events and the albums of a Facebook page. You don´t even need to be admin of that page, but you can NOT get those channels without any Access Token.

The good thing is: In most cases you don´t even need to worry about the App Access Token (or any Token at all), if you are using one of the SDKs. If you include either the PHP SDK or the JavaScript SDK correctly, each call to the Facebook API will automatically include the App Access Token by default.

The docs mention two possibilities to get the App Access Token, one includes a call to the API and the second one is actually very easy to create:

APP-ID|APP-SECRET” (App-ID, Pipe, App-Secret)

Boom! That´s the App Access Token already. Just be sure not to share it with anyone, the App Secret should never be available to a user.

User Access Token

This is the most common Access Token, you only get it by authorizing the User. This is the one you need when you want to post stuff on the timeline of the User (please don´t create Spam Apps!), or if you want to get User information (Name, Facebook ID, Albums, Movies, …).

For testing, you can generate a User Access Token in the Graph API Explorer. Just select the App, press “Get Access Token” and the login dialog will show up. After authorizing, the User Access Token will be visible in the text field labeled “Access Token”:

Graph API Explorer - User Access TokenThe API Explorer will use the Token in the text field for every test call, next thing i´ll show you is to get a User Access Token with the PHP SDK and the JavaScript SDK.

PHP SDK

How to initialize the PHP SDK is explained very well in the “Usage” section of the readme.md file. After that you need to direct the User to the authorization/login URL:

$scope = array('manage_pages, read_stream');
$helper = new FacebookRedirectLoginHelper('https://www.mydomain.com/after_login.php');
$loginUrl = $helper->getLoginUrl($scope);
echo '<a href="' . $loginUrl . '">Login</a>';

Best practice is not to redirect the User immediately when he opens your App and did not authorize it yet. The User does not know what the App is about, so you better require authorization right when you REALLY need it, or you present an intro page to tell the User why you need his authorization.

After login, the User will get redirected back to your App URL (or another redirect URL you can specify), see the Facebook docs for further information: PHP SDK – getLoginUrlIf the User is authorized successfully, you can get his ID and make calls to the API easily. Don´t worry about the User Access Token, it will get added automatically:

try {
    $session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
    // When Facebook returns an error
} catch(\Exception $ex) {
    // When validation fails or other local issues
}
if ($session) {
    try {
        $user_profile = (new FacebookRequest(
            $session, 'GET', '/me'
        ))->execute()->getGraphObject(GraphUser::className());

        echo "Name: " . $user_profile->getName();
    } catch(FacebookRequestException $e) {
        echo "Exception occured, code: " . $e->getCode();
        echo " with message: " . $e->getMessage();
    }   
}

JavaScript SDK

This is the one i prefer in most cases, because you don´t need a redirection. Usability to the max. For initialization, just put the code from the Facebook docs in your HTML file: Facebook API – JavaScript SDK
Right at the comment “Additional initialization code…” you put in your login call (see FB.login in the Facebook docs):

FB.login(function(response) {
	if (response.authResponse) {
		FB.api('/me', function(response) {
			console.log('Hello ' + response.name);
		});
	} else {
		//login cancelled or not every permission accepted
	}
}, {scope: 'manage_pages, read_stream'}); //additional permissions

Of course you need to think asynchronous while using the JavaScript SDK. Always make sure that the SDK is initialized and the User is authorized before trying to make calls to the API. As i´ve already mentioned, you don´t need to worry about the User Access Token.

Extended User Access Token

By default, a User Access Token is valid for only 2 hours and you can extend it to 60 days. This is quite easy with the PHP SDK:

$facebookSession->getLongLivedSession();
echo $facebook->getToken();

Of course this will only work if you got a standard User Access Token already (see section above). Apart from calling the “setExtentedAccessToken” function, there´s nothing else you need to do. You may want to store the Access Token in a database if you need to call the API on behalf of the user while he is not online. Which is the only reason why you would even want to create an Extended Access Token.

Extending the Access Token requires the App Secret, so you should never try to do that client-side. But you can do it without the PHP SDK, by making a server-side call to this URL (with “file_get_contents” or – much better – with “cURL“: https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=[app-id]&client_secret=[app-secret]&fb_exchange_token=[short-lived-token]

Remember, user tokens are always limited to 60 days max – you can´t just request a new token with a cron job, you can only get a new Token with User interaction.

Page Access Token

The last important Access Token is used to manage Facebook Pages. It´s a bit more complicated to get that Token, these are the required steps:

  • get a valid User Access Token with the additional permission “manage_pages”
  • make a call to /PAGE-ID?fields=access_token with the Facebook API
  • get Page Access Tokens for all your Facebook Pages in an Array

I will only show you how it´s done with the PHP SDK, because there´s not much difference in using the JavaScript SDK for it:

$request = new FacebookRequest($session, 'GET', '/PAGE-ID?fields=access_token');
$response = $request->execute();
$result = $response->getGraphObject()->asArray();
$pageToken = $result['access_token'];
$facebookSession = new FacebookSession($pageToken);

From now on, each call to the API will use the Page Access Token. And that is exactly what you need if you want to write something on your Page wall as the Page itself.

Extended Page Access Token

The Page Access Token is valid for only 2 hours, like the default User Access Token. However, you can extended to a Token that is valid forever (and not just 60 days like the Extended User Access Token) by just using the code above for getting a Page Access Token with only one difference: you have to get a valid Extended User Access Token before calling /me/accounts:

$facebookSession->getLongLivedSession();
$request = new FacebookRequest($session, 'GET', '/PAGE-ID?fields=access_token');
...

Quite easy, right? If you just need one Extended Page Access Token without creating some code, use the Graph API Explorer:

  • Authorize with your App and copy the generated User Access Token (don´t forget the “manage_pages” permission)
  • Put that link with the correct IDs in the Browser: https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=[app-id]&client_secret=[app-secret]&fb_exchange_token=[short-lived-token]
  • Copy the acquired Extended User Token back to the Graph API Explorer
  • Make a call to /me/accounts

Result: A list of all your Pages, including an Extended Page Access Token for every Page.

Useful Links

Any questions/suggestions? Feel free to comment and i´ll try to answer :)

7 Responses to “Facebook API – Access Tokens”

  1. This post has been a great help for me. Thank you very much.

  2. Great article! It really helped me.

  3. You have not explained about access token with expire=never (long lived access token).

    I think you should.

    Hope my post
    http://stackoverflow.com/questions/14209658/long-lived-access-token-facebook-page/14212125#14212125

    could add a bit in you very good explanation about access token :)

  4. Thanks for this…!

    One question, I would like to gather reviews from a list of pages that are not owned by me.

    Does this mean that I have to request for a page access token from each page and does that mean that the admin of each page has to grant that access token?

    • hi! for reviews from other pages, you need a page access token. and that one you only get if you are admin of the page. so it is impossible to gather reviews/ratings from pages you do not own, unfortunately.

Trackbacks/Pingbacks

  1. Extended Page Access Tokens with CURL - 21. July 2014

    […] is a follow up to my article about Access Tokens for Facebook. It is quite easy to generate an Extended Page Access Token with the PHP SDK, but being a big fan […]