Facebook: Permanent Page Access Token?
Asked Answered
S

19

221

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

Sismondi answered 19/6, 2013 at 17:52 Comment(2)
possible duplicate of Long-lasting FB access-token for server to pull FB page infoJavier
It sure seems so. I have better title, he has more detailed question and we both have roughly the same answer accepted.Sismondi
E
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".

Evelunn answered 9/2, 2015 at 20:14 Comment(75)
I haven't tested this, I hope someone else approves that this works. Someone else please confirm that it works for you as well.Sismondi
I missed this answer to a duplicate question before writing this. It provides the same steps and has a lot of people confirming that it works.Evelunn
Is it safe to use this token publicly or could it give access for someone to control the fb page?Ephrem
It is not safe to make this token public. It would, as you say, give anyone who knows it access to control the page.Evelunn
I think there is a way to invalidate the token. However, I think there is no backup available for a FB user, so if any damage is already done, it is permanent.Sismondi
I tried to do these steps as the Page itself (I want to post to Page's timeline as the Page) and got "(#100) Tried accessing nonexisting field (accounts) on node type (Page)" on step #5, but got an non-expiring token before that step that cannot post to itself :(Transcription
@Transcription You have to do this as a user who access to post to the page, you cannot do it as the page itself. This is the design of the 2.0 Graph API.Evelunn
But maybe there's another way. buffer.com schedule posts for me. I just want to make that on my own server.Transcription
@Transcription If you follow the directions above, you should be able to get that to work. All access is managed through users. So, using a Facebook user account that has access to manage the target page you can get a temporary access token and then turn it into a permanent access token that can be used without further user interaction.Evelunn
Step 4 is unnecessary, you can query /me/accounts directly using the long-lived user access token.Knock
Worked for me also, thanks. I only managed to obtained long lived access token via Graph API but when I just typed the GET requests in a browser tab, the access tokens generated were permanents. That's what happens when you don't follow each and every step !Pea
@Evelunn I created a test app, I am getting the long lived access token, but while fetching the page access token in step 5, the graph api returns a blank array Array ( [data] => Array ( ) )Johnnyjohnnycake
@Johnnyjohnnycake Does the user you're using have access to manage the target page?Evelunn
@Evelunn Yes, but when the user redirects to facebook page to allow the apps permission, it says "The app will access your basic profile"Johnnyjohnnycake
@Johnnyjohnnycake Are you using the Graph API Explorer to get the short-lived token, making sure that "manage_pages" permission is requested? It sounds like you're trying to implement this on a website. However you request the permission, you need to be sure that the "manage_pages" permission is requested.Evelunn
@Evelunn I am using this echo "<a href='https://www.facebook.com/dialog/oauth?client_id=$appId&redirect_uri=$redirectUri&scope=manage_pages&state=$state'>Get Facebook Code</a>"; I have passed the manage_pages in the scope.Johnnyjohnnycake
@Johnnyjohnnycake I'm not that familiar with that method of asking for permissions. But I think you have to have that permission approved by Facebook before your application can ask for it. So, even if you add it, it wont work because your app hasn't been approved to request that permission. I especially think this since the message "The app will access your basic profile" doesn't mention page access. If you're having problems with this, you should probably start a new question.Evelunn
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?Andino
I am getting empty json data after following those steps.Centigrade
Thanks for this. Note, if you're using curl for step 2 it may help if you wrap the entire URL in quotes.Flee
This worked for me—many thanks. I can't believe this is the ridiculous, convoluted process that Facebook expects us to go through.Hereinafter
@Evelunn For some reason, at the end of step 2, I ended up with a permanent page access token, but that's not supposed to happen, right? When I just checked the access_token returned by step 2 in the Access Token Debugger, it says "Expires: Never", so assuming I'm ok. Not complaining, but just curious...Concede
@Malvin9000 Don't know what's going on there. I never experienced that. I would suggest doing more tests if you decide to automate this process.Evelunn
I get an error message >> { "error": { "message": "The access token does not belong to application XXXXXXX", "type": "OAuthException", "code": 1 } }Cavendish
@DavidOkwii I'm not sure, but a guess would be that you need to request the access token with the same app that you intend to use it with. If you're using the Graph API Explorer, be sure to select the correct application before getting permissions from the user. If you're already doing that, I'd suggest creating another question here on SO to get to the bottom of the problem.Evelunn
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)Concede
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.Splendent
@donut, can you fix the answer somehow? I am no longer doing any development with FB OAuth, so I can't even try it unless I develop at least some small basic app again.Sismondi
@Sismondi I'll look into fixing the answer in the next few days when I have time to go through the steps again.Evelunn
@SeptianPrimadewa If by "legal" you are referring to whether or not Facebook approves of this, I think it is. I basically just copied these steps from Facebook's documentation.Evelunn
Hmm, I'm getting an empty response from step 5. Also, the official Facebook documentation says: "Page Access tokens have expirations; your app can continue to use a Page Access token for an hour after you originally get it." Can someone confirm that this still works?Trellis
EDIT: Okay, for me the tricky thing was that manage_pages was checked but grayed out. I needed to uncheck it then re-check it in order for it to work. Strange.Trellis
@bart In the "Extended Permissions" panel.Trellis
Going to the graph api explorer and using a page access token instead of a short term access token in step 2 seems to generate an access token that never expires...Corena
All the 5 steps work for me for FB v2.5. Thanks very muchHutto
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}Stickpin
Quiet some steps to get there. Anyone did automate that yet?Skive
In the last step I'm getting the following exception { "error": { "message": "Syntax error \"Expected end of string instead of \"?\".\" at character 11: access_toke\u200c\u200bn", "type": "OAuthException", "code": 2500, "fbtrace_id": "A8+gtSaShIO" } } Anyone knows how to resolve it????Appassionato
graph.facebook.com/v2.2{account_id}/accounts?access_token={long‌​_lived_access_token} it return response null { "data": [ ] }Pierides
@omid.n :- can you please post your code to like any post or any page ?Pierides
@Nancythakkar actually now facebook has a neat and clean way for managing tokens. Just checkout developers.facebook.com/tools/accesstoken You select the token and then click 'Extend Access Token'Bend
But My question is how we like /unlike any feeds from android app everytime it shows me error response: responseCode: 400, graphObject: null, error: {HttpStatus: 400, errorCode: 3, errorType: OAuthException, errorMessage: (#3) Publishing likes through the API is only available for page access tokens}} So How we get page access token?Pierides
And since I'm using the Facebook Marketing / Ads API, this was helpful: developers.facebook.com/docs/marketing-api/accessLanai
Step 5 and (#100) Tried accessing nonexisting field (accounts) on node type (Page): Different URL fixed the problem for me: https://graph.facebook.com/v2.8/195252237221555/?fields=access_token&access_token={long_lived_access_token}Colonial
Still works for me, even though it says that I needed the app review for the permissions. I just ignored it and continued thru granting permissions.Carn
"message": "The access token does not belong to application **********", after second stepApproach
Using Access Token Debugger: Step 1 generated an access token that expired in 1 hour. Step 2 generated an access token that never expires. Using v2.9.Vagrant
Hi, @Evelunn they updated the Graph API Explorer for v2.9 so that you can generate the long-lived access token now via the Explorer. You may consider changing your answer according to thatKendalkendall
Maybe I'am dumb, but why is this not well documented on the facebook developer documentation?Millikan
@Millikan That's the reason I had to write this answer and why it has so many up votes. Don't know why it's not well documented.Evelunn
I wonder how secure a permanent page token is. Since the token is passed in as a query parameter, is there a way someone watching the network traffic can snoop the token?Landsturm
@Landsturm Since the API is only accessed over HTTPS, everything should be encrypted at least as securely as password forms on websites under HTTPS.Evelunn
@ToyRobotic, I agree, I wasted a lot of time till I found this answer. Which still works fine as of November 2017, by the way. This one helps as well.Lacey
is it safe to add this access token to my .js file?Stacy
@Stacy Absolutely not. Unless it's only running server side with something like NodeJS, you don't want this token to be publicly accessible.Evelunn
@donut, thanks. But could you please explain what are the vulnerabilities that may face if we use token in .js file?Stacy
@Stacy This token is basically a key to access and make changes to a Facebook page. If you put it in a .js file, anybody who visits your website with that .js file could discover that token and make changes to the page.Evelunn
@Evelunn thanks i have got permanent access token using your method.Atonic
Looks like this isn't enough anymore after Facebook's recent changes to their API: engadget.com/2018/04/24/…Cordalia
Recently my account was disabled (FB suspected it was compromised, but it didn't seem to be) and I had to change my password to re-activate it. Somewhere in that process, it invalidated my permanent token, so that is something to keep in mind. Luckily, this process still seems to be working 2018-07-18.Apanage
This still works, worked for me... the answer below this one also works too, thanks for the solutions!Cymbre
Actually, after attempting this on another account, this only seems to work if you have an app with version <3.0 (i.e. 2.12)Apanage
In step 4, I am getting empty data array data[]Iodism
Same here, an empty response in step 4. Guess FB has changed it again!!!Ginder
Confirming it working properly with v3.2 as of today. Permanent access token received successfully.Natatory
Likewise, trying this today with v3.3 all steps worked and I now have a token that will never expire. Perfect.Incunabulum
1 - Data Access Expires in 3 months. (Is it based on when the user was last active?) 2 - I need the account insights. Is it enough to save only one access token? For fetching account or ad insights, is there any relation with all page access tokens?Jephum
I got "(#100) Tried accessing nonexisting field (accounts) on node type (Page)" error on step 4. Replacing app id with my user id resolved the issue.Salesclerk
When i validate my token ist says : Expirer Never, Data Access Expires 1603117184 (in about 3 months) Does that mean it will no longer work in 3 month and need to be renewed ?Rubefaction
Tested this today with version 9.0 of the API. The request in step 2 does return valid JSON now. But the token I generated in step 4 is only valid for 2 months. I can only select version 9.0 in the Graph API Explorer. So will try to get this to work with an older version.Ugaritic
Token generated in step 4 is still not permanent. I got the permanent token from same API as account it like: https://graph.facebook.com/v2.10/me?fields=access_token&access_token=<access_token>. You verify it by pasting in token debug tool.Huda
Incase (like me ) you arrived here wondering if this is still good ... the answer is YES as of 26-9-2021 or 9-26-2021 depending where you're coming from.Pretermit
This still works in 2022 using v13.0 of the graph explorer. The key to the entire thing is to not use the Graph API Explorer from step 2 on. I used Postman and I was able to get the token. Using the Graph Explorer always gave me a long-lived token.Overdue
This works for certain pages that I own, but not for another one that I more recently created. Yet I created and own it. It seems like you first need, as a human administrator, to give the app some permission for the page, but I can't find where to do that.Sanskritic
You may also try to use this bnjis.github.io/Facebook-permanent-token-generator toolWellspoken
W
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)

Weiman answered 23/4, 2017 at 10:44 Comment(18)
There is no "Extend Access Token" button to press. Maybe they took it out.Dhu
I see the "Extend" buttonRadiopaque
After extending access token (step 2) and debugging it again, it should be never expiring. You may just pass steps 3 and 4.Trusting
Thanks for this answer way more easier to understand than the big one above. It was really helpful.Gascon
Oh, dude, you are on fire! Big thanks! I wasted so much time to find this option, because I couldn't debug an app properly!Forwardlooking
For those who couldn't see the "Extend Access Token", remember to "Select your App from the top right dropdown menu" (and not "Graph API Explorer") as described in step 1!Olympie
Wow, I didn't know it was this easy to get a permanent access token! Thanks! This worked for me on API Version 2.12.Sporadic
This also works for page access tokens, not just user access tokens.Sporadic
I get a tried to access non existing fields access_tokenTentative
@Tentative I too get the same error: (#100) Tried accessing nonexisting field (access_token) on node type (Application). All steps worked until 3.2.Schellens
I manage to get temp page token with my user token. Extending the page token seems to give me the permanent page token. I'm on Graph Explorer, API 3.2.Immobilize
Note that if you stop at step 2, as previously suggested, you'll get have a user access token instead of a page access tokenUnparliamentary
THANKS! how is this not in Facebook doc??Inflectional
Does the Data Access expire?Dipody
What is the "Data access expire"? Even though the token says "Expires: Never", the "Data access expires" says in about 3 months.Sybaris
The expiration period for data access is 90 days, based on when the user was last active. When this 90-day period expires, the user can still access your app — that is, they are still authenticated — but your app can't access their data. To regain data access, your app must ask the user to re-authorize your app's permissions.Jephum
It was working fine until now. (#200) The permission(s) manage_pages,publish_pages are not available. It could because either they are deprecated or need to be approved by App Review. and (#200) This endpoint is deprecated since the required permission publish_actions is deprecatedBaudoin
I was able to create a permanent access token but I noticed a strange regression. When I used a "default" user token, I was able to recover the page's events with calls to "page/feed" ou "page/events". With the permanent access token, I no longer get the events. Is this normal?Stat
D
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.
Dividend answered 9/11, 2013 at 0:0 Comment(3)
This doesn't work anymore. The token only lasts for an hourDiscontinue
@Discontinue have you actually tested this on v2.8? the token debugger shows Expires NeverTbilisi
I don't remember. I may have tested it.Discontinue
G
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;
}
Gustafson answered 11/4, 2017 at 14:56 Comment(4)
+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.Gonnella
Sorry, I wasn't allowed to edit this answer. So, for Graph API 2.9, I wrote another answer instead.Gonnella
Seems like they changed stuff with 2.9 because none of these examples work anymoreDhu
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?Bascinet
G
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

Gonnella answered 25/4, 2017 at 8:9 Comment(5)
The Extend Access Token button is not there, am I missing something?Dhu
@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.Gonnella
@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.Gonnella
@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 :)Gonnella
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. WierdDhu
T
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.

Tamer answered 15/12, 2016 at 12:26 Comment(2)
THIS GUY!!! 5 virtual beers. This works replacing step 5 of the approved answer. graph version 2.8Deshabille
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, 2017Bromism
H
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'.
Huda answered 9/1, 2021 at 10:36 Comment(4)
Step 4 doesn't seem to work for me. I'm getting "(#100) Tried accessing nonexisting field (access_token) on node type (User)"Lorolla
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.Huda
Nice find. Thanks :)Caseation
In the debugger it says: Expires: Never and Data Access Expires: 1681385400 (in about 3 months). So will it stop working in 3 months?Bascinet
T
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

Truthfunction answered 2/10, 2020 at 18:38 Comment(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.Sismondi
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.Sismondi
@Sismondi answer is correct and using the same token in production.Truthfunction
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.Olympia
R
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.

Rigidify answered 19/6, 2013 at 17:57 Comment(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?Sismondi
@Viasec Correct the only way to get an access token is via an application as explained here developers.facebook.com/docs/facebook-loginRigidify
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.Sismondi
I
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)

Improvement answered 20/3, 2016 at 3:25 Comment(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.Estefanaestel
it returns null :( How we get page access token ?Pierides
T
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

Tallu answered 8/3, 2015 at 16:47 Comment(4)
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.Sismondi
@Sismondi It allows you to access comments on a public postBenny
While that might be enough for some, it doesn't answer the question.Sismondi
Yes, I could not find a way to access a page's data or posts using this method. Maybe it only supports other endpoints.Bascinet
A
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.

Annora answered 3/7, 2019 at 5:37 Comment(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.Bascinet
C
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.

Chant answered 7/1, 2019 at 17:41 Comment(0)
L
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.

Liew answered 23/8, 2016 at 15:12 Comment(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?Sismondi
D
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;
}
Dhu answered 19/6, 2017 at 21:9 Comment(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.Sismondi
@Sismondi 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.Gonnella
C
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.

Cordalia answered 14/5, 2020 at 9:0 Comment(0)
U
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.

Ugaritic answered 24/11, 2020 at 11:8 Comment(0)
M
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";
}
Morette answered 3/2 at 9:34 Comment(0)
G
-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.

Grisly answered 3/3, 2018 at 12:25 Comment(1)
OK. Does the answer by donut still work, or does it need some extra step?Sismondi

© 2022 - 2024 — McMap. All rights reserved.