Generate "never-expire" access token for Facebook Page

Facebook

Facebook Problem Overview


I have managed to post to Facebook Page via API (C#), but when administrator of the page logs out, the following error occurs:

"(OAuthException - #190) Error validating access token: The session is invalid because the user logged out."

How do I generate access token which is never expired?

I need a solution that doesn't open Facebook Login dialog.

Facebook Solutions


Solution 1 - Facebook

You can generate never expiring access token without coding, following this instructions:

  1. Open graph Explorer: https://developers.facebook.com/tools/explorer/.
  2. Choose your application from the right corner dropdown.
  3. From "Get Token" dropdown choose your Fan Page.
  4. Click on submit button to generate token.
  5. From the left side on "Search for a field" enter access_token and click submit again. Copy this token from the main window.
  6. Open https://developers.facebook.com/tools/debug/accesstoken and paste token here. Click "Debug".
  7. Click the button "Extend Access Token". This will generate never expiring token.

Solution 2 - Facebook

This is the code that I use to generate "Never" expire access token using PHP SDK:

$facebook = new \Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.10',
  'default_access_token' => '{access-token}'
]);

// Exchange token
$token = $facebook->post('/oauth/access_token',
    array(  
        'grant_type' => 'fb_exchange_token',           
        'client_id' => 'APP ID',
        'client_secret' => 'APP Secret',
        'fb_exchange_token' => 'access Token'
    )
);
$token = $token->getDecodedBody();
$token = $token['access_token'];

echo $token;

I echo the access token and then debug it using the access token debugger. The result should be: Expires: Never.

References from the Documentation:

Solution 3 - Facebook

  1. Generate long-lived token for admin of the fan page http://appdevresources.blogspot.sg/2012/11/extend-facebook-access-token-make-it.html (nice explanation with images)
  2. Generate long-lived token for fan page itself http://appdevresources.blogspot.sg/2012/11/retrieving-facebook-page-id-and.html
  3. Use token from 2) to post on the fan page's wall (no need for Facebook Login dialog)
  4. Resulted token will never expire (even if administrator of the fan page did log out)

Solution 4 - Facebook

You can use following api from facebook to refresh token life to 60 days and just when the token is about to expire, call the same api again with-in 60 days to refresh its life back to 60 days from that point of time Token expire is present in expires parameter and its value is in seconds

Replace CLIENT_ID and CLIENT_SECRET with their actual value

https://graph.facebook.com/oauth/access_token?client_id=<CLIENT_ID>
&client_secret=<CLIENT_SECRET>&grant_type=fb_exchange_token
&fb_exchange_token=<ACCESS_TOKEN>

in ACCESS_TOKEN, put the actual token value without appending "access_token="

Solution 5 - Facebook

  1. Create an app if you don't have - https://developers.facebook.com/
  2. Create a short lived user access token in the Graph Explorer - https://developers.facebook.com/tools/explorer/

Select your app created above and select “Get user access token in the drop down”

In the user access token pop up you can select some permissions for the token. For an non expiry page access token you need to select "publish pages" and "manage pages"

  1. Create long lived user access token

Go to https://developers.facebook.com/tools/accesstoken/. There you will find short lived user access tokens and app access token of all the apps you have

Press debug option of user access token of the app created above. This will take you to the debug tool. Where you can find all the information of short lived user access token.

In the bottom there is option to generate long lived(60 days) user access token for this short lived user access token. Generate long lived user access token by selecting “Extend Access Token”

  1. Create never expired page access token

a. Go to the Graph Explorer - https://developers.facebook.com/tools/explorer/.

b. Paste the long lived user access token generated in previous step inside “Access token” field.

c. Access “/me?fields=access_token” api . This will result page access tokens and pages related to them. These page access tokens will never expire(until user change the password/user revoke the app)

  1. Verify non expiry page access token

a. Go to https://developers.facebook.com/tools/debug/accesstoken/

b. Add the page access token retrieved from above step into “Access token “ field and debug

You will get expires as Never

Found here with little changes: https://medium.com/@Jenananthan/how-to-create-non-expiry-facebook-page-token-6505c642d0b1

Solution 6 - Facebook

It's November 2018 and this worked for me!

