Migrating from OAuthConfig to the OAuth1 library

The URL Fetch service's OAuthConfig class provided a simple mechanism for connecting to an API that utilized OAuth, specifically OAuth versions 1.0 and 1.0a. This mechanism is now deprecated and scheduled for sunset on July 6, 2015. The open source library OAuth1 for Apps Script was created as a replacement, and this page will demonstrate how to update your scripts to use this new mechanism.

Adding the library

Before you can start using the OAuth1 for Apps Script library, you must first add it to your scripts. To do so, follow these directions in the libraries guide and use the library project key Mb2Vpd5nfD3Pz-_a-39Q4VfxhMjh3Sh48.

Code changes

Before

The sample code below shows how the deprecated OAuthConfig class can be used to connect to the Twitter API.

var CONSUMER_KEY = '...';
var CONSUMER_SECRET = '...';

function listTweets() {
  var service = UrlFetchApp.addOAuthService('twitter');
  service.setAccessTokenUrl('https://api.twitter.com/oauth/access_token');
  service.setRequestTokenUrl('https://api.twitter.com/oauth/request_token');
  service.setAuthorizationUrl('https://api.twitter.com/oauth/authorize');
  service.setConsumerKey(CONSUMER_KEY);
  service.setConsumerSecret(CONSUMER_SECRET);

  var url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
  var options = {
    'oAuthServiceName' : 'twitter',
    'oAuthUseToken' : 'always'
  };
  var response = UrlFetchApp.fetch(url, options);
  var tweets = JSON.parse(response.getContentText());
  for (var i = 0; i < tweets.length; i++) {
    Logger.log(tweets[i].text);
  }
}

After

Below is the same code again after being updated to use the OAuth1 for Apps Script library.

var CONSUMER_KEY = '...';
var CONSUMER_SECRET = '...';
var PROJECT_KEY = '...';

function listTweets() {
  var service = getTwitterService();
  if (service.hasAccess()) {
    var url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
    var response = service.fetch(url);
    var tweets = JSON.parse(response.getContentText());
    for (var i = 0; i < tweets.length; i++) {
      Logger.log(tweets[i].text);
    }
  } else {
    var authorizationUrl = service.authorize();
    Logger.log('Please visit the following URL and then re-run the script: ' + authorizationUrl);
  }
}

function getTwitterService() {
  var service = OAuth1.createService('twitter');
  service.setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
  service.setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
  service.setAuthorizationUrl('https://api.twitter.com/oauth/authorize')
  service.setConsumerKey(CONSUMER_KEY);
  service.setConsumerSecret(CONSUMER_SECRET);
  service.setProjectKey(PROJECT_KEY);
  service.setCallbackFunction('authCallback');
  service.setPropertyStore(PropertiesService.getScriptProperties());
  return service;
}

function authCallback(request) {
  var service = getTwitterService();
  var isAuthorized = service.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this page.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this page');
  }
}

Move the setup code to its own function

Many developers already grouped their OAuthConfig setup code in a separate function for convenience, but this becomes a requirement when using the OAuth1 for Apps Script library. Both the functions listTweets() and authCallback() need access to the OAuth1 service object, and the solution is to move the service setup code to its own getTwitterService() function, which is then called from both places. Please note that the script must execute the OAuth1.createService() setup function each time it runs.

Use the library to create the service

Instead of creating the service using UrlFetchApp.addOAuthService(), use OAuth1.createService().

Set additional parameters

In addition to the OAuth URLs, keys, and secrets, the library requires a few additional parameters to be set.

  • setProjectKey(): Sets the project key of your script, shown in the File > Project properties dialog.
  • setCallbackFunction(): Sets the name of the callback function as defined in your script (see the Add a callback function section below).
  • setPropertyStore(): Sets the property store where authorization information should be stored. Unlike with OAuthConfig, for which only the developer could authorize the script and all users shared the same authorization, the library lets any user authorize the script and lets the developer choose how that authorization is shared. To emulate the old behavior of OAuthConfig, we've used script properties in the sample above. However, in most use cases, it's advantageous to use user properties, so that each user maintains their own authorizations.

Test to see if authorization has been granted before using the service

When using OAuthConfig, the script could start using the service before it was authorized. Apps Script would detect this situation and prompt the developer to authorize it. When using the OAuth1 for Apps Script library, you must test for authorization first using the service's hasAccess() method.

Prompt the user for authorization

Unlike before, when using the library you must decide how to prompt the user to authorize the service. First, call the service's authorize() method to get the URL, then get the user to visit that URL. In the sample above, we simply log a message for the developer to see. However, in a more complex script, you may want to open a dialog with a link for the user to click.

Add a callback function

Once the user has authorized the service, they are redirected back to a special URL in the format https://script.google.com/macros/d/{PROJECT KEY}/usercallback, where {PROJECT KEY} is the project key of your script, which you set up previously using setProjectKey().

In order to handle the callback, you must define a callback function in your script that completes the OAuth flow and shows a message to the user. In the sample above, this is the function authCallback(), and the name of that function must match the value you passed in to setCallbackFunction during setup. The callback function must pass its request object to the service's handleCallback() method and should present some sort of message to the user instructing them to close the window or tab. It currently isn't possible to close the window or tab automatically.

Use the service's fetch() method

Instead of using UrlFetchApp.fetch() to make the request to the API, use the service's fetch() method. Both methods accept the same parameters, but the service's version of fetch() automatically signs the requests with the OAuth credentials.

Resetting authorization

Although not shown in the example above, it is possible to remove or reset authorization. This was previously done using UrlFetchApp.removeOAuthService(), but when using the library, call the service's reset() method.

发送以下问题的反馈:

此网页
Apps Script
Apps Script