How to connect to the Facebook Graph API from Google Apps Script?
Asked Answered
P

1

7

I'm trying to connect to the Facebook Graph API via a Google Apps Script but I'm getting an error

I've tried:

function myFunction (name) {

  FB.init({  
    appId      : '{your-app-id}',  
    status     : true,  
    xfbml      : true,  
    version    : 'v2.0'   
  });  

  var jsonData = UrlFetchApp.fetch("graph.facebook.com/"; + name);
}

I've also tried:

function myFuntion(name) {  

    window.fbAsyncInit = function() {  
        FB.init({  
          appId      : 'your-app-id',  
          xfbml      : true,  
          version    : 'v2.0'  
        });  
      };   

      var jsonData = UrlFetchApp.fetch("graph.facebook.com/"; + name);

}

but neither have worked, I always get a:

"ReferenceError: "FB" is not defined." and a "ReferenceError: "window" is not defined"
and
"(#4) Application request limit reached","type":"OAuthException","code":4}}

despite putting in my facebook app ID into the variable. I know that "window" is part of an external javascript library so that's why I'm unable to use it in a Google Apps Script, but even after looking at other posts I'm still confused on why I get a "FB" is not defined error.

Any ideas on how to solve this?

Portauprince answered 17/2, 2015 at 6:21 Comment(7)
Could you put more of your code up?Plaintive
This answer may help you: StackOverflow answer - Facebook with Apps ScriptBalthazar
What do you eventually want to do? Post to your FB page? Post to someone else's page? Allow others to post to your page? Depending on what you want to do, will depend what authorization you need.Balthazar
i want to get data from a FB page by returning the json of a FB page. For example, getting json from the NBA facebook page - graph.facebook.com/nbaPortauprince
Okay, I just used the API Explorer to get that data: Facebook API Explorer Now I know what you want.Balthazar
what is the method and url for the API explorer i would use to get that data if i don't know the id of the facebook page? i cannot be using FB.api because FB is not definedPortauprince
Let us continue this discussion in chat.Balthazar
B
9

There are error codes at the bottom of this page:

Facebook Graph API - Error codes

The "OAuthException" has to do with the Login Status. If you get that error, then you aren't logged in, and to get what you want, you need to be logged in.

You can get an App Access Token using a Server to Server request. There are four types of

Access Tokens:

  • User - to read, modify or write a specific person's Facebook data on their behalf.
  • App - modify and read the app settings, and publish Open Graph actions.
  • Page - read, write or modify the data belonging to a Facebook Page.
  • Client - the client token is used rarely. Very limited Access to Facebook.

Forms of Access Tokens

User access tokens come in two forms: short-lived tokens and long-lived tokens

  • short-lived - lifetime of about an hour or two - generated via web login
  • long-lived - lifetime of about 60 days

You probably don't have an App Access Token. You have an App ID, but that's different than an App Token.

You only get your App Token once. You need to run some code to get it.

Note, that you also must know your App Secret in order to run this code. If you don't know, or have your App Secret, then you need to get that.

See if you can run this code:

//A Facebook App Token never changes unless you go to the Facebook Developers Console, 
//and you
//change the App Secret.  So, do NOT keep requesting a new App Token.  Just get it once, 
//then
//hard code it into a backend secret function.
// The App Token can be used to modify your App, but you can just do that 'Manually'

function getOneTimeFB_AppToken() {
  Logger.log("getOneTimeFB_AppToken ran");
  //keep this info secret
  //Generate an App Access Token

  var myApp_ID = 'Your App ID';
  var myAppSecret = 'Your App Secret';
  var optnAppTkn = {"method" : "get"};
  var getAppTknURL = "https://graph.facebook.com/oauth/access_token?client_id=" + myApp_ID + "&client_secret=" + myAppSecret + "&grant_type=client_credentials"
  var getAppTkn = UrlFetchApp.fetch(getAppTknURL, optnAppTkn);
  Logger.log("Object returned from GET: " + getAppTkn)
  var myAppTkn = getAppTkn.getContentText();
  Logger.log("myAppTkn: " + myAppTkn);
};

Run that code, then in the script editor, choose the VIEW menu, and the LOGS menu item. Read what is in the LOGS. Don't keep running this code over and over again. Just run it once if it's successful.

If that code works, then you just successfully communicated with Facebook.

You need to understand what the Tokens can do, and what your options are. If you are not going to get a token from a user through client side authorization, then you need to understand the App Token.

App Tokens allow you to interact with Facebook on behalf of an app rather than a user. This can be used to read YOUR app insights and modify the parameters of YOUR app.

You never want to use an App Token in client side (browser) code. That would be a major security problem.

However, if a user has granted your application publishing permissions, then you can use the App Token to publish content to Facebook on behalf of that person. So, app access token can be used in place of a user access token to make API calls IF your app has been granted publishing permissions.

But how do you get publishing permissions? Well, there is no way to get the initial short term access token through the server. That just makes sense if you think about it in terms of security. You can't get the initial, short term access token any other way than through a client login. So, if you want to do something that isn't within the bounds of the App Access Token, you can't do it without having the user login through client side.

You can achieve a client side login, without using the JavaScript SDK. So, in the case of an Apps Script Stand Alone HTML web app, you can still use Facebook login without needing to link to the Facebook JavaScript SDK. If you need to do that, let me know.

In that code, FB is an object. The object needs to be assigned "key/value" pairs. Every "key/value" pair is an element (property) in the object. The error is directly related to how objects work. That FB object gets assigned values from a link (inside HTML) to the Facebook API. If you are trying to use an HTML link to the Facebook API from server side (.gs) code, it won't work. There are lots of things that could be going wrong. In order to know exactly what is going wrong, we need to know whether that code is in a gs file, or an HTML file inside a <script> tag.

There are a couple of ways to connect to Facebook:

  • From HTML (Client Side)
  • From the server with HTTP Requests

It looks like the code you are using is from an example of how to use the Facebook JavaScript SDK that is meant to run from inside HTML. The problem with that, is that Apps Script sanitizes HTML sent to the browser. So, if you try to link to the Facebook JavaScript SDK through the HTML, you may not get access. I know that, in the past, I have not been able to use a link to the Facebook API in HTML with the NATIVE sandboxed mode. I haven't tried the new IFRAME sandbox mode.

Balthazar answered 17/2, 2015 at 17:16 Comment(5)
Hi Sandy, thanks for your response. My code is in a gs file, I'm trying to connect to the facebook graph api within the gs file (from the server with HTTP Requests), not from html (client side). Since I'm doing it from the server side and not from the client side, meaning that I won't be able to use the "window", is there a way to connect to the graph api if "FB" also won't work? or is there to make "FB" work within the gs file?Portauprince
Yes, but you need to use the UrlFetchApp.fetch() class and method. I have used it, and explain it here: Facebook API with Apps ScriptBalthazar
I tried that but it won't work. var jsonData = UrlFetchApp.fetch("graph.facebook.com" + name); it's saying that i'm making too many requests to the graph api: Application request limit reached","type":"OAuthException","code":4}, so that's why i'm trying to authorize the app to increase the request limit and hoping that will work, but i'm stuck here. i looked at other posts like this #25282815 and they said that facebook possibly blocked it. any workarounds to this?Portauprince
Without seeing all of your code, there is no way anyone can figure out what is wrong. You need to post your entire code in your question. Remove ID's, passwords.Balthazar
i have edited the question with all my code on therePortauprince

© 2022 - 2024 — McMap. All rights reserved.