<?php
$args=[
    'usertoken'=>'xxx',
    'appid'=>'xxx',
    'appsecret'=>'xxx',
    'pageid'=>'xxx'
];
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;
}
echo "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']}";
echo '<br><br>Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';

Never Expire from FB Debug

Solution 7 - Facebook

The accepted answer is no longer correct. This works now.

Open graph Explorer: https://developers.facebook.com

  • Login and choose your application from the right corner dropdown
  • Once logged in click Tools & Support icon in top right corner
  • Then choose Access Token Tool link on the right side beneath your applications name

To the right of the displayed user token > click [Debug] button

This will have taken you to the Access Token Debugger

  • Click the blue button at the bottom that says Extend Access Token
  • This will say: This new long-lived access token will never expire
  • Copy and paste that token into your application ie; EAAYMFDuobYUBADtYjVDukwBGpwPHOCY0iYglYY3j3r200MzyBZB4.....

Solution 8 - Facebook

You need to get a user access token by FB.login() with manage_pages, pages_show_list and others in scope permissions. Then, execute FB.api("/{user-app-id}/accounts", fields: ...) to get a list of pages with their respectively info, including access_token. Here, you get a short-lived-token, but with this token you can extend its expiration time to "Never".

FB.login(function (response){
  if(response.status!=="connected"){
    return;
  }        
  FB.api('/'+USER_APP_ID+'/accounts',{fields: 'id, name, access_token,category, picture'}, 
   function(d){
    console.log(d) // Here you get access_token (short-lived-token)
  });
},{scope: 'manage_pages, pages_show_list', auth_type: 'rerequest'});

With the last access token and from server side, you make a call to API Graph, using App ID and App Secret of the App you use to get permissions to manage the page.

GET /oauth/access_token?  
grant_type=fb_exchange_token&           
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={short-lived-token} 

The response gives you an access token with expiration time in "Never".

References: API Graph Accounts, Expiration and Extends Access Tokens

Solution 9 - Facebook

The method below worked for me, if you are using 4.x Facebook SDK:

  1. Create the Temporary User Access Token for the first time using the method mentioned here.
  2. Now! It's time to convert this token to Long Term Token using PHP SDK 4.x. Use the following code as it worked for me:

//Class for Generating the Long Lived Token

namespace App\Lib;

use Facebook\FacebookApp;
use Facebook\FacebookClient;
use Facebook\Authentication\OAuth2Client;

class FacebookLongLivedTokenGenerator
{
    public $longLivedTokenGenerated = false;

    public function generateFacebookLongLivedToken($appId, $appSecret, $oldToken)
    {
        //request new access token
        $oauth2Fb = new OAuth2Client(new FacebookApp($appId, $appSecret), new FacebookClient());
        $longLivedToken = $oauth2Fb->getLongLivedAccessToken($oldToken);
        if ($longLivedToken) {
            $this->longLivedTokenGenerated = true;
            $this->userAccessToken = $longLivedToken;
        }
        return trim($this->userAccessToken);
    }
}

You can consume the above class this way:

$longToken = new FacebookLongLivedTokenGenerator();
echo $longToken->generateFacebookLongLivedToken($appId, $appSecret, $oldUserAccessToken);

Solution 10 - Facebook

this Makefile works as of 2015-10-29. steps 2 and 3 give only a two-month token, but the page access token given in the final step shows in the https://developers.facebook.com/tools/debug/">debugger</a> as "Expires: Never". this answer draws upon the work of several others, and is provided in the hopes that it will simplify things for developers regardless of preferred programming language.

before using this, you need to put your existing page ID, app ID, and app secret, in that order, in your ~/.netrc file as follows: machine graph.facebook.com login 123456 account 234567 password 345678

also before using this, login to Facebook with w3m, clicking "Keep me logged in".

