@cajka-d

Почему при использовани библиотеки OAuth2 для Goole Apps Script redirect_uri неверный?

Здравствуйте.

Пишу приложение на языке Google Apps Script. В данном приложение хочу использовать API ВКонтакте. Чтобы взаимодействовать с API ВКонтакте из приложения на языке Google Apps Script, добавила в среду разработки библиотеку OAuth2. Ссылка на библиотеку OAuth2. Сделала все, как описано в документации по ссылки. Сам код работает, но ссылка которая формируется для параметра redirect_uri нерабочая. То есть, если по ней перейти, Google пишет, что файл не найдет. Вконтакте также при авторизации через OAuth2 возвращает ошибку, что redirect_uri не найден.

Код скрипта:

var CLIENT_ID = 'client id';
var CLIENT_SECRET = 'client secret';

/**
 * Authorizes and makes a request to the VK API.
 */
function run() {
  var service = getService();
  if (service.hasAccess()) {
    // GET requests require access_token parameter
    var url = 'https://api.vk.com/method/users.get?fields=first_name,last_name&access_token=' + service.getAccessToken();
    var response = UrlFetchApp.fetch(url);

    // note: add 'email' to the fields= list above in order to
    //       fetch email from token (+uncomment 2 lines below)
    // var email = service.getToken().email;
    // Logger.log('email: '+email);

    var result = JSON.parse(response.getContentText());
    Logger.log(JSON.stringify(result, null, 2));
  } else {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log('Open the following URL and re-run the script: %s',
        authorizationUrl);
  }
}

/**
 * Reset the authorization state, so that it can be re-tested.
 */
function reset() {
  getService().reset();
}

/**
 * Configures the service.
 */
function getService() {
  return OAuth2.createService('VK')
      // Set the endpoint URLs.
      .setAuthorizationBaseUrl('https://oauth.vk.com/authorize')
      .setTokenUrl('https://oauth.vk.com/access_token')

      // Set the client ID and secret.
      .setClientId(CLIENT_ID)
      .setClientSecret(CLIENT_SECRET)

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

      // Set the scope and additional specific parameters if its are supported
      .setScope('email,groups,offline');
}

/**
 * Handles the OAuth callback.
 */
function authCallback(request) {
  var service = getService();
  var authorized = service.handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput('Success!');
  } else {
    return HtmlService.createHtmlOutput('Denied.');
  }
}

/**
 * Logs the redict URI to register in the VK Aps Page https://vk.com/apps?act=manage.
 */
function logRedirectUri() {
  Logger.log(OAuth2.getRedirectUri());
}


Чтобы получить URL для redirect_uri, можно просто выполнить функцию logRedirectUri.

Может, кто подскажет, что я делаю не так? И что нужно сделать, чтобы возвращаемый URL для redirect_uri был рабочим при обращение?
  • Вопрос задан
  • 218 просмотров
Решения вопроса 1
oshliaer
@oshliaer Куратор тега Google Apps Script
Google Products Expert
Редирект не нужно указывать в настройках приложения. Он не для этого.

6189d3fa84698507725762.png

Еще, я думаю, что вам нужно передать версию API

const url =
  'https://api.vk.com/method/users.get?&v=5.131&fields=first_name,last_name&access_token=' +
    service.getAccessToken();


https://github.com/googleworkspace/apps-script-oau...
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы