219

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

2

19 Answers 19

680

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

75
  • 5
    Step 4 is unnecessary, you can query /me/accounts directly using the long-lived user access token.
    – CBroe
    Commented May 15, 2015 at 20:28
  • 15
    Facebook messed this up so it doesn't work anymore. :-( After step 1.5 above (clicking the "Get Access Token" button) a red warning appears in the following dialog, stating "Submit for Login Review - Some of the permissions below have not been approved for use by Facebook" and also a padlock with the text "This does not let the app post to Facebook" appears at the same time below. So a new step should be inserted between step 1.5 and 1.6 above, reading "Do a lot of tedious sh*t with your app, then submit it for review, then pray and wait." :-( Anyone know a way around this for a pure test app? Commented Jul 27, 2015 at 0:48
  • 10
    For anyone who gets to the last step, and the browser just returns: message: "(#100) Tried accessing nonexisting field (accounts) on node type (Page)", type: "OAuthException", code: 100 go to the FB Access Token Debugger and test your long_lived_access_token. Consistently I've seen that after a few minutes, if you go back and recheck the long_lived_access_token the FB Access Token Debugger will then indicate that that token is permanent (expire: never) Commented Sep 22, 2015 at 19:24
  • 14
    I swear, if i had not read this answer, i would still be banging my head to the wall with a short lived token... To bad that the last part isn't working... I'm getting the (#100) Tried accessing nonexisting field (accounts) on node type (Page) error... unable to proceed with step 5... Still, thank you... LE: check out the last part of the answer provided by @Vlasec. You can get the permanent access token by querying /{pageId}?fields=access_token&access_token={long_lived_access_token} so problem fixed. Commented Oct 27, 2015 at 13:13
  • 15
    Had to use this for the final step to get my permanent access token as it says "accounts" does not exist, even for v2.7: https://graph.facebook.com/v2.7/{page_id}?fields=access_token&access_token={long_lived_access_token}
    – Reado
    Commented Jul 23, 2016 at 9:07
101

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)

18
  • 3
    There is no "Extend Access Token" button to press. Maybe they took it out. Commented Jun 19, 2017 at 20:24
  • 4
    I see the "Extend" button
    – Eduardo
    Commented Jul 9, 2017 at 5:31
  • 2
    After extending access token (step 2) and debugging it again, it should be never expiring. You may just pass steps 3 and 4. Commented Aug 23, 2017 at 13:48
  • 3
    Does the Data Access expire? Commented Jul 9, 2019 at 2:57
  • 3
    What is the "Data access expire"? Even though the token says "Expires: Never", the "Data access expires" says in about 3 months.
    – notQ
    Commented Sep 19, 2019 at 10:46
12

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.
3
  • 3
    This doesn't work anymore. The token only lasts for an hour
    – flashsnake
    Commented Jan 23, 2016 at 3:52
  • @flashsnake have you actually tested this on v2.8? the token debugger shows Expires Never
    – Bizmate
    Commented Jan 13, 2017 at 8:10
  • I don't remember. I may have tested it.
    – flashsnake
    Commented Feb 20, 2017 at 23:31
12

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;
}
4
  • 1
    +1 Just tried and, among all these partially depreciating answers, it works wonders! I like this answer because future modifications are easy with a little edit here and there. Commented Apr 16, 2017 at 14:50
  • Sorry, I wasn't allowed to edit this answer. So, for Graph API 2.9, I wrote another answer instead. Commented Apr 25, 2017 at 8:11
  • Seems like they changed stuff with 2.9 because none of these examples work anymore Commented Jun 19, 2017 at 20:28
  • This doesn't return a permanent token, does it? Just a 60 day token? Looks like you'd have to run the function again within the 60 days to get an updated one?
    – Simon E.
    Commented Jan 13, 2023 at 11:23
11

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

5
  • The Extend Access Token button is not there, am I missing something? Commented Jun 19, 2017 at 20:33
  • @CesarBielich: You have to debug a Short Access Token first. It appears below the results when you debug a short app token. Since you cannot see it, you must have debugged a user access token. Note that this answer does not apply to use access token; only app access token can be used User Acess Tokens cannot be permanent. They can be generated upto Long Tokens. Commented Jun 21, 2017 at 14:58
  • 1
    @CesarBielich I think you are confusing something here. You can create access tokens for Users, Apps and Pages. You need to choose an app that you created, instead of Graph API Explorer in the Application field before you can request a token. Commented Jun 21, 2017 at 15:05
  • @CesarBielich: Use the first method if the second one is too confusing for you. You just fill the input fields in the first one and everything happens automatically :) Commented Jun 21, 2017 at 15:07
  • Sorry I was commenting about a different post I just made last night lol. Yeah for some reason I couldnt get yours to work and make me a never expiring token. I had to remove the v2.9 in the second call and that worked for me. Wierd Commented Jun 21, 2017 at 15:42
7

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.

2
  • 1
    THIS GUY!!! 5 virtual beers. This works replacing step 5 of the approved answer. graph version 2.8
    – Root -
    Commented Mar 13, 2017 at 16:21
  • 2
    I have wasted weeks on being able to use the Facebook API. It is, to date, the most confused and inconsistent token I have come across. This solution still works perfectly.. October, 2017
    – tinonetic
    Commented Oct 14, 2017 at 13:41
