Categories
Code

Authorization Errors with Apps Script Execution API

A web form was built using the Google Apps Script Execution API and it would only be using to users who have successfully authenticated using their Gmail / Google Apps account. The form data would go into a Google Spreadsheet but, in some case, when the user would submit the form, the script would throw an error.

Authorization is required to perform that action.

This is puzzling because the user has already authenticated through Google OAuth 2.0 and the error is not consistent either. The error 401 Invalid Credentials suggest that the OAuth access token you’re using with the project is either expired or invalid.

The auth token provided by Google automatically expires in one hour. Thus if a person has authenticated the form but leave it unattended for more than an hour, the token would automatically expire and the Google API would return an error saying that authorization is required.

An easy workaround would be to auto refresh the token every 45 minutes. This can be done by calling gapi.auth.authorize with the client ID, the scope and immediate:true as parameters.


// OAuth Token expires every hour, 
// so refresh every 45 minutes

window.setInterval(refreshOAuthToken, 1000*60*45);

function refreshOAuthToken() {
  gapi.auth.authorize({
    'client_id': CLIENT_ID,
    'scope': SCOPES,
    'immediate': true
  }, function(r) {
    console.log("OAuth Token Refreshed");
  });
}

You can go to the Chrome developer’s console and use the expires_at field to know how much time is left before the token will expire.

new Date(gapi.auth.getToken().expires_at * 1000)

Call refreshOAuthToken() and the expires_at field with advance by 60 minutes.

Categories
Code

Use the Twitter Search API without the OAuth Library

Google doesn’t recommend using script libraries inside add-ons based Apps script projects as they tend to impact performance. This snippet shows how to use the Twitter Search API inside Google Apps Script without including the OAuth library.

Create a new Twitter app, get the Consumer Key and Secret and you will be able to perform most Twitter API functions from within Google Apps Script.

function testTwitterConnection() {

  var twitterKeys = {
    TWITTER_CONSUMER_KEY: "iqoWfLEG1Q4eMGptxiEzb83Da",
    TWITTER_CONSUMER_SECRET: "g6EJijC9Nsrc2D6WazXjF353FNATZzCvtCoigtBoUMfCQeW0L"
  };

  setupTwitter(twitterKeys);
  searchTwitter('ctrlq');
  
}

function setupTwitter(twitterKeys) {

  // URL encode the consumer key and the consumer secret according to RFC 1738
  var encodedConsumerKey = encodeURIComponent(twitterKeys.TWITTER_CONSUMER_KEY);
  var encodedConsumerSecret = encodeURIComponent(twitterKeys.TWITTER_CONSUMER_SECRET);

  // Concatenate the encoded consumer key, a colon character “:”, and the encoded consumer secret into a single string.
  // Base64 encode the string from the previous step.
  var base64EncodedBearerToken = Utilities.base64Encode(encodedConsumerKey + ":" + encodedConsumerSecret);

  // Step 2: Obtain a bearer token

  // The request must be a HTTP POST request.
  // The request must include an Authorization header with the value of Basic .
  // The request must include a Content-Type header with the value of application/x-www-form-urlencoded;charset=UTF-8.
  // The body of the request must be grant_type=client_credentials.

  var bearer_url = 'https://api.twitter.com/oauth2/token';
  var options = {
    "method": "POST",
    "headers": {
      "Authorization": "Basic " + base64EncodedBearerToken,
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
    },
    "payload": {
      "grant_type": "client_credentials"
    }
  };

  var response = UrlFetchApp.fetch(bearer_url, options);
  var data = JSON.parse(response.getContentText());

  // Store the Access Token
  if (data.access_token) {
    PropertiesService.getScriptProperties()
      .setProperty("TWITTER_ACCESS_TOKEN", data.access_token);
  }

  return data.access_token;
}


function searchTwitter(query) {

  var access_token = PropertiesService.getScriptProperties().getProperty("TWITTER_ACCESS_TOKEN");

  if (access_token === null) {
    Logger.log("Run Twitter setup again");
    return;
  }

  var base_url = 'https://api.twitter.com/1.1/search/tweets.json';
  var search_url = base_url + '?q=' + encodeURIComponent(query);

  var options = {
    "method": "GET",
    "headers": {
      "Authorization": "Bearer " + access_token,
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
      "Accept-Encoding": "gzip"
    },
    "followRedirects": true,
    "muteHttpExceptions": true
  };

  var response = UrlFetchApp.fetch(search_url, options);
  var data = JSON.parse(response.getContentText());
  var tweets = data.statuses;

  // Output the tweets in the log
  // They can also be saved in a Google Spreadsheet

  for (var t = 0; t < tweets.length; t++) {
    Logger.log("%s wrote: %s", tweets[t].user.name, tweets[t].text);
  }

}