Search code examples
oauthgoogle-apps-scriptmicrosoft-translator

Doing an https POST request for token


I am trying to do the following request in Google Apps Script. This request would return the token to be used for accessing the API.

POST https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
Content-Type: application/x-www-form-urlencoded

client_id=USERS-CLIENT-ID&client_secret=USERS-SECRET-KEY&grant_type=client_credentials&scope=http%3a%2f%2fapi.microsofttranslator.com%2f

How do I do the above request in Google Apps Script. I am reading about it but unable to find a solution. I tried something like below, but it didn’t work. Which methods should I use?

var oAuthConfig = UrlFetchApp.addOAuthService("bearer");
oAuthConfig.setConsumerKey("USERS-CLIENT-ID");
//some code omitted
//I couldn't figure out where to put grant_type and scope 
var result = UrlFetchApp.fetch("http://api.microsofttranslator.com/v2/Http.svc/Translate?text=hello&from=en&to=ja",options); //gave oAuth error

Solution

  • addOAuthService is really only meant for OAuth 1 services.

    For OAuth 2 you'll need to manually do the POST call. Here is an example

    var parameters = {
        method : 'post',
        payload : 'client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&grant_type=authorization_code&redirect_uri='+REDIRECT_URL+'&code=' + code
      };
    
      var response = UrlFetchApp.fetch(TOKEN_URL,parameters).getContentText(); 
    

    You can see a more fully formed example here - https://github.com/entaq/GoogleAppsScript/blob/master/IO2013/YouTubeAnalytics/oauth2.gs#L22