Trying to post data from Google Spreadsheet to a external Api - javascript

I'm using Google SpreadSheet and IFTTT to do a DB Call Log of my phone, this is working perfect.
Now I'm trying to populate a form in a web page by API from this DB Call Log.
I would like to send lastRow to my API every time IFTTT populate the Sheet.
The first Row in the Sheet is populated with headers name: departament, first_name, last_name, email, phone, deadline.
So i manage to send data to API like this:
function myFunction() {
var data = {
'department': 1,
'first_name' : 'Test',
'last_name' : 'test',
'email' : 'email#gmail.com',
'phone' : ["0700000000"],
'deadline' : '2017-04-10T00:00'
}
var payload = JSON.stringify(data)
var headers = {
'AUTHORIZATION': 'Token b8473654v6345teryrby456yrtyrtyertytdvfh87afc',
// Add any other required parameters for XXX API.
};
var url = 'http://api.XXX.com/api/1.0/clients/';
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headers,
'payload' : payload,
};
var response = UrlFetchApp.fetch(url, options);
}
Now i need to automate it but i don't know how:
(this is a SpreadSheet question) IFTTT populate the "deadline" column in this format "April 10, 2017 at 01:54PM" however the needed format for API is "2017-04-10T13:54", how to auto modify it?
to get the values from Sheet cells (from lastRow) and send them throw json payload
to set a trigger event so the script trigger's every time IFTTT populates a new Row in the Sheet.
Thank you!

Will try to answer the question one by one:
1) Reformat date: You can use Utilities.formatDate() in apps script to modify your date.
Code:
function reformatDate(dtStr)
{
if (dtStr == undefined)
dtStr = "April 1, 2017 at 01:54PM"
dtStr = dtStr.replace("at", "") // Remove at
dtStr = dtStr.replace(/(\d)(PM)/g,"$1 $2") //Add a space between the time and PM
dtStr = dtStr.replace(/(\d)(AM)/g,"$1 $2") //Add a space between the time and AM
Logger.log(dtStr)
dtStr = new Date(dtStr)
var newDt = Utilities.formatDate(dtStr, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "yyyy-MM-dd'T'HH:mm")
Logger.log(newDt)
return newDt
}
2) Get last row Values: You can use getLastRow() and getValues() functions in apps scripts
function lastRowData(){
var ss = SpreadsheetApp.getActive()
var sheet = ss.getActiveSheet()
var lastRow = sheet.getLastRow()
var lastCol = sheet.getLastColumn()
var lastRowData = sheet.getRange(lastRow,1,1,lastCol).getValues()
return lastRowData[0]
}
Edit
To get values as is i.e. displayed values in the sheet, you can modify the getvalues to getDisplayValues() like so:
var lastRowData = sheet.getRange(lastRow,1,1,lastCol).getDisplayValues()
3) Trigger your sheet: I will not reinvent the wheel here. But will provide you with an awesome answer from #Mogsdad
Link: Trigger an email when a cell is written into from another app (IFTTT)
In short, you will have to use onEdit Trigger to detect new entries.
If on edit doesn't work, try on Change trigger.
Complete code:
function myFunction() {
var lastRow = lastRowData()
var data = {
'department': lastRow[0],
'first_name' : lastRow[1],
'last_name' : lastRow[2],
'email' : lastRow[3]',
'phone' : [lastRow[4]],
'deadline' : reformatDate(lastRow[5])
}
var payload = JSON.stringify(data)
var headers = {
'AUTHORIZATION': 'Token b8473654v6345teryrby456yrtyrtyertytdvfh87afc',
// Add any other required parameters for XXX API.
};
var url = 'http://api.XXX.com/api/1.0/clients/';
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headers,
'payload' : payload,
};
var response = UrlFetchApp.fetch(url, options);
}
Hope that helps!

Related

Call API in Google Scripts to populate in Google Sheets

