Skip to content

Instantly share code, notes, and snippets.

@franciscojsc
Last active March 30, 2023 21:43
Show Gist options
  • Save franciscojsc/cf058462273cd9d4870cbe9a27c7213c to your computer and use it in GitHub Desktop.
Save franciscojsc/cf058462273cd9d4870cbe9a27c7213c to your computer and use it in GitHub Desktop.
Apps Script - Web API
// Documentaion https://developers.google.com/apps-script/guides/content
const API_KEY = '03214fc6-dbf0-424f-8086-a7acde8c91af'
// Request Get
// curl -L URL_OF_YOUR_SCRIPT?apikey=03214fc6-dbf0-424f-8086-a7acde8c91af&phone=5599999999999
function doGet(event) {
try {
const data = event.parameters;
if (!validateAuth(data)) {
return formatResponse({ status: 'Not Authorization' });
}
const { phone } = data;
const positionLine = searchLine(phone)
if (positionLine != -1) {
const line = getLine(positionLine);
const lineFormat = formatLine(line);
return formatResponse(lineFormat)
}
return formatResponse({ status: 'Not Found' });
} catch (error) {
return formatResponse({ status: 'Error' });
}
}
// Request Post
// curl --location 'URL_OF_YOUR_SCRIPT' \
// --header 'Content-Type: application/json' \
// --data '{
// "phone": "5599999999999",
// "apikey": "03214fc6-dbf0-424f-8086-a7acde8c91af"
// }'
function doPost(event) {
try {
const postData = event.postData;
const data = JSON.parse(postData.getDataAsString());
if (!validateAuth(data)) {
return formatResponse({ status: 'Not Authorization' });
}
const { phone } = data;
const positionLine = searchLine(phone)
if (positionLine != -1) {
const line = getLine(positionLine);
const lineFormat = formatLine(line);
return formatResponse(lineFormat)
}
return formatResponse({ status: 'Not Found' });
} catch (error) {
return formatResponse({ status: 'Error' });
}
}
function validateAuth(data) {
try {
const { apikey } = data;
if (apikey == API_KEY) {
return true;
}
return false;
} catch (error) {
return false;
}
}
function formatResponse(result) {
return ContentService
.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON);
}
function readyDataSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var values = sheet.getDataRange().getValues();
Logger.log(values);
return values;
}
// Datas in sheet
// Nome | Sobrenome | Telefone
function searchLine(value) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var column = sheet.getRange("C:C").getValues(); // column sheet
for (var i = 0; i < column.length; i++) {
if (column[i][0] == value) {
return i + 1;
}
}
return -1;
}
function getLine(positionLine) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var lineValues = sheet.getRange(positionLine, 1, 1, sheet.getLastColumn()).getValues()[0];
return lineValues;
}
function formatLine(line) {
return {
name: line[0],
surname: line[1],
phone: line[2]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment