205
votes

I work on a project that has facebook pages as one of its data sources. It imports some data from it periodically with no GUI involved. Then we use a web app to show the data we already have.

Not all the information is public. This means I have to get access to the data once and then keep it. However, I don't know the process and I haven't found a good tutorial on that yet. I guess I need an access_token, how can I get it from the user, step by step? The user is an admin of a facebook page, will he have to add some FB app of ours to the page?

EDIT: Thanks @phwd for the tip. I made a tutorial how to get a permanent page access token, even with offline_access no longer existing.

EDIT: I just found out it's answered here: Long-lasting FB access-token for server to pull FB page info

18
It sure seems so. I have better title, he has more detailed question and we both have roughly the same answer accepted.Vlasec

18 Answers

662
votes

Following the instructions laid out in Facebook's extending page tokens documentation I was able to get a page access token that does not expire.

I suggest using the Graph API Explorer for all of these steps except where otherwise stated.

0. Create Facebook App

If you already have an app, skip to step 1.

  1. Go to My Apps.
  2. Click "+ Add a New App".
  3. Setup a website app.

You don't need to change its permissions or anything. You just need an app that wont go away before you're done with your access token.

1. Get User Short-Lived Access Token

  1. Go to the Graph API Explorer.
  2. Select the application you want to get the access token for (in the "Application" drop-down menu, not the "My Apps" menu).
  3. Click "Get Token" > "Get User Access Token".
  4. In the pop-up, under the "Extended Permissions" tab, check "manage_pages".
  5. Click "Get Access Token".
  6. Grant access from a Facebook account that has access to manage the target page. Note that if this user loses access the final, never-expiring access token will likely stop working.

The token that appears in the "Access Token" field is your short-lived access token.

2. Generate Long-Lived Access Token

Following these instructions from the Facebook docs, make a GET request to

https://graph.facebook.com/v2.10/oauth/access_token?grant_type=fb_exchange_token&client_id={app_id}&client_secret={app_secret}&fb_exchange_token={short_lived_token}

entering in your app's ID and secret and the short-lived token generated in the previous step.

You cannot use the Graph API Explorer. For some reason it gets stuck on this request. I think it's because the response isn't JSON, but a query string. Since it's a GET request, you can just go to the URL in your browser.

The response should look like this:

{"access_token":"ABC123","token_type":"bearer","expires_in":5183791}

"ABC123" will be your long-lived access token. You can put it into the Access Token Debugger to verify. Under "Expires" it should have something like "2 months".

3. Get User ID

Using the long-lived access token, make a GET request to

https://graph.facebook.com/v2.10/me?access_token={long_lived_access_token}

The id field is your account ID. You'll need it for the next step.

4. Get Permanent Page Access Token

Make a GET request to

https://graph.facebook.com/v2.10/{account_id}/accounts?access_token={long_lived_access_token}

The JSON response should have a data field under which is an array of items the user has access to. Find the item for the page you want the permanent access token from. The access_token field should have your permanent access token. Copy it and test it in the Access Token Debugger. Under "Expires" it should say "Never".

94
votes

Here's my solution using only Graph API Explorer & Access Token Debugger:

  1. Graph API Explorer:
    • Select your App from the top right dropdown menu
    • Select "Get User Access Token" from dropdown (right of access token field) and select needed permissions
    • Copy user access token
  2. Access Token Debugger:
    • Paste copied token and press "Debug"
    • Press "Extend Access Token" and copy the generated long-lived user access token
  3. Graph API Explorer:
    • Paste copied token into the "Access Token" field
    • Make a GET request with "PAGE_ID?fields=access_token"
    • Find the permanent page access token in the response (node "access_token")
  4. (Optional) Access Token Debugger:
    • Paste the permanent token and press "Debug"
    • "Expires" should be "Never"

(Tested with API Version 2.9-2.11, 3.0-3.1)

12
votes

I made a PHP script to make it easier. Create an app. In the Graph API Explorer select your App and get a user token with manage_pages and publish_pages permission. Find your page's ID at the bottom of its About page. Fill in the config vars and run the script.

<?php
$args=[
    'usertoken'=>'',
    'appid'=>'',
    'appsecret'=>'',
    'pageid'=>''
];

echo generate_token($args);

function generate_token($args){
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
    $longtoken=$r->access_token;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/me?access_token={$longtoken}")); // get user id
    $userid=$r->id;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
    foreach($r->data as $d) if($d->id==$args['pageid']) return $d->access_token;
}
11
votes

In addition to the recommended steps in the Vlasec answer, you can use:

  • Graph API explorer to make the queries, e.g. /{pageId}?fields=access_token&access_token=THE_ACCESS_TOKEN_PROVIDED_BY_GRAPH_EXPLORER
  • Access Token Debugger to get information about the access token.
10
votes

Another PHP answer to make lives easier. Updated for Facebook Graph API 2.9 . Just fill 'er up and load.

