204

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

Community
  • 1
  • 1
Vlasec
  • 5,143
  • 3
  • 23
  • 29
  • 2
    possible duplicate of [Long-lasting FB access-token for server to pull FB page info](http://stackoverflow.com/questions/12168452/long-lasting-fb-access-token-for-server-to-pull-fb-page-info) – Gajus Aug 09 '14 at 15:24
  • It sure seems so. I have better title, he has more detailed question and we both have roughly the same answer accepted. – Vlasec Oct 10 '14 at 09:23

18 Answers18

660

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

donut
  • 9,157
  • 5
  • 29
  • 52
  • 1
    I haven't tested this, I hope someone else approves that this works. Someone else please confirm that it works for you as well. – Vlasec Feb 10 '15 at 15:47
  • I missed [this answer to a duplicate question](http://stackoverflow.com/a/21927690/134014) before writing this. It provides the same steps and has a lot of people confirming that it works. – donut Feb 17 '15 at 16:50
  • Is it safe to use this token publicly or could it give access for someone to control the fb page? – Moss Feb 23 '15 at 23:43
  • It is **not safe** to make this token public. It would, as you say, give anyone who knows it access to control the page. – donut Feb 24 '15 at 17:06
  • 1
    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. – Vlasec Mar 09 '15 at 15:16
  • 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 :( – gabrielhpugliese Apr 30 '15 at 03:14
  • @gabrielhpugliese 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. – donut May 01 '15 at 17:11
  • But maybe there's another way. buffer.com schedule posts for me. I just want to make that on my own server. – gabrielhpugliese May 01 '15 at 23:07
  • @gabrielhpugliese 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. – donut May 04 '15 at 15:34
  • 4
    Step 4 is unnecessary, you can query `/me/accounts` directly using the long-lived user access token. – CBroe May 15 '15 at 20:28
  • 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 ! – JJP May 29 '15 at 07:39
  • 2
    @donut 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 ( ) )` – Criesto Jun 16 '15 at 07:12
  • 1
    @Criesto Does the user you're using have access to manage the target page? – donut Jun 17 '15 at 17:48
  • @donut Yes, but when the user redirects to facebook page to allow the apps permission, it says "The app will access your basic profile" – Criesto Jun 18 '15 at 06:29
  • @Criesto 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. – donut Jun 18 '15 at 17:23
  • @donut I am using this `echo "Get Facebook Code";` I have passed the `manage_pages` in the scope. – Criesto Jun 19 '15 at 06:02
  • 1
    @Criesto 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. – donut Jun 19 '15 at 18:32
  • 14
    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? – QuestionOverflow Jul 27 '15 at 00:48
  • 1
    I am getting empty json data after following those steps. – Musakkhir Sayyed Aug 04 '15 at 13:12
  • Thanks for this. Note, if you're using curl for step 2 it may help if you wrap the entire URL in quotes. – GoGoCarl Aug 11 '15 at 01:38
  • This worked for me—many thanks. I can't believe this is the ridiculous, convoluted process that Facebook expects us to go through. – greenie2600 Aug 20 '15 at 18:28
  • 2
    @donut 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... – AdjunctProfessorFalcon Aug 21 '15 at 05:13
  • @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. – donut Aug 21 '15 at 17:45
  • I get an error message >> { "error": { "message": "The access token does not belong to application XXXXXXX", "type": "OAuthException", "code": 1 } } – David Okwii Sep 01 '15 at 11:31
  • @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. – donut Sep 03 '15 at 20:00
  • 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) – AdjunctProfessorFalcon Sep 22 '15 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. – Mujnoi Gyula Tamas Oct 27 '15 at 13:13
  • @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. – Vlasec Oct 27 '15 at 13:28
  • @Vlasec I'll look into fixing the answer in the next few days when I have time to go through the steps again. – donut Oct 27 '15 at 16:56
  • 1
    @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. – donut Nov 08 '15 at 23:01
  • 1
    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? – Pete Nov 24 '15 at 15:12
  • 1
    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. – Pete Nov 24 '15 at 15:51
  • @bart In the "Extended Permissions" panel. – Pete Nov 25 '15 at 15:23
  • 1
    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... – Strainy Dec 29 '15 at 23:23
  • 2
    All the 5 steps work for me for FB v2.5. Thanks very much – zhihong Apr 04 '16 at 09:27
  • 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 Jul 23 '16 at 09:07
  • 1
    Quiet some steps to get there. Anyone did automate that yet? – Markus Malkusch Sep 25 '16 at 10:43
  • 5
    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???? – Lucy Sep 27 '16 at 11:04
  • https://graph.facebook.com/v2.2/{account_id}/accounts?access_token={long‌​_lived_access_token} it return response null { "data": [ ] } – Nancy thakkar Dec 15 '16 at 10:18
  • @omid.n :- can you please post your code to like any post or any page ? – Nancy thakkar Dec 15 '16 at 10:21
  • @Nancythakkar actually now facebook has a neat and clean way for managing tokens. Just checkout https://developers.facebook.com/tools/accesstoken/ You select the token and then click 'Extend Access Token' – omid.n Dec 15 '16 at 11:31
  • 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? – Nancy thakkar Dec 15 '16 at 11:50
  • And since I'm using the Facebook Marketing / Ads API, this was helpful: https://developers.facebook.com/docs/marketing-api/access – Ryan Jan 12 '17 at 04:02
  • 2
    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}` – Petr Cibulka Feb 03 '17 at 11:38
  • 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. – Micheal Luttrull May 08 '17 at 11:24
  • "message": "The access token does not belong to application **********", after second step – Paras Grover May 10 '17 at 13:33
  • 1
    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`. – Daerik May 25 '17 at 15:38
  • 1
    Hi, @donut 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 that – Felix Geenen Jul 03 '17 at 12:29
  • 2
    Maybe I'am dumb, but why is this not well documented on the facebook developer documentation? – ToyRobotic Jul 11 '17 at 12:48
  • @ToyRobotic 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. – donut Jul 11 '17 at 16:59
  • 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? – Keeto Sep 18 '17 at 22:06
  • @Keeto Since the API is only accessed over HTTPS, everything should be encrypted at least as securely as password forms on websites under HTTPS. – donut Sep 18 '17 at 22:44
  • 2
    @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](https://stackoverflow.com/a/39248356/1688203) helps as well. – retif Nov 23 '17 at 10:14
  • is it safe to add this access token to my .js file? – Mihir Mar 03 '18 at 13:12
  • @Mihir **Absolutely not.** Unless it's only running server side with something like NodeJS, you don't want this token to be publicly accessible. – donut Mar 09 '18 at 23:05
  • @donut, thanks. But could you please explain what are the vulnerabilities that may face if we use token in .js file? – Mihir Mar 12 '18 at 12:47
  • @Mihir 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. – donut Mar 14 '18 at 23:32
  • 1
    @donut thanks i have got permanent access token using your method. – Bhavin Thummar Mar 22 '18 at 06:03
  • Looks like this isn't enough anymore after Facebook's recent changes to their API: https://www.engadget.com/2018/04/24/facebook-limit-access-user-data-third-party-apps/ – KFunk May 06 '18 at 20:28
  • 1
    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. – Mingwei Samuel Jul 19 '18 at 03:42
  • 1
    This still works, worked for me... the answer below this one also works too, thanks for the solutions! – tdelam Sep 17 '18 at 15:36
  • 1
    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) – Mingwei Samuel Oct 01 '18 at 05:44
  • 2
    In step 4, I am getting empty data array data[] – Muhammad Ali Hassan Mar 09 '19 at 15:51
  • Same here, an empty response in step 4. Guess FB has changed it again!!! – andrewdixon Apr 03 '19 at 13:49
  • Confirming it working properly with v3.2 as of today. Permanent access token received successfully. – leymannx Apr 24 '19 at 11:50
  • Likewise, trying this today with v3.3 all steps worked and I now have a token that will never expire. Perfect. – dan richardson May 20 '19 at 13:51
  • 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? – Ashwanth Madhav Dec 04 '19 at 06:49
  • 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. – quotesBro Jan 20 '20 at 06:22
  • 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 ? – daslicht Jul 21 '20 at 14:24
  • 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. – Erik van den Hoorn Nov 23 '20 at 15:23
  • 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=`. You verify it by pasting in token debug tool. – krsoni Jan 09 '21 at 10:29
94

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)

Rob
  • 4,999
  • 30
  • 33
  • 3
    There is no "Extend Access Token" button to press. Maybe they took it out. – Cesar Bielich Jun 19 '17 at 20:24
  • 4
    I see the "Extend" button – Eduardo Jul 09 '17 at 05: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. – daniel_serretti Aug 23 '17 at 13:48
  • 1
    Thanks for this answer way more easier to understand than the big one above. It was really helpful. – Paul Laffitte Oct 18 '17 at 08:30
  • 2
    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! – Killuminati Nov 15 '17 at 23:44
  • 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! – sonlexqt Jan 14 '18 at 19:25
  • 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. – Sean the Bean Mar 01 '18 at 14:32
  • This also works for page access tokens, not just user access tokens. – Sean the Bean Mar 01 '18 at 21:16
  • 1
    I get a tried to access non existing fields access_token – Natim Jun 04 '18 at 09:27
  • 1
    @Natim I too get the same error: `(#100) Tried accessing nonexisting field (access_token) on node type (Application)`. All steps worked until 3.2. – mateuscb Oct 30 '18 at 02:23
  • 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. – Douglas Liu Jan 18 '19 at 10:16
  • Works like a charm – Alex Kuzava Feb 26 '19 at 13:19
  • Note that if you stop at step 2, as previously suggested, you'll get have a user access token instead of a page access token – mcont Mar 14 '19 at 18:01
  • THANKS! how is this not in Facebook doc?? – Pm Rivière Apr 12 '19 at 08:11
  • 1
    Does the Data Access expire? – turtlepower Jul 09 '19 at 02:57
  • What is the "Data access expire"? Even though the token says "Expires: Never", the "Data access expires" says in about 3 months. – notQ Sep 19 '19 at 10:46
  • 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. – Ashwanth Madhav Dec 02 '19 at 10:12
  • 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 deprecated` – Emerica Apr 17 '20 at 10:27
  • 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? – Gold.strike Sep 16 '20 at 14:10
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;
}
dw1
  • 851
  • 10
  • 13
  • 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. – Siddhant Rimal Apr 16 '17 at 14:50
  • Sorry, I wasn't allowed to edit this answer. So, for Graph API 2.9, I wrote [another answer](http://stackoverflow.com/a/43605020/5040900) instead. – Siddhant Rimal Apr 25 '17 at 08:11
  • Seems like they changed stuff with 2.9 because none of these examples work anymore – Cesar Bielich Jun 19 '17 at 20:28
11

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.
Gajus
  • 55,791
  • 58
  • 236
  • 384
chuycepeda
  • 316
  • 2
  • 6
10

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

Community
  • 1
  • 1
Siddhant Rimal
  • 885
  • 1
  • 11
  • 26
  • The Extend Access Token button is not there, am I missing something? – Cesar Bielich Jun 19 '17 at 20:33
  • @CesarBielich: You have to debug a Short Access Token first. It appears [below the results](http://imgur.com/nQ07ec3) 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. – Siddhant Rimal Jun 21 '17 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](http://imgur.com/a/v1sbd) that you created, instead of `Graph API Explorer` in the Application field before you can request a token. – Siddhant Rimal Jun 21 '17 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 :) – Siddhant Rimal Jun 21 '17 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 – Cesar Bielich Jun 21 '17 at 15:42
6

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.

Fabian Schmick
  • 1,426
  • 2
  • 20
  • 29
  • 1
    THIS GUY!!! 5 virtual beers. This works replacing step 5 of the approved answer. graph version 2.8 – Root - Mar 13 '17 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 – user919426 Oct 14 '17 at 13:41
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.

Gajus
  • 55,791
  • 58
  • 236
  • 384
phwd
  • 19,949
  • 5
  • 47
  • 77
  • 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 Jun 20 '13 at 07:51
  • 1
    @Viasec Correct the only way to get an access token is via an application as explained here https://developers.facebook.com/docs/facebook-login/ – phwd Jun 20 '13 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 Jun 20 '13 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)

baji shaik
  • 41
  • 1
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

azec-pdx
  • 4,177
  • 6
  • 49
  • 81
3

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

  • 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 Oct 12 '20 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 Oct 12 '20 at 14:32
  • @Vlasec answer is correct and using the same token in production. – kamal sehrawat Dec 21 '20 at 17:19
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.

Vladimir Jovanović
  • 2,330
  • 3
  • 13
  • 34
2

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.

Niko Jojo
  • 1,024
  • 2
  • 11
  • 26
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.

wittmason
  • 330
  • 2
  • 5
  • 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 Sep 02 '16 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;
}
Cesar Bielich
  • 4,018
  • 7
  • 33
  • 71
  • 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 Jul 11 '17 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. – Siddhant Rimal Apr 10 '18 at 04: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.

KFunk
  • 2,067
  • 18
  • 30
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

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'.
krsoni
  • 455
  • 6
  • 11
  • Step 4 doesn't seem to work for me. I'm getting "(#100) Tried accessing nonexisting field (access_token) on node type (User)" – breez Jan 23 '21 at 18:49
  • 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 Jan 27 '21 at 07:33
-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.

AymDev
  • 3,440
  • 2
  • 24
  • 42
Bamboomy
  • 2,091
  • 3
  • 20
  • 30