Search code examples
facebookfacebook-graph-apifacebook-oauth

Facebook insights via graph.facebook.com authentication flow


I am trying to programatically grab a few insights metrics from facebook for various pages (about 50 clients). Therefore I want to automate this.

I created a facebook app and have my app_id and app_secret. I also created a app_access_token which doesn't expire?

My question is this: How do I get the page access token for each of the pages I want to get insights from? Currently I...

STEP 1) ...went to the Query Explorer and seleted my app and grabbed a user_access token with the manage_pages and read_insights permissions.

STEP 2) I then used that user_access_token to go to https://graph.facebook.com/v2.5/{pagename}?fields=access_token&access_token={user_access_token} to get what I presume is the page_access_token.

STEP 3) I then use this token to do my queries for things like https://graph.facebook.com/v2.5/{pagename}/insights/page_impressions?access_token={page_access_token}.

Now since the app is already OKAYed, shouldn't be there a way to grab that user_access_token in step 1 programatically? They all expire except the app_access_token I described above. Can I use that token somehow in step 1?

I am not using and SDKs just pure https calls.


Solution

  • Actually it is possible. I managed to get an extended page access token by doing this:

    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]
    

    from here. Basically you get a short lived user token and then use that to get a page access token and then use that with your app id/secret to get an extended page token that never expires (perfect for embedding in an automated reporting app).

    It is convoluted but it works. And as a bonus if you register the APP on Facebook business manager, that page token will work on all sites you have access to under that business manager account.