Vishaal Kalwani
Vishaal Kalwani

Reputation: 740

Server-to-server Facebook Access Token expires

I am building an Integration that allows users to schedule creation of Custom Audiences on the Facebook Ads platform. Once the user authenticates, we pass the client side token to the server from the client and then exchange their short lived token with the ads_management permission for a long-lived token, but that token only lasts 60 days?

The idea of the integration is that the user can set it and forget it (but disconnect any time). Now it seems like they need to visit the app at least once every 60 days. Is there any way around this? In my app, the person who turns on the Integration might not necessarily visit the app, or could leave the company and the integration would then break in 60 days.

Upvotes: 0

Views: 282

Answers (2)

Thomas Rückert
Thomas Rückert

Reputation: 106

Just like Michael Hirschler said in his answer, you can simply use the old (non-expired) access token to fetch a new one. You should save the expiry date returned on every request when getting an access token: (This property is called expires_in)

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

When expiration date is almost reached, you can use the same api endpoint for that with some changed query params. Insert your old access token as the user-access-token.

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={user-access-token}" 

As you can see, you will also need your app-id and app-secret for doing so.

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

Upvotes: 1

Michael Hirschler
Michael Hirschler

Reputation: 2518

You can simply ask Facebook for a new access token by passing your current access token.

It's as easy as exchanging the long-lived token, just re-call the same operation (using the current long-lived token). You will get a new one.

I suggest doing so some days before it expires (say, 10 days). This will ensure your system is going to have a spare time if any error occurs (e.g. Facebook's server down, User rejected permissions on your app, ...).

Upvotes: 1

Related Questions