简体   繁体   中英

Reading a Facebook personal page posts

I'm working on a feature on our website to display my company's Facebook page posts on our Intranet site. I found this code and am having trouble.

<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '<ourappid',
      xfbml      : true,
      version    : 'v2.8'
    });

    FB.AppEvents.logPageView();

    FB.login(function (response) {
      if (response.authResponse) {
          //alert("You are logged in");
          FB.api('/ourpageurl/feed', function(response) {
            console.log("response",response);
          })
      } else {
        alert("Login attempt failed!");
      }
    }, { scope: 'public_profile' });
  };

  (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 = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

I do not control our company's Facebook page. Our social media director provided me with the app id. When I run the code above on a browser where I have not logged into Facebook with my username, I get a pop up window asking for my Facebook credentials. When I run this on a browser where I have an active Facebook session, the code does nothing. Nothing inside the login callback function is executed.

I've also tried skipping the FB.login portion and just running

      FB.api('/ourpageurl/feed', function(response) {
        console.log("response",response);
      })

immediately after FB.AppEvents.logPageView(); , but I get an error object back complaining about an access token. As far as I've been able to tell, in order to get an access token, I have to run the login method. What am I doing wrong here?

First of all: You can only call FB.login on user interaction, or browsers will block the popup. If done correctly, FB.login opens a popup where you can authorize the App with your user account.

I assume that is not what you want. For getting the feed of an unrestricted Page, you can use an App Access Token - it is the only Token that does not need user authorization. Access Tokens are meant to be kept secret, so you need to do that API call on your server, NOT on the client with JavaScript. You also need to think about caching the result, if a lot of users hit the Page where you read/show the feed, you may hit an API limit on Facebook.

About Tokens in general:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM