Facebook access token shenanigans


Using facebook access tokens to make app that can post to your pages automatically.

  1. Create a facebook app
  2. In settings of said app (via “mange apps” on left hand side), click on the app, make sure it’s turned on/status is live.
  3. Optionally, add a dummy fb account as developer of your app, and have him use the app to post stuff to pages, so that if someone complains about things you automatically post (e.g. copyright), it doesn’t affect your main account.
    1. If you use this dummy fb account, then obviously also add him as Editor to the pages you want him posting to.
  4. Go to facebook’s Graph API Explorer:  https://developers.facebook.com/tools/explorer/ . In upper right hand corner’s drop down, select your aforementioned app.  Then in the dropdown under it, select “Get User Access token.”  In popup, select the manage_pages and publish_pages scopes, and click “Get Access Token.”  This token allows app to act on this user’s behalf.
    1. From this point forward, you can go to https://developers.facebook.com/tools/accesstoken/ to get the user token, as you already logged in to (granted) your app with the manage_pages and publish_pages scopes.  i.e. the access token debugger (step 5 below) will show you the manage_pages and publish_pages scopes.
  5. Go to Facebook’s access token debugger https://developers.facebook.com/tools/debug/accesstoken/, paste in User Access token from step 4, It’ll show you info on this token, including expiration date/time (1 hour-ish).  Click “Extend Access Token” button below. It’ll give you a new token, and you can paste this into the access token debugger.  It should say Expration is NEVER.  😀
  6. (I think this is no longer necessary given step 5):  use token from step 4 (5?) to get  Extended User Token (expires in 60 days? never?).  You can get the client_secret and client_id from your app’s setting:  https://graph.facebook.com/oauth/access_token?client_id=<client_id>&client_secret=<client_secret>&grant_type=fb_exchange_token&scope=publish_stream,publish_actions,manage_pages&fb_exchange_token=<token from step 4>
  7. Now call graph.facebook.com/me/accounts with the Extended User Token to get Extended Page Tokens.  i.e. it’ll give you a page with access tokens for everything (pages, etc) under your account:
  8. https://graph.facebook.com/me/accounts?access_token=<token from step 5/6)

  9. Then something like this:

    $data[link] = $link;

    $data[picture] =$img;

    $data[caption] = $desc;

    $data[message] =[Click for price!!] . $desc;

    $data[description] = $desc;

    $data[access_token] = $page_access_token;

    $post_url =https://graph.facebook.com/.$page_id./feed‘;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $post_url);

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $return = curl_exec($ch);

    curl_close($ch);