DEV Community

Davide Santangelo
Davide Santangelo

Posted on • Updated on

Permanent Facebook page access token

At Chorally among other sources we also integrate Facebook and this is a little ruby script to get a Facebook page permanent token.

Use Graph API Explorer for all of these steps except where otherwise stated.

Create Facebook App

If you already have an app, skip this step.

Go to My Apps.
Click "+ Add a New App".
Setup a website app.
Enter fullscreen mode Exit fullscreen mode

You don't need to change its permissions or anything. You just need an app that won't go away before you're done with your access token.

Get User Short-Lived Access Token

Go to the Graph API Explorer.

Select the application you want to get the access token for (in the "Application" drop-down menu, not the "My Apps" menu).

Click "Get Token" > "Get User Access Token".

In the pop-up, under the "Extended Permissions" tab, check "manage_pages".
Click "Get Access Token".
Enter fullscreen mode Exit fullscreen mode

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 user access token.

  API_URL = "https://graph.facebook.com/v3.0"

  # 1 Generate Long-Lived Access Token
  response = RestClient.get("#{API_URL}/oauth/access_token?grant_type=fb_exchange_token&client_id=#{client_id}&client_secret=#{client_secret}&fb_exchange_token=#{user_access_token}")
  access_token = JSON.parse(response.body)['access_token']

  # 2 Get User ID
  response = RestClient.get("#{API_URL}/me?access_token=#{access_token}")
  id = JSON.parse(response.body)['id']

  # 3 Get Permanent Page Access Token
  response = RestClient.get("#{API_URL}/#{id}/accounts?access_token=#{access_token}")

  # 4 Array of items the user has access to
  JSON.parse(response.body)['data']

Enter fullscreen mode Exit fullscreen mode

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

Latest comments (3)

Collapse
 
fahimxyz profile image
Fahim R.

And you can use my this simple tools also for page access token ;)

Facebook Page Access Token: fahimxyz.github.io/fb-page-token/

Collapse
 
caiodomingos profile image
Caio-Domingos

If my data arrays is empty, what does that mean?

Collapse
 
dewitte profile image
@dewitte

Thank you - this was very helpful. I was lost in so many different FB access pages and this took me right where I needed to be.