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 in my Facebook PHP SDK 4.0 Tutorial. After that you need to direct the User to the authorization/login URL:

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:

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

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:

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:

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:

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 🙂

37 thoughts on “Facebook API – Access Tokens

  1. Mark says:

    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.

  2. solar poolheizung says:

    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. Ashish says:

    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.

    • 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. Kenny says:

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

  5. Joe says:

    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.

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

      • Joe says:

        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.

          • Joe says:

            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

            • 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”.

              • Joe says:

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

                • 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. Cherrie says:

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

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

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

  7. Ryan Archer says:

    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?

    • 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 says:

    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?

    • 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!

      • Antonio Reggiani says:

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

        Thank you Andreas!

  9. gaurav goyal says:

    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.

Leave a Reply

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