<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
    'usertoken'=>'',
    'appid'=>'',
    'appsecret'=>'',
    'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
    $longtoken=$r->access_token;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/me?access_token={$longtoken}")); // get user id
    $userid=$r->id;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$userid}?fields=access_token&access_token={$longtoken}")); // get permanent token
    if($r->id==$args['pageid']) $finaltoken=$r->access_token;
    return $finaltoken;
}
?>

Addendum: (alternative)

Graph 2.9 onwards , you can skip much of the hassle of getting a long access token by simply clicking Extend Access Token at the bottom of the Access Token Debugger tool, after having debugged a short access token. Armed with information about pageid and longlivedtoken, run the php below to get permanent access token.

<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
    'longlivedtoken'=>'',
    'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$args['pageid']}?fields=access_token&access_token={$args['longlivedtoken']}"));
return $r->access_token;
}
?>

Although the second code saves you a lot of hassle, I recommend running the first php code unless you are in a lot of hurry because it cross-checks pageid and userid. The second code will not end up working if you choose user token by mistake.

Thanks to dw1 and Rob

6
votes

I tried these steps: https://developers.facebook.com/docs/marketing-api/access#graph-api-explorer

Get Permanent Page Access Token

  • Go to Graph API Explorer
  • Select your app in Application
  • Paste the long-lived access token into Access Token
  • Next to Access Token, choose the page you want an access token for. The access token appears as a new string.
  • Click i to see the properties of this access token
  • Click “Open in Access Token Tool” button again to open the “Access Token Debugger” tool to check the properties

One Tip, it only worked for me when the page language is english.

4
votes

If you are requesting only page data, then you can use a page access token. You will only have to authorize the user once to get the user access token; extend it to two months validity then request the token for the page. This is all explained in Scenario 5. Note, that the acquired page access token is only valid for as long as the user access token is valid.

4
votes

