Facebook PHP SDK: getting “long-lived” access toke

2020-05-15 04:39发布

问题:

BASIC PROBLEM: I want my app to be able to make calls to the Facebook graph api about authorized users even while the user is away.

For example, I want the user (A) to authorize the app, then later I want user (B) to be able to use the app to view info about user (A)'s friends. Specifically: the "work" field. Yes, I am requesting those extended permissions (user_work_history, friends_work_history, etc). Currently my app has access to the logged-in user's friends work history, but not to any of the friends' work history of other users of the app.

Here's what I know already:

  • Adding offline_access to the scope parameter is the old way and it no longer works.
  • The new way is with "long-lived" access tokens, described here. These last for 60 days.
  • I need to exchange a normal access token to get the new extended token. The FB documentation says:

    https://graph.facebook.com/oauth/access_token?
    client_id=APP_ID& client_secret=APP_SECRET& grant_type=fb_exchange_token& fb_exchange_token=EXISTING_ACCESS_TOKEN

Here's what I don't know (and I'm hoping you can tell me): How do I get the extended (aka "long-lived") access token using the Facebook PHP SDK? Currently, my code looks like this:

$facebook->getAccessToken();

Is there such a thing as this?:

$facebook->getExtendedAccessToken();

If not, is this what I should be doing?

$accessToken = $facebook->getAccessToken();
$extendedAccessToken = file_get_contents("https://graph.facebook.com/oauth/access_token?             
    client_id={$appId}&
    client_secret={$secret}&
    grant_type=fb_exchange_token&
    fb_exchange_token={$accessToken}"
    );

I've tried it and it doesn't work. I get this error:

Warning: file_get_contents(https://graph.facebook.com/oauth/access_token? client_id=#######& client_secret=#########& grant_type=fb_exchange_token& fb_exchange_token=##########) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /...

Does it work any differently if I switch to FQL instead of the graph api? I've read through the Facebook documentation many times, but the PHP sdk is not thoroughly documented and I can't find any examples of how this should work.

回答1:

I finally figured this out on my own. The answer is pretty anti-climactic. It appears that newly created apps get 60 day access tokens automatically. I'm not sure if this is dependent on enabling the "depricate offline_access" setting in the Migrations section of the app settings. Leave it on to be safe.

So at the time of writing this, you can use the PHP SDK as follows: $facebook->getAccessToken();

(The reason my app wasn't working as expected was unrelated to the expiration of the access token.)

Just one more thing, to get long-lived access token using PHP SDK you should call $facebook->setExtendedAccessToken(); before $facebook->getAccessToken();



回答2:

In the last Facebook PHP SDK 3.2.0 you have a new function setExtendedAccessToken() that you have to call before getAccessToken();

Like this:

$user = $facebook->getUser(); 
$facebook->setExtendedAccessToken(); //long-live access_token 60 days
$access_token = $facebook->getAccessToken();


回答3:

Actually newly created apps only get a 60 day access token automatically if you are using a server side call. If you are using the client-side endpoint as shown above in the question, even new apps will still receive a short-term token initially. see: https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal/

I had the same HTTP/1.1 400 Bad Request error that you had when using the New Endpoint and the problem was if you copy the code Facebook gives you exactly and paste it into your app, there are actually spaces in between the params, meaning there's unnecessary spaces in the url and it won't get called correctly when passed into file_get_contents() even though it works okay when pasted in the browser. This took me way too long to figure out. Hope this helps somebody! Here is my complete working code to get the extended access token out of the new endpoint (replace x's with your values):

$extend_url = "https://graph.facebook.com/oauth/access_token?client_id=xxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxxxxxxxx&grant_type=fb_exchange_token&fb_exchange_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

$resp = file_get_contents($extend_url);

parse_str($resp,$output);

$extended_token = $output['access_token'];

echo $extended_token;


回答4:

The selected answer is now outdated. Here are Facebook's instructions to swap a short-term token (provided in front-end) for a long-term token (server only):

https://developers.facebook.com/docs/facebook-login/access-tokens/refreshing/

Generate a Long-lived User or Page Access Token
You will need the following:

A valid User or Page Access Token
Your App ID
Your App Secret
Query the GET oath/access_token endpoint.

curl -i -X GET "https://graph.facebook.com/{graph-api-version}/oauth/access_token?  
    grant_type=fb_exchange_token           
    client_id={app-id}&
    client_secret={app-secret}&
    fb_exchange_token={your-access-token}" 

Sample Response
{
  "access_token":"{long-lived-access-token}",
  "token_type": "bearer",
  "expires_in": 5183944            //The number of seconds until the token expires
}