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”:

The 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 in my Facebook PHP SDK 4.0 Tutorial. 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
}
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:

$longLivedSession = $facebookSession->getLongLivedSession();
echo $longLivedSession->getToken();

Of course this will only work if you got a standard User Access Token already (see section above). Apart from calling the “setExtendedAccessToken” 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 🙂

63 thoughts on “Facebook API – Access Tokens”

  1. 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?

    1. 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.

      1. What will be the approach to get the reviews of different pages If I got the access toke token from other admin user?

  2. solar poolheizung

    Do you mind if I quote a few of your posts as long as I provide credit and sources back to your webpage?

    My website is in the very same niche as yours and my users would certainly
    benefit from some of the information you present here.
    Please let me know if this alright with you. Appreciate it!

  3. I i don’t say thank you that would be a sin 🙂

    Spent numerous hours on how to get Page values, facebook page data after authentication but couldn’t found any help.

    Thankfully i landed on this page and it was bang on.

    After authentication save the token, page token in db and make a separate call to this function to get Page specific data.

    function getFacebookData($pageName, $type)
    {
    $url = ‘https://www.facebook.com/’ . $pageName;
    $id = substr(strrchr($url, ‘/’), 1);
    $json = file_get_contents(‘http://graph.facebook.com/’ . $id);
    $json = json_decode($json);

    // if Type 1 return only id else return entire array
    return ($type == 1 ? $json->id : $json);
    }

    I hope this will help someone finding the same solution.

    1. which extended token? user token, i assume? you can´t auto retrieve a new one when it expires, it would make the whole concept of extending useless. user tokens are not supposed to get used if the user did not visit your app in more than 2 months.

  4. Thanks for clarifying my doubts about Facebook’s access tokens. Now that Facebook PHP SDK v5 is out, are these codes still valid?

  5. So to have your app read pages that are both public and restricted (location) I will require a page token & app token? The app token works sufficiently to get all public data but cannot access restricted pages based on location. In your opinion which would be better to use as default in my application. The benefit of app tokens are that I have never needed to renew them as it seemed it renew by itself. Is the amount of data retrieve via the graph api the same with all tokens?
    Thanks.

    1. you do need a page token for restricated pages, yes. app tokens are not related to a user, that´s why. extended page tokens are always better, and you do not need to renew them. as you can read in my article, they are valid forever. app tokens are just “app-id|app-secret”, there´s nothing to renew because those things will most likely stay the same in the app. but again: use a page token if possible.

      1. I want to create a web service or API that provides a user a login window where they will enter their credentials. I want to then create an app on their behalf in order to acquire user and page tokens on their behalf. This will then be used by my apps to allow them to interact with certain pages. Is this possible? If so do could you perhaps outline how I could go ahead and do this? I have just mentally scoped this out and do not yet have any idea how to code this, but just want to make sure its possible. Appreciate your response.

          1. Thanks for your valuable response. I am still a bit confused on which urls are used to acquire the page tokens:

            get long lived user token

            https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=&client_secret=&fb_exchange_token=

            get page token

            https://graph.facebook.com/me/accounts?access_token=

            found this on another site and not sure what it is used for.

            https://www.facebook.com/dialog/oauth?client_id=&redirect_uri=&scope=manage_pages%2Cpublish_stream&state=

            which url is used to request a page token from a specific restricted page or do I use the user token and make a normal feed request to that page using the ID?

            https://www.facebook.com/sourz.de/feed?limit=100&fields=id,message,from,to

            1. that link from another site is very old, publish_stream does not exist anymore. anyway, to get the page token for one single page: /page-id?fields=name,access_token – or for your example: graph.facebook.com/sourz.de?fields=name,acces_token – you need to use a user token with the manage_pages permission though, and it´s “graph”, not “www”.

              1. Thank you. Yes sorry that was a copy paste error. I tried what you suggested on the page access and was able to get the feed after getting the user token via the graph api explorer tool. Just so my understanding is correct; looking at the user token itself, if I do not include manage_pages, I am still getting the data feed. Is there a noticeable difference in the page and user tokens format? Is it possible to distinguish between the two? Also the long term token I received had a expires date, which is in this format &expires=5184000, is this supposed to be seconds? Finally, I promise to stop bothering you after this, I created a login button and tested using my own account and after logging in, the login window closes and I do not see the user token. Is there an explicit controller method I need to create?

                window.fbAsyncInit = function() {
                FB.init({
                appId : ‘xxxxxxxxxxxxxxxx’, // App ID
                channelUrl : ‘http://localhost’,
                status : true,
                cookie : true,
                xfbml : true,
                oauth : true
                })

                };

                function doLogin() {
                FB.login(function(response) {
                if (response.authResponse) {
                document.getElementById(‘loginBtn’).style.display = ‘none’;
                getUserData();
                }}, {scope: ’email,public_profile’, return_scopes: true});
                };

                1. some things are only possible with a page token. for example, reading the ratings of a page. i believe the expire number is a timestamp of a future date. in you code, debug the response of FB.login to see the user token.

  6. Hi,
    How to get all friend’s feed from facebook graph API…I wanna access an user home page feeds for my app. As “read_stream” permission is no longer working, i have “user_posts” permission approved. But still i am not able to access friend’s posts on my wall….Appreciate your response….

    1. you can´t get the whole feed anymore. you can only get posts of friends made on your wall. that´s all i can tell you, if you need more information you should post a detailed description of your problem on facebook, including your code.

    1. that is not possible. of course you need to login to get a page token, else facebook can´t know if the page belongs to you. and of course you can only get a page token of pages you own.

      1. That is kind of a stupid requirement, you would have expected the access token to be available from your page management screen. That’s how they would know if the page belongs to you.

        I’m trying to write some code that only interacts with a page, and I don’t see why I need to implement the user login just to get the token for a page.

  7. Hi Andreas,

    Thanks for your informative post! Much easier to read than Facebook docs. I want to use an App Access Token to pull images down from a Facebook page’s album.

    Main reason is that I don’t want to bother user to login to Facebook everytime they want to view the page (or when the user access token expires).

    Was looking to set it up server side using PHP firstly (and if having issues with that – use cURL). Is this the right token for the job? After setting it up and getting the “APP-ID|APP-SECRET” – can I just use the normal JavaScript SDK language to tell my HTML page to pull in the Facebook content via JS?

    1. hi! you should never do this client side, tokens should alway be kept secret and if you would use the app token…well, then you would allow every user to see the app secret. it´s called secret for a reason 😉 – a user could change app settings with it, for example. so php with curl is definitely the way to go, but you should cache the results in your own database too. don´t make the same call for every single user, or you will hit api limits sooner or later. for example, if a user hits the page, check the timestamp of the last api call in your database, if it´s too old then use the graph api to check for new entries.

  8. Antonio Reggiani

    Hi Andreas, thank you for this post.
    I’m using c# istead of php, but I can normally obtain same results.
    I have a strange behavior trying to post on page: if I use the access_token obtained from the request as you described (scope: “publish_actions, user_posts,manage_pages”) I have this error:

    (OAuthException – #200)
    (#200) The user hasn’t authorized the application to perform this action

    If I use Graph API explorer to create a page token and use manually that from my APP I can publish without any problems.
    I noticed, examining the token with the Access Token Debugger (https://developers.facebook.com/tools/debug/accesstoken/), that my token Never expires, the Graph API one instead has 60 minutes of life, and also Profile Page ID is the same, but the User ID (both with my name) is different.
    Of course I’m administrator of the page.
    Any idea?

    1. publish_actions is for posting as user only. if you want to post as page, you need publish_pages. maybe that is the problem? the user id is app scoped, it will be different per app. make sure you have a page token with publish_pages, you know when it is a page token if the page id shows up in the debugger. i hope that helps!

      1. Antonio Reggiani

        Fantastic, was exactly that! I supposed that “manage_pages” was the highest level… 🙂

        Thank you Andreas!

  9. hi andreas

    i am using facebook php sdk v5 and i want to get facebook user data after login to facebook from my site and save that data in .data file and i’m using the query like…

    $facebook->get(‘/me?fields=id,name,gender,likes.limit(5000),groups.limit(5000),friends.limit(5000).fields(gender), posts.limit(500)’, $access_token);

    but it gives many error please help in correct this query.

  10. Hi Andreas,

    I’m working with the Unity SDK and I’m having a really hard time posting to a page AS the page. I get “manage_pages” and “publish_pages” permissions, but when I try to post with

    “FB.API(“/Page-ID/photos”, HttpMethod.POST, HandleResult, wwwForm);”

    I get an error asking for “publish_actions” wich makes no sens. If I also get “publish_actions” the post goes online, but is posted to the page as the user/admin speaking.

    Any Ideas?

    1. you are most likely using a USER Token, not a PAGE Token. You get a Page Token by authorizing with manage_pages and publish_pages and then using /page-id?fields=access_token or /me/accounts?fields=access_token – if you want to get tokens for ALL your pages.

      1. Thank you for your reply. Sorry, I forgot to mention, that I already do/did this. With the Page Access Token I receive from /page-id?fields=access_token I can do exactly what I want, but it only works in the Graph Explorer. My problem is: when i get the Page Access Token in Unity via

        “FB.API(“/page-id?fields=access_token”, HttpMethod.GET, AccountCallback);”

        There is nothing I can do with it, since the SDK chooses wich Token is used and I cant change that Variable to the Token i know i need.

        So after I get the manage_pages and publish_pages with:

        var perms = new List () { “manage_pages”, “publish_pages” };
        FB.LogInWithPublishPermissions (perms, AuthCallback);

        If have the Perms, but the SDK still uses them with the wrong Token. Thats what I cant figure out.

      2. yes, I’m sure that’s the case. I have the page token, but I don’t know how to tell the SDK to use it.

  11. Hi Dear, thanks for your page.

    I can publish and read the token, but when I publish my link, it doesn’t seems in the feed and show for me as visitor.

    Do you know what is happening?

  12. Hi thank you for this post! I agree with other readers, it’s much better than Facebook’s own docs.

    I have another scenario: need to automatically upload a catalog feed to Facebook. I have a personal Facebook ID that the business has granted permission. Running the following didn’t work:

    curl -k https://graph.facebook.com/v2.10/xxxxxxxxxxxxxx/uploads -F ‘schedule={“data”: “@/tmp/catalog.xml”}’ -F ‘access_token=mmmmmmmmm|nnnnnnnnnnnnnnnnn’

    where “xxx” is my catalog object ID, mmm/nnnnnn is my ‘App token” from “Access token tool” after I logged in from http://developers.facebook.com

    I’m getting this error:
    {“error”:{“message”:”Unsupported post request. Object with ID ‘xxxxxxxxxxxxxx’ does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api”,”type”:”GraphMethodException”,”code”:100,”error_subcode”:33,”fbtrace_id”:”YYYYYYY”}}

    Would you kindly help me understand what could be the issue? Many thanks!

    1. the pipe sign in the token looks like you are using an app access token, it can´t work with that one. you definitely need a user or page token with the correct permissions (publish_actions or publish_pages).

  13. Hi I have a quick question.
    We are developing a platform/website where people can compare certain companies, for example gyms nearby.

    Now we would like to have the facebook rating displayed of all these companies but without having these companies grant us permission or having to log in.

    After reading a bit about it (I myself am not IT/tech person) I came to the conclusion that this is not possible, am I corrrect?

    Now I found a company that claims that it is possible, so I wanted to check with you since it’s clear you know what you’re talking about.

    Thx in advance!
    Nick

    1. hi! it is definitely not possible, you need a page token to get the ratings with the api, and you only get that one if you manage the page. may i ask what company claims that it is possible?

  14. Hello!

    I created the extended page access token when my account has the Page Admin role. What will happen to the token when my Page Admin role is removed?

  15. SDK 5.6.2

    Fatal error: Call to undefined method Facebook\Helpers\FacebookRedirectLoginHelper::getSessionFromRedirect() …

  16. Hi ! Great article, some question for you.

    I have un Login with Facebook button on my site. I got a user token, with that a fetch a list of manage pages and a page token. If I extend this token, this will be a never expire token ? If not, how I can got this never expire token ?

    Maybe my flow is not good…

    Thanks

    1. the last part of the article should answer your question – although, it might be that extended page tokens are not valid forever anymore, so you might have to get a new one every 60 days or so. just try it, and debug the token – see link to the facebook debugger in the article 🙂

  17. Hi Andreas,

    I did not find a way to retrieve page posts with an app token. Is it really always needed to use a page token (that is based on a specific user token) to retrieve the postings of pages that are managed by one company?

    Facebook says that an app key can be used instead of a user access key to make API calls (but maybe not for https://graph.facebook.com/v4.0/{page-id}/posts).
    https://developers.facebook.com/docs/facebook-login/access-tokens/#apptokens

    Thanks in advance for helping me 🙂

      1. Hi Andreas,

        thanks for the quick reply!
        For what we want to do, FB declined public page access (they are a lot stricter with this now) but they accepted our request for manage_pages permission for the app so I thought that with this permission the app could also load posts from the pages that are associated with the company account that owns the app. What we want to do is to load postings of FB pages that accepted us through business manager request. I can get postings from those sites with my user token and with our page token but when I use the app token I get the error that manage_pages is needed for the specific sites. Is it really wanted by facebook that our application “depends” on a user-related token (like the page token)? Since a user could just leave a company etc this seems a bit unreliable to me.

        1. hi! in general, you should always use a page token of the specific page you want to get data from. it is no problem if a user leaves a company and does not have access to the page anymore – in that case, the page token will be invalid. the only problem is that you cannot store the token and use it later. with an app token, there is no relation to any user. what if the user would not be allowed to see the page because of age/country restrictions?

          there are some limitations in the api that are important if you think of it from a security point of view, but i can understand that they may be annoying 😉

  18. access right are linked to account, so is there any reason to not create an account that haves right to access to this page? tomsoft Sep 30 ’14 at 9:47

Leave a Reply to solar poolheizung Cancel Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.