Mandrill API to Google Sheets Script - google-apps-script

I want to call the Mandrill API in order to have tagged template data populate in my google sheet labeled test, but I can't seem to get it working (spent hours I am a beginner). Below is my code
function mandrill() {
var from = "https://mandrillapp.com/api/1.0/tags/list.json";
var key = "*************";
var params = {
"return" :[
"time",
"sent",
"opens",
"clicks",
],
"sheet": "test"
}}
I followed the official docs but I can't seem to get it working. Any help at all would be greatly appreciated.
https://mandrillapp.com/api/docs/tags.JSON.html#method=all-time-series

The Apps Script reference specifies how to use the fetch() method to retrieve your request from Mandrill.
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
Please use
UrlFetchApp.fetch(url, options);
You need to JSON.stringify() the JSON request for the Mandrill /urls/list.json and pass it as a payload into the options of the fetch request. According to the documentation you provided, the correct JSON request is:
{
"key": "example key"
}
Subsequently, you can proceed your response and use it to populate the sheet. Please refer to:
https://developers.google.com/apps-script/reference/url-fetch/http-response
Then you need to parse the answer to JavaScript object, you need to parse it before accessing the content with the method getContentText(). You can then access the entries of interest and populate your sheet with it:
In summary, your code to retrieve the response from Mandrill should look like this:
function mandrill() {
var from = "https://mandrillapp.com/api/1.0/tags/list.json";
var params = {
"key": "*************"
};
var payload = JSON.stringify(params);
var options = {
'method': 'post',
'payload': payload,
'contentType' : 'application/json'
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response).getContentText());
var ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test");
sheet.getRange("A1").setValue(data['sent'])
}

Related

Google Sheets activity sending to GA4 with App Script

I have been trying to change my script that used to send to the old UA Google Analytics using the IMAGE() but with the new GA4 you have to send a POST. I tried to use the onOpen(e) with some of the code below but nothing seems to work even though I am not getting any errors. Does anyone know if it is possible to make a call [POST] with this information:
function onOpen(e) {
// Make a POST request with a JSON payload.
var data = {
"client_id": Utilities.getUuid(),
"user_id": "webuser",
"events": ["name", "cve_database"]
};
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://www.google-analytics.com/mp/collect?api_secret=<ID-Here>&measurement_id=<GA4 Acc>', options);
Logger.log(response)
}
I tried to get it to update the Google Analytics information so that I can keep track of the users who view the page.

doPost not running for other users in google appscript

I have deployed my appscript as a form addon and as a web app both.
Everything seems to be working fine in the container form. But now I'm facing this issue where doPost function is not running as I have to run the function as other user. I tried this code from this answer, but this is also giving same authorization error.
function merry2script() {
var url = 'https://script.google.com/macros/s/AKfycbzM97wKyc0en6UrqXnVZuR9KLCf-UZAEpzfzZogbYApD9KChnnM/exec';
var payload = {payloadToSend : 'string to send'};
var method = 'post'
var headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}
var response = UrlFetchApp.fetch(url, {method : method, payload: payload, headers: headers}).getContentText();
Logger.log(response);
return;
}
Is this the correct way to post to appscript with oauth token?
If not how can I send a post request ?
I deployed the web app with these settings
I'm getting this error
I've been stuck for 3 days any help is appreciated
Thank you
UPDATED QUESTION:
APPSCRIPT DOPOST
function doPost(e) {
var data = JSON.stringify(e);
var jsonData = JSON.parse(data);
let query = jsonData.queryString;
let params = query.split("&");
let destinationId = params[0].split("=")[1];
// code is breaking here saying "you don't have access to the document"
let ss = SpreadsheetApp.openById(destinationId);
let sheetName = ss.getActiveSheet().getSheetName();
let dataSheet = ss.getSheetByName(sheetName);
var uniqueIdCol = dataSheet.getRange("A1:A").getValues();
let rowToUpdate;
// code to update row...
}
BACKEND CODE
// call appscript to update status sheet
const data = {
comment
};
let scriptId = process.env.DEPLOYMENT_SCRIPT_ID;
const config = {
method: "post",
url: `https://script.google.com/macros/s/${scriptId}/exec?destinationId=${destinationId}&uniqueId=${uniqueId}&status=${status}`,
data,
headers: {
Authorization: `Bearer ${respondent.form.oAuthToken}`,
},
};
await axios(config);
These are the scopes which I requested to user
"https://www.googleapis.com/auth/script.container.ui",
"https://www.googleapis.com/auth/forms.currentonly",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/script.send_mail",
"https://www.googleapis.com/auth/forms",
"https://www.googleapis.com/auth/script.scriptapp",
"https://www.googleapis.com/auth/drive"
UPDATED QUESTION 2
I had made a script which can write to google sheet with some extra data which I send from my node backend.
So my script has doPost function which is invoked from backend. I send destinationId of the sheet to know in which sheet to write as in the code above.
I have deployed the webapp as Execute as: Me and Who has access to the app: Anyone.
I'm able to run the doPost function but not able to write to sheet.
Hope my question is clear
So after struggling for 4 days I was able to send email and write to spreadsheet with users OAuth token by directly interacting with Sheets API and Gmail API instead of doing it through ScriptApp doPost method