I'm trying to figure out how to send request to URL, so that it populates in Google Sheets. At this moment the log throws error "Order not found". It's my first time writing script for that request. So far I have:
function myFunction() {
var data = {
"date":"2021-07-01",
"reference":"REFERENCE",
"products":[
{
"id":"31565598851174",
"quantity":15
},
{
"id":"31424655589478",
"quantity":10
}
]
}
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
var url = "https://stockists.rerootedorganic.co.uk/api/order/?key=example"
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I think that the problem might be with the syntax in query. Any help to identify what I'm doing wrong would be amazing, thank you.
Errors:
Execution log
11:45:18 AM Notice Execution started
11:45:19 AM Info
{"error":{"message":"Order not found"}}
11:45:19 AM Info null
11:45:20 AM Info
{"error":{"message":"Order not found"}}
11:45:20 AM Info {error={message=Order not found}}
11:45:19 AM Notice Execution completed
Adapt this code
function myFunction() {
var url = 'https://stockists.rerootedorganic.co.uk/api/order/?key=example&date='
var when = '2021-07-01' // string format
var data = JSON.parse(UrlFetchApp.fetch(url+when).getContentText())
Logger.log(data.order.reference)
for (var i=0;i<data.order.products.length;i++){
Logger.log(data.order.products[i].id + ' qty: ' + data.order.products[i].quantity)
}
}
to populate the sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('** Menu **')
.addItem('request','myFunction')
.addToUi();
}
function myFunction() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var d = Utilities.formatDate(sh.getRange('B3').getValue(), "GMT+2", "yyyy-MM-dd")
var url = sh.getRange('B1').getValue() + '?key=' + sh.getRange('B2').getValue() + '&date=' + d
var data = JSON.parse(UrlFetchApp.fetch(url).getContentText())
for (var i=0;i<data.order.products.length;i++){
sh.appendRow([data.order.reference,data.order.products[i].id,data.order.products[i].quantity])
}
}

JavaScript API post and return using Google Sheets script?

