skip to Main Content

I need to be able to post to a user’s business page using the Facebook Javascript SDK.

I have successfully logged my user’s into facebook but when I try to use a function to post to the user’s page, nothing happens. I have even tried to manually enter my own page id into the function to make it work but still nothing happens.

I log my user in using the following javascript which I got from the Facebook documentation and it works.

<script>

  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      testAPI();
    } else {
      // The person is not logged into your app or we are unable to tell.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'my app id',
      cookie     : true,  // enable cookies to allow the server to access 
                          // the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v3.3' // The Graph API version to use for the call
    });

    // Now that we've initialized the JavaScript SDK, we call 
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });

  };

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
        }

    </script>

I then altered the code to add a function called postapi() to test a post to the logged in user’s page as shown below:

<script>
        function postapi() {
            FB.api(
                '/{your-page-id}/feed',
                'POST',
                { "message": "Awesome!" },
                function (response) {
                    // Insert your code here
                });
        }
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      testAPI();
    } else {
      // The person is not logged into your app or we are unable to tell.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'my app id',
      cookie     : true,  // enable cookies to allow the server to access 
                          // the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v3.3' // The Graph API version to use for the call
    });

    // Now that we've initialized the JavaScript SDK, we call 
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });

  };

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
        }

    </script>

I then use a button to open the login dialog and request the proper permissions as follows:

<fb:login-button scope="manage_pages,publish_pages,pages_show_list" onlogin="checkLoginState();">
</fb:login-button>

I successfully tested to see if this actually stored the user’s access token by displaying the user access token in a textbox as follows:

function placetoken() {
            var user_access_token = FB.getAuthResponse()['accessToken'];
            document.getElementById("<%=TextBox1.ClientID%>").value=user_access_token;
        }

I now need to be able to use the user access token to get a list of the pages (including page id and page access token) that the user manages so they can choose one to post to.

I have tried:

var user_pages=FB.api('/me/accounts', 'GET');

But I cannot figure out how to capture what the api returns.

I would like to be able to use the Facebook Javascript SDK to log user’s in and post to their business pages.

2

Answers


  1. Publishing on a page feed requires a page token valid for that specific page incl all required permissions granted by a page admin. Therefore you first need to retrieve a manage_pages permission with login, request a page token (via /me/accounts for example) for that specific page and then make the actual publish feed call.

    Login or Signup to reply.
  2. In order to publish to a Page (as a Page, which is the only option), you need to to the following:

    • Authorize with the manage_pages and publish_pages permissions.
    • Get a Page Token of the Page in question with /page-id?fields=access_token
    • Use the Page Token to post with /me/feed

    Example Request with Page Token:

    FB.api(
        '/me/feed',
        'POST',
        {message: 'Awesome!', access_token: 'the-page-token'},
        function (response) {
            // Insert your code here
        }
    );
    

    Be aware that only users with a role in the App would see the new post, unless you put your App live and get the required permissions reviewed by Facebook.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search