MACHINE := graph.facebook.com
PAGE_ID := $(shell awk '$$2 ~ /^$(MACHINE)$$/ {print $$4}' $(HOME)/.netrc)
APP_ID := $(shell awk '$$2 ~ /^$(MACHINE)$$/ {print $$6}' $(HOME)/.netrc)
APP_SECRET := $(shell awk '$$2 ~ /^$(MACHINE)$$/ {print $$8}' $(HOME)/.netrc)
PERMISSIONS := manage_pages,publish_actions,publish_pages
FB := https://www.facebook.com
GRAPH := https://$(MACHINE)
CODE ?=
TOKEN ?=
TWOMONTHTOKEN ?=
BROWSER ?= w3m -dump
REDIRECT := http://jc.unternet.net/test.cgi
CLIENT_SIDE := $(FB)/dialog/oauth?client_id=$(APP_ID)&redirect_uri=$(REDIRECT)
CLIENT_SIDE := $(CLIENT_SIDE)&scope=$(PERMISSIONS)&response_type=code
SERVER_SIDE := $(GRAPH)/oauth/access_token?client_id=$(APP_ID)
SERVER_SIDE := $(SERVER_SIDE)&redirect_uri=$(REDIRECT)
SERVER_SIDE := $(SERVER_SIDE)&client_secret=$(APP_SECRET)&code=$(CODE)
LONG_LIVED := $(GRAPH)/oauth/access_token?client_id=$(APP_ID)
LONG_LIVED := $(LONG_LIVED)&client_secret=$(APP_SECRET)
LONG_LIVED := $(LONG_LIVED)&grant_type=fb_exchange_token
LONG_LIVED := $(LONG_LIVED)&fb_exchange_token=$(TOKEN)
ACCOUNTS := $(GRAPH)/me/accounts?access_token=$(TWOMONTHTOKEN)
export
env:
	env
	@echo Usage: make code
	@echo '        ' make CODE=codefrompreviousstep token
	@echo '        ' make TOKEN=tokenfrompreviousstep longterm
	@echo '        ' make TWOMONTHTOKEN=tokenfrompreviousstep accounts
	@echo Then edit '$$HOME/.netrc' replacing password with page token
code:
	$(BROWSER) "$(CLIENT_SIDE)"
token:
	$(BROWSER) "$(SERVER_SIDE)"
longterm:
	$(BROWSER) "$(LONG_LIVED)"
accounts:
	$(BROWSER) $(ACCOUNTS)

it turns out in many cases the first step fails with w3m. in that case, install another browser such as firefox; ssh -X to your server if the script is remotely hosted; and use make BROWSER=firefox code instead. the following steps should work with w3m as shown.

note: if cutting-and-pasting this Makefile, make sure to replace the 4-space indentations with proper tabs.

Solution 11 - Facebook

Using Facebook API v3.1 - None of the answers above worked for me. Instead, I had to:

  1. Create a "system user"

  2. Grant him access to the properties I needed (in my case an App)

  3. Generate a new token for that app and system user

The instructions I used can be found here

Solution 12 - Facebook

podrias intentar algo como esto

Administrar Paginas
<a href="#" class="btn" onclick="token_live()" >url</a>

							<script type="text/javascript">
								function token_live(){
									var token_app = "";
									$.ajax({
										url: "https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id=598062314053459&client_secret='client_secret'&fb_exchange_token=access_token",
										type: 'POST',
										dataType: 'HTML',
										data: {api_public: 'AP-42b3a8aab70',
										},
									})
									.done(function(data) {
					
			var txt = data
var obj = JSON.parse(txt);

	var token_live = obj.access_token

var url_infinit = "https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id='remplaza_cliente_id'&client_secret='client_secret'&fb_exchange_token="+token_live;

alert(url_infinit);

```

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIvan StudenikinView Question on Stackoverflow
Solution 1 - FacebookMile JanevView Answer on Stackoverflow
Solution 2 - FacebookAriView Answer on Stackoverflow
Solution 3 - FacebookIvan StudenikinView Answer on Stackoverflow
Solution 4 - FacebookHarsh GuptaView Answer on Stackoverflow
Solution 5 - FacebookMadiddltaView Answer on Stackoverflow
Solution 6 - FacebookDazzaView Answer on Stackoverflow
Solution 7 - FacebookJay LeporeView Answer on Stackoverflow
Solution 8 - FacebookHarry MartelView Answer on Stackoverflow
Solution 9 - FacebookImran ZahoorView Answer on Stackoverflow
Solution 10 - Facebookjcomeau_ictxView Answer on Stackoverflow
Solution 11 - FacebookGuyView Answer on Stackoverflow
Solution 12 - Facebookuser9186623View Answer on Stackoverflow