16

I'm new to integrating facebook into the websites I'm working on and trying to get a long term access token by following the instructions here: https://developers.facebook.com/docs/facebook-login/access-tokens/ Even when using the Graph API Explorer here: https://developers.facebook.com/tools/explorer/ I enter the following and populate it with my AppID and AppSecret and current token I get when I press Get Access Token...

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

I get the return

{ "error": "Invalid response" }

Can someone elaborate on what I might be doing wrong, or the steps in greater detail that works for you in acquiring this long term token.

I've tried to follow what's happening in this thread Facebook Page Access Tokens - Do these expire? with no more success. Any help would be greatly appreciated.

Thanks for your time and help. Cheers,

-Ryan

Community
  • 1
  • 1
StafHat
  • 285
  • 1
  • 3
  • 11

5 Answers5

23

You can't get the long-lived user token using the Graph API Explorer. You have to make a GET request to:

https://graph.facebook.com/oauth/access_token?
grant_type=fb_exchange_token&
client_id={app-id}& client_secret={app-secret}& fb_exchange_token={short-lived-token}

You can check it in the browser.

If you need the page access token, you can have a never expiring token. Check out the accepted answer here: What are the Steps to getting a Long Lasting Token For Posting To a Facebook Fan Page from a Server

Ethan
  • 4,295
  • 4
  • 25
  • 44
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
  • Thanks so much! This really wasn't all that different to what I was doing, but for some reason, putting the request directly into the url bar got this working for me. PAge token is the next step, thanks for the extra link! – StafHat Sep 09 '13 at 00:35
  • when i call this from the browser it give me a response , but when i call it using php code it is giving me an error like this: `Error validating access token: Session has expired on Friday, 17-Mar-17 04:38:48 PDT. The current time is Saturday, 10-Jun-17 00:44:35 PDT.` , any solution for this.I want to fetch new token because old token is expired. – chirag satapara Jun 10 '17 at 07:58
  • You can get the `short-lived user access token` from the simple [Login](https://developers.facebook.com/docs/facebook-login) flow. – Sahil Mittal Jun 12 '17 at 07:05
11

So I thought I'd revisit this and provide the documentation I wrote that will hopefully help someone else get this happening!

ONE. Create Application

Create an application associated with the user of the page you want to have access to.

TWO. Get Required Pieces of Info

After creating an App we should have two key pieces of info:

App ID: AAAAA (should be about ~15 characters long)

App Secret: BBBBB (should be about ~32 characters long)

With these by going to https://developers.facebook.com/tools/explorer Making sure to select the correct Application from the Dropdown Box at the top.

Click on Get Access Token and get a ‘fresh’ token.

Here you'll need to select appropriate permissions for your specific app's purpose.

CCCCC (should be ~200 characters long)

THREE. Get Long Life Token (2 Month)

You should then have the pieces of info needed to run the query to get a long-term (2 month) token:

https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={app-id}& client_secret={app-secret}& fb_exchange_token={short-lived-token}

Replace {app-id}, {app-secret} and {short-lived-token} with the three bits of info you’ve taken note of so far.

You should get a request like the following:

https://graph.facebook.com/oauth/access_token?%20grant_type=fb_exchange_token&%20client_id=AAAAA&%20client_secret=BBBBB&%20fb_exchange_token=CCCCC

Place this query into the url bar of an internet browser. You should get a response in the window that looks something like the following:

access_token=DDDDD&expires=5184000

DDDDD (should be ~200 characters long)

FOUR. Test Token (Part 1)

If you enter the highlighted part into the input on the following debug site:

https://developers.facebook.com/tools/debug/

It should give you an expiry of approximately 2 months.

FIVE. Get Non Expiring Page Token

Now taking note of this new long-live-token we’ll use this to get a token that doesn’t expire, unless the associated application is removed from a user’s access or deleted. We use either the page name or preferably page-id when making the request:

You can get your facebook page id using something like http://findmyfacebookid.com/ We'll refer to your page id as EEEEE

https://graph.facebook.com/{page-id}/?fields=access_token&access_token={long-live-token}

You should get a request like the following:

https://graph.facebook.com/EEEEE/?fields=access_token&access_token=DDDDD

This will return something like the following: { "access_token": "FFFFF", "id": "131062838468" }

FFFFF (should be ~200 characters long)

SIX. Test Token (Part 2)

Take the highlighted part and enter it into the debug page and you should get something that shows the token never expires and you’ve been successful in acquiring your never expiring page token.

SEVEN. High Five!

Sorry for the long list of how to achieve this, but I find it better to give the whole process instead of just a small snippet. Let me know if you find this helpful or you have a better way of achieving any of the steps.

StafHat
  • 285
  • 1
  • 3
  • 11
  • Hi @Ryan, this doesn't work. the application created does posts to facebook but only page-admins can see its posts. – YSY Oct 12 '15 at 11:39
1

Facebook PHP SDK has already implemented method to get long-lived token using short-lived token, after login successfully and got the short-lived token, simple calling

$result = $facebook->setExtendedAccessToken();

if $result is null, it means you got the long-lived access token.

Hieu Vo
  • 3,105
  • 30
  • 31
0

client side

        if (response.status === 'connected') {
            {
                event.preventDefault();
                FB.login(function (response) {
                    if (response.authResponse) {
                        var profileId = response.authResponse.userID;
                        var accessToken = response.authResponse.accessToken;
                        var e = response.authResponse.accessToken;
                        document.getElementById('token').innerHTML = e;
                        var profileName = "";
                        var pagesList = "";
                        var isPage = 0;
                        var type = "fb";
                        $.ajax({
                            url: "WebService1.asmx/getlonToken",
                            type: "POST",
                            dataType: 'json',
                            data: '{accessToken:"' + accessToken + '"}',
                            contentType: "application/json; charset=utf-8",
                            async: true,
                            success: function (response) {
                                accessToken = response.d;
                                document.getElementById('status').innerHTML = accessToken;
                            },
                            error: function (e) {
                                alert('Error' + e);
                            }
                        });



                    }
                }, { scope: 'user_about_me,friends_about_me,user_activities,friends_activities,user_birthday,friends_birthday,user_education_history,friends_education_history,user_events,friends_events,user_groups,friends_groups,user_hometown,friends_hometown,user_interests,friends_interests,user_likes,friends_likes,user_location,friends_location,user_notes,friends_notes,user_photos,friends_photos,user_relationships,friends_relationships,user_relationship_details,friends_relationship_details,user_status,friends_status,user_videos,friends_videos,user_website,friends_website,email,manage_pages,publish_stream,read_stream,read_page_mailboxes,read_insights, read_mailbox' });

            }

Server side

   [WebMethod]
    public string getlonToken(string accessToken)
    {
        var fb = new FacebookClient(accessToken);
        dynamic result = fb.Get("oauth/access_token", new
            {
                client_id = 123,
                client_secret = "123fff45",
                grant_type = "fb_exchange_token",
                fb_exchange_token = accessToken,
                scope = "user_about_me,friends_about_me,user_activities,friends_activities,user_birthday,friends_birthday,user_checkins,friends_checkins,user_education_history,friends_education_history,user_events,friends_events,user_groups,friends_groups,user_hometown,friends_hometown,user_interests,friends_interests,user_likes,friends_likes,user_location,friends_location,user_notes,friends_notes,user_photos,friends_photos,user_relationships,friends_relationships,user_relationship_details,friends_relationship_details,user_religion_politics,friends_religion_politics,user_status,friends_status,user_videos,friends_videos,user_website,friends_website,email,manage_pages,publish_stream,read_stream,read_page_mailboxes,read_insights,ads_management"
            });

        fb.AccessToken = (string)result["access_token"];
        return fb.AccessToken;
    }
}
nouman arshad
  • 453
  • 5
  • 15
0

You can generate Short-Lived Token from Graph API Explorer.

Then you can extend it in Long-Lived Token from Access Token Debugger. I do this every time.

Access Token Debugger

Stefan Pavlov
  • 398
  • 2
  • 8