While getting the permanent access token I followed above 5 steps as Donut mentioned. However in the 5th step while generating permanent access token its returning the long lived access token(Which is valid for 2 months) not permanent access token(which never expires). what I noticed is the current version of Graph API is V2.5. If you trying to get the permanent access token with V2.5 its giving long lived access token.Try to make API call with V2.2(if you are not able to change version in the graph api explorer,hit the API call https://graph.facebook.com/v2.2/{account_id}/accounts?access_token={long_lived_access_token} in the new tab with V2.2) then you will get the permanent access token(Which never expires)

3
votes

In addition to mentioned methods it is worth mentioning that for server-to-server applications, you can also use this form of permanent access token: app_id|app_secret This type of access token is called App Token. It can generally be used to call Graph API and query for public nodes within your application back-end. It is mentioned here: https://developers.facebook.com/docs/facebook-login/access-tokens

3
votes

As all the earlier answers are old, and due to ever changing policies from facebook other mentioned answers might not work for permanent tokens.

After lot of debugging ,I am able to get the never expires token using following steps:

Graph API Explorer:

  1. Open graph api explorer and select the page for which you want to obtain the access token in the right-hand drop-down box, click on the Send button and copy the resulting access_token, which will be a short-lived token
  2. Copy that token and paste it in access token debugger and press debug button, in the bottom of the page click on extend token link, which will extend your token expiry to two months.
  3. Copy that extended token and paste it in the below url with your pageId, and hit in the browser url https://graph.facebook.com/{page_id}?fields=access_token&access_token={long_lived_token}
  4. U can check that token in access token debugger tool and verify Expires field , which will show never.

Thats it

2
votes

Thanks to @donut I managed to get the never expiring access token in JavaScript.

// Initialize exchange
fetch('https://graph.facebook.com/v3.2/oauth/access_token?grant_type=fb_exchange_token&client_id={client_id}&client_secret={client_secret}&fb_exchange_token={short_lived_token}')
.then((data) => {
    return data.json();
})
.then((json) => {
    // Get the user data
    fetch(`https://graph.facebook.com/v3.2/me?access_token=${json.access_token}`)
    .then((data) => {
        return data.json();
    })
    .then((userData) => {
        // Get the page token
        fetch(`https://graph.facebook.com/v3.2/${userData.id}/accounts?access_token=${json.access_token}`)
        .then((data) => {
            return data.json();
        })
        .then((pageToken) => {
            // Save the access token somewhere
            // You'll need it at later point
        })
        .catch((err) => console.error(err))
    })
    .catch((err) => console.error(err))
})
.catch((err) => {
    console.error(err);
})

and then I used the saved access token like this

fetch('https://graph.facebook.com/v3.2/{page_id}?fields=fan_count&access_token={token_from_the_data_array}')
.then((data) => {
    return data.json();
})
.then((json) => {
    // Do stuff
})
.catch((err) => console.error(err))

I hope that someone can trim this code because it's kinda messy but it was the only way I could think of.

2
votes

If you have facebook's app, then you can try with app-id & app-secret.

Like :

access_token={your-app_id}|{your-app_secret}

it will don't require to change the token frequently.

1
votes

Application request limit reached (#4) - FB API v2.1 and greater

This answer led me to the "ultimate answer for us" and so it is very much related so I am appending it here. While it's related to the above it is different and it seems FB has simplified the process some.

Our sharing counts on our site stopped worked when FB rolled over the api to v 2.1. In our case we already had a FB APP and we were NOT using the FB login. So what we needed to do was get a FB APP Token to make the new requests. This is as of Aug. 23 2016.

  1. Go to: https://developers.facebook.com/tools/explorer
  2. Select the api version and then use GET and paste the following:

    /oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials
    

    You will want to go grab your app id and your app secret from your app page. Main FB Apps developer page

  3. Run the graph query and you will see:

    {
       "access_token": "app-id|app-token",
       "token_type": "bearer"
    }
    

    Where

    "app-id"
    and
    "app-token"
    will be your app id from your FB app page and the generated FB App HASH you just received.
  4. Next go test your new APP access token: FB Access Token tester

  5. You should see, by pasting the

    "app-token"
    into the token tester, a single app based token without an expiration date/time.

In our case we are using the FB js sdk so we changed our call to be like so (please note this ONLY gets the share count and not the share and comment count combined like it used to be):

FB.api(
    '/','GET',{
    // this is our FB app token for our FB app 
        access_token: FBAppToken,
        "id":"{$shareUrl}","fields":"id,og_object{ engagement }"
}

This is now working properly. This took a lot of searching and an official bug report with FB to confirm that we have to start making tokenized requests to the FB api. As an aside I did request that they (FB) add a clue to the Error code (#4) that mentions the tokenized request.

I just got another report from one of our devs that our FB comment count is broken as well due to the new need for tokenized requests so I will update this accordingly.

1
votes

Many of these examples do not work, not sure if it's because of 2.9v coming out but I was banging my head. Anyways I took @dw1 version and modified it a little with the help of @KFunk video and got this working for me for 2.9. Hope this helps.

$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
    'usertoken'=>'',
    'appid'=>'',
    'appsecret'=>'',
    'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
    $r = json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
    $longtoken=$r->access_token;
    $r=json_decode(file_get_contents("https://graph.facebook.com/{$args['pageid']}?fields=access_token&access_token={$longtoken}")); // get user id
    $finaltoken=$r->access_token;
    return $finaltoken;
}
0
votes

As of April 2020, my previously-permanent page tokens started expiring sometime between 1 and 12 hours. I started using user tokens with the manage_pages permission to achieve the previous goal (polling a Page's Events). Those tokens appear to be permanent.

I created a python script based on info found in this post, hosted at github.com/k-funk/facebook_permanent_token, to keep track of what params are required, and which methods of obtaining a permanent token are working.

0
votes

I created a small NodeJS script based on donut's answer. Store the following in a file called get-facebook-access-token.js:

const fetch = require('node-fetch');
const open = require('open');

const api_version = 'v9.0';
const app_id = '';
const app_secret = '';
const short_lived_token = '';
const page_name = '';

const getPermanentAccessToken = async () => {
  try {
    const long_lived_access_token = await getLongLivedAccessToken();
    const account_id = await getAccountId(long_lived_access_token);
    const permanent_page_access_token = await getPermanentPageAccessToken(
      long_lived_access_token,
      account_id
    );
    checkExpiration(permanent_page_access_token);
  } catch (reason) {
    console.error(reason);
  }
};

const getLongLivedAccessToken = async () => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/oauth/access_token?grant_type=fb_exchange_token&client_id=${app_id}&client_secret=${app_secret}&fb_exchange_token=${short_lived_token}`
  );
  const body = await response.json();
  return body.access_token;
};

const getAccountId = async (long_lived_access_token) => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/me?access_token=${long_lived_access_token}`
  );
  const body = await response.json();
  return body.id;
};

const getPermanentPageAccessToken = async (
  long_lived_access_token,
  account_id
) => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/${account_id}/accounts?access_token=${long_lived_access_token}`
  );
  const body = await response.json();
  const page_item = body.data.find(item => item.name === page_name);  
  return page_item.access_token;
};

const checkExpiration = (access_token) => {
  open(`https://developers.facebook.com/tools/debug/accesstoken/?access_token=${access_token}&version=${api_version}`);
}

getPermanentAccessToken();

Fill in the constants and then run:

npm install node-fetch
npm install open
node get-facebook-access-token.js

After running the script a page is opened in the browser that shows the token and how long it is valid.

0
votes

Most of the answers above now doesn't give permanent token, they only extend it to 2 months. Here's how I got it:

  1. From (Graph Explorer tool)0, select the relevant permissions and get the short lived page access token.
  2. (Go to debugger tool)1 and paste your access token. Then, click on 'Extend Token' button at the bottom of the page.
  3. Copy the the extended token and use it in this API:
  4. https://graph.facebook.com/v2.10/me?fields=access_token&access_token=<extended_access_token>
  5. This should return you the permanent access token. You can verify it in debugger tool, the expires at field should say 'Never'.
-1
votes

I found this answer which refers to this tool which really helped a lot.

I hope this answer is still valid when you read this.