Search code examples
facebookfacebook-fqlfacebook-authentication

How to get a token to access one of my facebook pages


So here's the deal, I'm learning how to work with facebook api, and I'm having some difficulties trying to understand it, the documentation isn't at all organized imho.

So I'm getting this error "Impersonated access tokens can only be used with the Graph API"

And I think it's because I copied the token from the graph API explorer.

My main purpose with this project is to have a normal website, that fetches some data of my facebook page(albums, photos and events) and display it on the website as page content. It's like the facebook page is the backoffice.

How can I solve this?

Here's a real example, of what I'm trying to accomplish: http://codecanyon.net/item/facebook-album-gallery/full_screen_preview/400462


Solution

  • I agree that FB documentation is to be nice..."unorganized".

    Regardless there are a few steps required to get the access tokens.. copying from FB explorer wont work.

    1. Register an FB app
    2. Use the FB app ID and secret key to create a .php page (for example) to get a user to give you specifically requested permissions
    3. When the user completes the request for permissions, FB will redirect the user to your specified callback and append an access_token to the URL
    4. parse that token, and store it somewhere
    5. use that access_token to get the data off the API that you want
    6. If the access_token is permanent then you can use the stored token for later to get more data offline.

    I modified the example code as follows to create the apps permissions grabbers:

    $app_id = "myappid";
    $app_secret = "mysecret";
    $my_url = "http://mycallbackurl";
    session_start();
    $code = $_REQUEST["code"];
    (empty($code)) {
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
     $dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
       . $app_id . "&redirect_uri=" . $my_url 
       . "&scope=offline_access,manage_pages,read_stream,read_insights,export_stream,read_friendlists";
    
      }else{
    
      $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;
    
      $response = file_get_contents($token_url);
      $params = null;
      parse_str($response, $params);
    
      $graph_url = "https://graph.facebook.com/me?access_token="
       . $params['access_token'];
    
     $user = json_decode(file_get_contents($graph_url));
     $at = $params['access_token'];
     $uid = $user->id;
     $un = $user->name;
    
     ...and so on