Answer the question
In order to leave comments, you need to log in
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())
}
{"timestamp":"2022-04-06T22:36:34.174+00:00","status":401,"error":"Unauthorized","message":"","path":"/oauth/token"}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question