I need some help with this. I can't figure out how to print the return from an api post sent from Google Sheets (including any error codes). Posting seems to work fine as the data shows up on RequestBin when I run the function in Sheets (although there are no quotes "" around the nonce output, which I don't understand either).
I need to be able to print the return in Google Sheets (this function runs in the Script Editor) and the data needs to overflow into adjacent cells, whatever the post request returns.
This is the functional code that I have so far:
function testPost() {
var nonce = new Date().getTime();
var data = {
'key':'QrHuXeXcbN',
'signature':'c4cc0d98be8e0860391799c2ca719da5ea6514f1538c4ec69ec1c19',
'nonce':nonce
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://requestb.in/19bzt9a1', options);
}
I have tried a number of different ways to return the values but I can't figure it out.
Got it. Finally. Just needed this at the end... return response.getContentText()
function testPost() {
var nonce = new Date().getTime();
var data = {
'key':'QrHuXeXcbN',
'signature':'c4cc0d98be8e0860391799c2ca719da5ea6514f1538c4ec69ec1c19',
'nonce':nonce
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://requestb.in/19bzt9a1', options);
return response.getContentText()
}

MailChimp GAS - invalid resource: blank email

I'm writing a script that takes google sheet data and uploads my mailchimp subscriber data, where the edited cell values are sent over as updated merge tags. The original code came from here. I've got the script running successfully, accept for this one error:
"Invalid Resource","status":400,"detail":"Blank email address"
I understand the error according to the documentation in the mailchimp api documentation, but I'm not sure why it's not recognizing the subscriber data from the script:
var emHash = md5(em.toLowerCase()); //this is pulled from my md5 function
var payload = JSON.stringify({
"status_if_new": "subscribed",
"email_address": em,
"merge_fields": {
"LEAD": lead,
//rest of vars following same syntax
}
});
var options = {
"headers" : headers,
"payload": payload,
"method" : "put",
"muteHttpExceptions" : true
};
var response = UrlFetchApp.fetch('https://us15.api.mailchimp.com/3.0' + '/lists/' + 'xxxxxxx' + '/members/' + emHash,options);
Logger.log(response);
}
Last is the function triggered by editing so that changed values get sent over via the function above
function onEdit(e) {
var activeSheet = e.source.getActiveSheet();
var range = e.range;
var rowedited = range.getRowIndex();
if (activeSheet.getName() !== "ATTENDANCE"){
return;
Logger.log("Oops :(");
}
else {
var values = sheet.getRange(rowedited, 1, 1, 13).getValues()[0];
var em = values[2];
var lead = values[1];
//remaining vars omitted for brevity
sendToMailChimp_(em,lead...[etc.]);
}
Any thoughts?
I figured it out - I pulled an amateur move and had the columns attributed to the wrong array element.... So yes, I started at 1 and not 0
facepalm
It is now working!

Assign latest date (from API) to identifier (in spreadsheet) using Google Apps Script

I have a Google Sheets spreadsheet with a list of identifiers in the first column (e.g. COLTS or RAMS). Using Google Apps Script I then fetch transaction data for these identifiers from an API (multiple transactions per identifier). That data looks like this:
{
"sportsfolio_transactions":[
{
"trans_date":"06/26/2017 9:58:00 AM",
"amount":-10.30,
"trans_type_id":1,
"trans_type_name":"Buy",
"stock_id":"COLTS",
"shares":3
},
{
"trans_date":"04/25/2017 2:58:00 AM",
"amount":-3.22,
"trans_type_id":1,
"trans_type_name":"Buy",
"stock_id":"COLTS",
"shares":1
}
{
"trans_date":"05/20/2017 2:58:00 AM",
"amount":-30.22,
"trans_type_id":1,
"trans_type_name":"Buy",
"stock_id":"RAMS",
"shares":9
}]}
The code I have so far filters for buy transactions and looks like this:
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('apidata'); active spreadsheet
var output = [];
data["sportsfolio_transactions"].forEach(function(elem,i) {
output.push([elem["stock_id"],elem["shares"],elem["trans_type_name"],elem["trans_date"],elem["amount"]]);
});
var outputbuy = [];
data["sportsfolio_transactions"].forEach(function(element,i) {
if(element["trans_type_name"] == "Buy") {
outputbuy.push([element["stock_id"],element["shares"],element["trans_type_name"],element["trans_date"],element["amount"]]);
}
});
Now I would like to put the date of the latest transaction next to each identifier.
E.g. according to the above data, next to COLTS should be the date 06/26/2017
After hours of trying (math.max, sorting, etc.) I'm out of ideas and hope that you can help me out here. Oh, and if you see any possible improvements for the posted code, of course that is also much appreciated.
Managed to get the problem solved, sort of. Can only look into "Buy" transactions, was not able to get "Buy" || "Sell" to work properly.
Also, this code seems awefully inefficient, but it's the best I was able to produce. Any ideas on how to make it more efficient?
Here's the code:
function getLastTrade() {
var url= 'https://asmwebdev1.azurewebsites.net/api/get_sportsfolio_transactions/'
var today = new Date()
var enddate = Utilities.formatDate(today,"GMT", "MM/dd/YYYY");
var formData = {
'email': 'xxxxx',
'password': 'x',
'sportsfolio_key': '9657',
'start_date': '01/01/2017',
'end_date': enddate,
};
var options = {
'method' : 'post',
'payload' : formData
};
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('apidata');
var Avals = ss.getRange("A2:A50").getValues();
var Alast = Avals.filter(String).length;
for(var row=2;row<Alast+2;row++){
var oldestdate = new Date(0)
data["sportsfolio_transactions"].forEach(function(element,i) {
var lastid = sheet.getRange(row, 1).getValues();
if(element["stock_id"] == lastid && element["trans_type_name"] == "Buy"){
var newestdate = new Date(element["trans_date"])
if(newestdate>oldestdate) {
oldestdate = newestdate
}
sheet.getRange(row,6).setValue(oldestdate)
}
});
}
}
The data that the API returns contains hundreds of transactions, a small sample can be seen in the post above.

Google Script API routexl error 409

I'm trying to make a script which works out the fastest route to pass multiple locations, with the help of the routexl API. However, everything I try seems to come up with an error 409 Truncated server response. My code is as follows.
function myFunctionpost() {
var url = "https://api.routexl.nl/distances";
var places = [{"address":"1","lat":"52.05429","lng":"4.248618"},{"address":"2","lat":"52.076892","lng":"4.26975"},{"address":"3","lat":"51.669946","lng":"5.61852"}];
var locations = JSON.stringify(places);
var headers = {
"Authorization":"Basic " + Utilities.base64Encode("Username:password"),
"Content-Type":"application/json"
};
var options = {
'method' : 'post',
'headers' : headers,
'contentType': 'application/json',
'payload' : locations,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
//var json = response.getContentText();
//var data = JSON.parse(json);
Logger.log(response);
}
The 409 error indicates there is no input found. I am no Google Apps expert, but the RouteXL API expects "locations" as input parameter. In your example the locations JSON is posted without the locations key.
Update: after some testing on Google Apps Script, I also found the ContentType needs to be adjusted.
Here is an example that worked for me:
function myFunctionpost() {
var url = "https://api.routexl.nl/distances";
var places = [{"address":"1","lat":"52.05429","lng":"4.248618"},{"address":"2","lat":"52.076892","lng":"4.26975"},{"address":"3","lat":"51.669946","lng":"5.61852"}];
var locations = JSON.stringify(places);
var headers = {
"Authorization":"Basic " + Utilities.base64Encode("username:password")
};
var options = {
'method' : 'post',
'headers' : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : {'locations': locations},
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
//var json = response.getContentText();
//var data = JSON.parse(json);
Logger.log(response);
}

Categories

Resources