A
A
Alexander Lazarenko2022-04-07 01:46:45
Google Apps Script
Alexander Lazarenko, 2022-04-07 01:46:45

Integration with CDEK 2.0 API - why can't I get a Google Script token?

I wrote the following code to get the token on their test environment:

function logInCDEK() {
  var url = "https://api.edu.cdek.ru/v2/oauth/token?parameters"
  var options = {
    "method": "post",
    "headers": {
      "Content-type": 'application/json',
      'Accept': 'application/json'
    },
    "grant_type" : "client_credentials",
    "client_id" : "EMscd6r9JnFiQ3bLoyjJY6eM78JrJceI",
    "client_secret" : "PjLZkKBHEiLK3YsjtNrt3TGNG0ahs3kG",
    muteHttpExceptions: true
  }

  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText())
}


It gives out the following:
{"timestamp":"2022-04-06T22:36:34.174+00:00","status":401,"error":"Unauthorized","message":"","path":"/oauth/token"}


Help me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Grigory Boev, 2022-04-07
@InFiNiTy2707

Because you need to pass data in the query parameters, and not in the post body

function logInCDEK() {
  let url = `https://api.edu.cdek.ru/v2/oauth/token`;

  let options = {
    method: "POST",
    muteHttpExceptions: true,
    headers: {
      "Content-type": "application/json",
      "Accept": "application/json"
    },
  };

  let queryParams = {
      grant_type : "client_credentials",
      client_id : "EMscd6r9JnFiQ3bLoyjJY6eM78JrJceI",
      client_secret : "PjLZkKBHEiLK3YsjtNrt3TGNG0ahs3kG",
    };

  url+=Object.keys(queryParams).length?`?${getQueryString(queryParams)}`:"";

  let response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText())
}

/**
 * Преобразует object в query-строку для подстановки в url
 *
 * @author Boew Grigory ([email protected])
 * @param {Object} data Объект для преобразования
 * @return Возвращает query строку
*/
function getQueryString(payload) {
  let payloadData = Object.entries(payload);
  return encodeURI(
    payloadData
      .filter(o=>o[1]!==undefined)
      .map(v=>`${v[0]}=${v[1]}`)
      .join("&")
    );
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question