Google scripts function to fetch curl data to Google Sheets

I'm trying to fetch some data to a google sheet. The code goes like this:
function ls() {
var url = "https://api.loanscan.io/v1/interest-rates?tokenFilter=BTC";
var params = {
"contentType": "application/json",
"headers":{"x-api-key": "KEY",
},
};
var json = UrlFetchApp.fetch(url, params);
var jsondata=json.getContentText();
var page = JSON.parse(jsondata);
Logger.log page
return page;
}
The Logger.log gives the correct Data, as you can see in the next link.
Log
However when I run the function in the google sheet, it returns a blank cell.
Please help, thank you.
You should write the Logger.log(page); with parentheses, because sheets is probably hanging on your Logger statement.
I don't have an API key for that site, but I do get the forbidden error response from the API when using =ls() in a cell in sheets.

Google Apps Script : Returning "null" when trying to select a specific object in a API response but I can see it in the original response

I am a relative newbie to JSON in general. I am attempting to implementing some functionality in Google Apps Scripts.
My function calls the www.goldpricez.com's API and receives back some data about gold prices around the world, and of that data I would like to return one specific value (the price of Gold in MAD) in this instance.
function fetchGoldRates() {
var currency = "mad";
var unit = "gram";
var url = 'http://goldpricez.com/api/rates/currency/' + currency + '/measure/' + unit;
var params = {
'method': 'GET',
'muteHttpExceptions': true,
'headers': {
'X-API-KEY': '###'
}
};
var response = UrlFetchApp.fetch(url,params);
var parsedData = JSON.parse(response.getContentText());
Logger.log(parsedData); //Works and include the data I want in the object gram_in_mad
Logger.log(parsedData.gram_in_mad); //Returns Null
}
This is the JSON data I receive back...in a pretty print visualized format.
{
"ounce_price_usd": "1729.54",
"gmt_ounce_price_usd_updated": "26-05-2020 04:18:01 am",
"ounce_price_ask": "1729.54",
"ounce_price_bid": "1729.03",
"ounce_price_usd_today_low": "1724.91",
"ounce_price_usd_today_high": "1730.33",
"usd_to_mad": "9.871449",
"gmt_mad_updated": "26-05-2020 12:05:00 am",
"ounce_in_mad": 17073.066,
"gram_to_ounce_formula": 0.0321,
"gram_in_usd": 55.518234,
"gram_in_mad": 548.0454
}
I cannot access the individual element that I want which is gram_in_mad, and I cannot understand why. Here is the logger console of Google Apps Script showing me my log lines.
From your question and script,
If the value of This is the JSON data I receive back...in a pretty print visualized format. is the value of JSON.stringify(parsedData), parsedData.gram_in_mad returns 548.0454.
But if the value of This is the JSON data I receive back...in a pretty print visualized format. is the value of parsedData, I thought that in the case of response of var response = UrlFetchApp.fetch(url,params);, parsedData might be the string even when var parsedData = JSON.parse(response.getContentText()); is used.
So how about the following modification?
From:
var parsedData = JSON.parse(response.getContentText());
To:
var parsedData = JSON.parse(JSON.parse(response.getContentText()));

Google Spreadsheet Script: UrlFetchApp upload string as file

I saw this SO thread to upload a file using UrlFetchApp.
Also I saw this SO thread to post a string as file in python requests (without having a file or creating a temp file).
I want to send a string as file in Google Spreadsheet Script, and based on the two threads above I think it should be possible to do it without creating a temp file in google drive.
My question is how in Google Spreadsheet Script I can pretend the string is coming from a file and pass it to UrlFetchApp?
Here is the base code I am working on:
var string = 'test';
var url = "https://api.telegram.org/.../sendDocument";
var chat_id = "12345";
var data = {'chat_id': chat_id,
'text':text} ;
var headers = { "Accept":"application/json",
"Content-Type":"application/json"
};
var options = { "method":"POST",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
Here is how I got it right to post a string as file:
var url = "https://api.telegram.org/.../sendDocument";
var blob = Utilities.newBlob('Test!', 'text/plain', 'report.txt');
var data = {
'chat_id' : '12345',
'document': blob
};
var options = {
'method' : 'POST',
'payload' : data,
};
UrlFetchApp.fetch(url, options);
Thanks to comment from #Jack Brown and google developer example for posting blobs (example titled: Make a POST request with form data.).