How to Access Facebook API from Google Apps Script

Introduction

Facebook provides various REST APIs called Graph APIs which application developers can use to integrate their app with Facebook. Google App scripts is a powerful and easy to use application development platform which makes it easy to create business applications that can integrate with G Suite. Accessing Facebook API from Google Apps Script gives you such unimaginable power which you can use to develop a variety of useful business applications or apps.

You can do a lot of things and only restricted by your imagination. For example, think about an app that gets a list of all your friends on your Facebook and their birthdays. Stores them in Google Spreadsheet and sends personalized automated emails to wish on their birthdays or even directly post on their wall automatically. Sounds cool right. But to achieve all of this cool stuff, the first thing we need to do is access Facebook API from Google apps script which we will discuss here.

OAuth2 Protocol Intro

All the big brands like Facebook, Google, LinkedIn, Adobe, Yahoo, etc. expose APIs for application developers. These APIs are not directly accessible and protected by permissions and privileges. The protocol which enables this safeguarding of APIs is OAuth2. If you want to know how OAuth2 protocol works, please wait for my next post. That is to say, when a user authenticates an app to use their Facebook profile ( or any other site’s profile) then they don’t need to enter the credentials in the app ( hence security for users). Instead, App gets a user-specific access token. Using this token the client app can call graph APIs.

Create a Facebook App

Enough of theories right. Let’s access the Facebook API from Google Apps Script now. The first thing you need to do is create a new app on the Facebook developer’s site. Go to “My Apps->Add a new App”. A new window like below will open. Enter app name and click “Create App ID”:-

App ID is present at the top in a new panel. Go to “Settings->Basic”. In the right-hand side you will see a window like this:-

In the “App Domains” field, enter “script.google.com”. Also, copy the values in the fields “App ID” & “App Secret” on the clipboard and keep it safe for further reference. We will need it later. Save the changes and exit.

Google Apps Script setup

Now we need to do some coding in Google App Script. Visit your google drive and click on “New->Google Sheets->Blank spreadsheet”. In the newly opened spreadsheet visit the menu and click on “Tools->Script editor”. In the new tab, the editor will open where we will start writing our code. But before that, please give some good names to the untitled project, like “Facebook login”.

We will make use of the Oauth2 library provided by google for accessing Facebook API from Google Apps Script. Have a look at it here. We need to add this library as a dependency in our project. In the editor, go to “Resources->Libraries”. In the newly opened window, we need to give script id of the library (1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF), add it, and select the latest version and save it:-

Go to “View->Show manifest file” to verify the successful import of the library”. Click the file “appscript.json” shown in left panel of editor. If its added successfully you can see script id provided in dependencies:-

Code for OAuth2 Object

Now let’s go back to “code.gs” and delete default functions. We will have a function “getFbService”. Here we will make use of OAuth2 library functions. Create an OAuth2 object to connect with Facebook. Basically this function internally customizes an URL with all the necessary headers and values, used to post requests to Facebook.  The function goes like this:-

function getFbService() { // Create a new service with the given name. The name will be used when // persisting the authorized token, so ensure it is unique within the // scope of the property store. return OAuth2.createService('Facebook') // Set the endpoint URLs. .setAuthorizationBaseUrl('https://www.facebook.com/dialog/oauth') .setTokenUrl('https://graph.facebook.com/v2.6/oauth/access_token') // Set the client ID and secret, from the Google Developers Console. .setClientId('...') .setClientSecret('...') // Set the name of the callback function that should be invoked to complete // the OAuth flow. .setCallbackFunction('authCallback') // Set the property store where authorized tokens should be persisted. .setPropertyStore(PropertiesService.getUserProperties()); }
Code language: JavaScript (javascript)

In the “setClientId” function replace the “…” with the App Id we had saved earlier from the Facebook developers site. In the “setClientSecret” function, replace the “…” with the App Secret copied from the Facebook developer site. The “setCallbackFunction” is used to set the callback function which is triggered when we receive a response from Facebook for our request. This is the function that we need to implement which goes like this:-

/** * Handles the OAuth callback. */ function authCallback(request) { Logger.log(request); var service = getFbService(); var authorized = service.handleCallback(request); if (authorized) { return HtmlService.createHtmlOutput('Success!'); } else { return HtmlService.createHtmlOutput('Denied.'); } }
Code language: JavaScript (javascript)

We have written down the callback function, but this callback function is tied to a redirect URI which Facebook calls when it is done with its token generation process ( or even in case of failure if verification fails). This redirect URI is of the form “https://script.google.com/macros/d/{SCRIPT ID}/usercallback”. But we can write a function “ “logRedirectUri” also to see the exact value. 

function logRedirectUri() { var service = getFbService(); Logger.log(service.getRedirectUri()); }
Code language: JavaScript (javascript)

Run this function and go to “View->Logs” to check. Now Facebook also needs to know what’s the URI where it has to redirect the response. So copy this URI from logs and switch back to our Facebook developers page.Go to “Settings” and paste it in the field “Valid OAuth Redirect URIs”:-

Also make sure “Client OAuth Login” and “Web OAuth Login” are selected to Yes. Save the changes and exit. 

Core Function Logic

Let’s come back to our app scripts editor. We are done with functions that are used to set the login request. Now we need to have another function that will check if the app script already has access to Facebook API or not. If it has access then we will trigger a simple Facebook graph API to fetch the details of the user who is currently logged in and save it in the spreadsheet. If the app doesn’t have access then we will get an authorization URL. As discussed earlier this authorization URL is basically made from the OAuth2 object we created in the “getFBService” function.

One thing to note here is, google app script can not redirect the user automatically to this URL. We need to present this URL to the user and ask him to click it manually. We will present this URL as a link in the sidebar of the spreadsheet  to the user. Let’s write a function “run” for all of this as below:-

/** * Authorizes and makes a request to the Facebook API. */ function run() { var service = getFbService(); if (service.hasAccess()) { var url = 'https://graph.facebook.com/v2.6/me'; var response = UrlFetchApp.fetch(url, { headers: { 'Authorization': 'Bearer ' + service.getAccessToken() } }); var result = JSON.parse(response.getContentText()); SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1").setValue(result.name); SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("B1").setValue(result.id); } else { var authorizationUrl = service.getAuthorizationUrl(); Logger.log('Open the following URL and re-run the script: %s', authorizationUrl); var template = HtmlService.createTemplate( '<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' + 'Reopen the sidebar when the authorization is complete.'); template.authorizationUrl = authorizationUrl; var page = template.evaluate(); SpreadsheetApp.getUi().showSidebar(page); } }
Code language: JavaScript (javascript)

Execution and Verification

Let’s select this function in the editor and execute it. Since we never had a valid token before so it will open up a sidebar with link in spreadsheet as below:-

 Click on this link and the user will be redirected to facebook authentication URL. If the user is already logged in to facebook then a token will be generated and the redirect URI configured earlier will be triggered with the token successfully. Otherise facebook will present user a login page to enter credentials and upon validation will generate the token. If authentication fails then redirect URI is triggered with a failed response. On successfull validation user will see a dialogue which he can continue with :-

App Script has got a valid access token now. So if we execute our “run” function again it will trigger graph API with the access token and user details ( username and facebook id) will be fetched successfully and updated in the spreadsheet:-

So this is how we can integrate Facebook graph APIs in Google App scripts. You can explore all the Facebook API and app script classes for G suites. Combining both of these you can do a hell lot of stuff. you are limited only by your imagination( I know I am repeating it again). Please leave your comments below about your thoughts on the post.

Click here to view posts you may like.

5 thoughts on “How to Access Facebook API from Google Apps Script”

  1. Hey,

    Very instructive and powerful. Thank you very much Abhishek.
    Any link or good practice(s) to share to get the necessary credentials and be able to post on Facebook Pages the user has been allowed to post on ? Or for the app to ask for credentials to post on a Facebook page on his behalf ?

    Thanks a lot, again.

    Kindest regards,
    CHK

  2. Hey Abhishek,

    Thanks for the great tutorial.

    I have been able to set it up to get my basic profile data. But to view my connected Instagram accounts or use the instagraph graph API I need to provide additional permissions: ‘intagram_basic’ & ‘pages_show_list’.

    How do I go about requesting additional permissions?

    Thanks again.

Leave a Reply

Your email address will not be published. Required fields are marked *