Search code examples
phpfacebookfacebook-graph-apifacebook-php-sdkfacebook-access-token

Getting an access token for a local Facebook script


I will start this question by mentioning that this is my first experience with Facebook's API.

I have a script on my own PC, which is executed with WAMP. It fetches data from Facebook's Graph API, when given manually an access token from Graph API Explorer, getting a specific group's feed.

I would like my script to ask for an access token, and then just use file_get_contents to ask for the json string. I need the access token to have all the permissions available.

What should I do to make the next steps work?

  1. Open my PHP file. (already exists)
  2. The script will ask for an access token.
  3. It will print the content of https://graph.facebook.com/GROUP_ID/feed?=access_token=ACCESS_TOKEN

Solution

    1. If you are developing a facebook app, you don't need to login to facebook again. (Code snippets for both PHP and Javascript, use that is required to you.)

      [PHP]

      You can get the access_token by performing Http GET request on -

      https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials
      

      For more details: login as app

      [Javascript]

      FB.getLoginStatus(function(response) 
      {
        if (response.status === 'connected') 
        {
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
        } 
        else if (response.status === 'not_authorized') 
        {
           // the user is logged in to Facebook, 
           // but has not authenticated your app
        } 
        else 
        {
           // the user isn't logged in to Facebook.
        }
      });
      

      For more details: getLoginStatus

    2. If you are integrating fb with your website, you need to login first and in the response you can obtain the access token.

      Read this: Login Architecture

      [PHP] (Difficulty: High)

      Read this: server-side-login

      [Javascript] (Dfifficulty: Low)

      FB.login(function(response) 
      {
          if (response.authResponse)
          {
              console.log('Welcome!  Fetching your information.... ');
              var access_token = response.authResponse.accessToken;
          } 
          else 
          {
              console.log('User cancelled login or did not fully authorize.');
          }
       }); 
      

      More details: FB.Login