Выполнение запроса https POST для токена

Я пытаюсь выполнить следующий запрос в сценарии Google Apps. Этот запрос вернет токен, который будет использоваться для доступа к 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

Как выполнить указанный выше запрос в скрипте Google Apps. Я читаю об этом, но не могу найти решение. Я пробовал что-то вроде ниже, но это не сработало. Какие методы следует использовать?

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

person Sumit Sinha    schedule 31.07.2013    source источник


Ответы (1)


addOAuthService на самом деле предназначен только для сервисов OAuth 1.

Для OAuth 2 вам нужно вручную выполнить вызов POST. Вот пример

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(); 

Здесь вы можете увидеть более полный пример — https://github.com/entaq/GoogleAppsScript/blob/master/IO2013/YouTubeAnalytics/oauth2.gs#L22

person Arun Nagarajan    schedule 01.08.2013