7

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, select the relevant permissions and get the short lived page access token.
  2. Go to debugger tool 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'.
4
  • Step 4 doesn't seem to work for me. I'm getting "(#100) Tried accessing nonexisting field (access_token) on node type (User)"
    – brz
    Commented Jan 23, 2021 at 18:49
  • 1
    Your extended_access_token needs to Page access token and not user. In the first step, when you select the permission, you'll have to change the token type to page using the provided dropdown in Graph Explorer. Also, to verify, if you query fields=name in step 4, you should get the Page name and not user name.
    – krsoni
    Commented Jan 27, 2021 at 7:33
  • Nice find. Thanks :)
    – Neeraj
    Commented Feb 18, 2022 at 8:27
  • 1
    In the debugger it says: Expires: Never and Data Access Expires: 1681385400 (in about 3 months). So will it stop working in 3 months?
    – Simon E.
    Commented Jan 13, 2023 at 11:35
6

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

4
  • Hello, thanks for your answer. It looks simple enough. Perhaps you could provide an answer that uses Facebook API URLs rather than their user interface? For example, the software I was developing 7 years ago was supposed to do everything automatically when the customer allows the application access to the page.
    – Vlasec
    Commented Oct 12, 2020 at 14:31
  • I am no longer actively anything Facebook-related at the moment. But if you are sure your answer is the solution, I could mark it as such and check the upvotes and keep it as such if it works for others.
    – Vlasec
    Commented Oct 12, 2020 at 14:32
  • @Vlasec answer is correct and using the same token in production. Commented Dec 21, 2020 at 17:19
  • This one worked great for me (February 2022). I already had the long lived token and was able to get the permanent by connecting to that URL(from step 3) in my PHP code. Commented Feb 7, 2022 at 19:55
4

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.

3
  • Sorry, maybe I wasn't clear enough. I've read about tokens, I just need to learn how to ask the user for permission and transfer a token to my app. It seems I need to create some facebook "app" which sole purpose is asking for permissions, is that right?
    – Vlasec
    Commented Jun 20, 2013 at 7:51
  • 1
    @Viasec Correct the only way to get an access token is via an application as explained here developers.facebook.com/docs/facebook-login
    – phwd
    Commented Jun 20, 2013 at 11:50
  • Thanks, I must have disregarded it somehow, I assumpted it to be somewhere in the APIs section, which was wrong. I'll look at that, I hope it answers my question.
    – Vlasec
    Commented Jun 20, 2013 at 12:56
4

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)

2
  • Going back api versions to achieve results will only result in more work in the future I've found, especially since API version expire after a certain time.
    – SlickRemix
    Commented Sep 17, 2016 at 2:22
  • it returns null :( How we get page access token ? Commented Dec 15, 2016 at 9:51
3

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

4
  • 1
    Does it allow any kind of access to pages? I think it doesn't and in that case it doesn't really answer the question.
    – Vlasec
    Commented Mar 9, 2015 at 15:12
  • @Vlasec It allows you to access comments on a public post
    – Ali Gajani
    Commented Feb 2, 2017 at 2:02
  • 1
    While that might be enough for some, it doesn't answer the question.
    – Vlasec
    Commented Feb 6, 2017 at 13:29
  • Yes, I could not find a way to access a page's data or posts using this method. Maybe it only supports other endpoints.
    – Simon E.
    Commented Jan 13, 2023 at 11:47
3

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
  • I think this might work for some things, but I couldn't find a way to activate the right permissions to access a page's posts using this method.
    – Simon E.
    Commented Jan 13, 2023 at 11:41
2

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.

1

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
  • 1
    It was always the user of the app who did the login and allowed the app the access. Anyway, this doesn't seem to create a page access token, so I think it is not a valid answer to the question. Interesting though - maybe make a Q/A of your own?
    – Vlasec
    Commented Sep 2, 2016 at 14:09
1

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;
}
2
  • Nice snippet, but this question is not about how to make it in PHP, but about how to use the API itself, which can be done in Java or .NET as well. For example I needed to do it in Java. Pseudocode or step by step guide would be more useful for those not using PHP.
    – Vlasec
    Commented Jul 11, 2017 at 13:19
  • 2
    @Vlasec I'd argue that this PHP snippet is pretty close to any pseudo code and is very easy to understand. Casar is just using some APIs that are already provided by facebook. Rest of the stuff is self explanatory. Commented Apr 10, 2018 at 4:20
0

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

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

This code tip can help you

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

echo generate_token($args);

function generate_token($args)
{
    $r = json_decode(file_get_contents("https://graph.facebook.com/v18.0/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/v18.0/me?access_token={$longtoken}")); // get user id
    $userid = $r->id;
    $r = json_decode(file_get_contents("https://graph.facebook.com/v18.0/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
    foreach ($r->data as $d) {
        if (!empty($d->access_token)) {
            return $d->access_token;
        }
    }

    return "not found";
}
-1

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.

1
  • OK. Does the answer by donut still work, or does it need some extra step?
    – Vlasec
    Commented Mar 8, 2018 at 16:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.