How to follow HTTPResponse in Google Apps Script? - google-apps-script

I get this error below when I GET my google apps script.
ERROR: The script completed but did not return anything.
Since I will be posting to my app (which redirects to my app when the post is complete), I should be automatically redirected back to my app?
function doGet(e){
var options = {
"method" : 'POST',
"payload" : "user_id="+e.parameter.user_id+"&gmail="+getEmail()
};
var url = 'http://somedomain.com/users/give_gmail_permission/';
var response = UrlFetchApp.fetch(url, options);
return response;
}
What am I doing wrong? How do I follow HTTPResponse in Google Apps Script?

change the line:
return response
for
return HtmlService.createHtmlOutput("<b>"+response.getResponseCode()+"</b><br>"+response.getContentText()).
setSandboxMode(HtmlService.SandboxMode.NATIVE);
the modified script:
function doGet(e){
var options = {
"method" : 'POST',
"payload" : "user_id="+e.parameter.user_id+"&gmail="+getEmail()
};
var url = 'http://somedomain.com/users/give_gmail_permission/';
var response = UrlFetchApp.fetch(url, options);
Logger.log("response code: "+response.getResponseCode());
Logger.log("response: "+response.getContentText());
return HtmlService.createHtmlOutput("<b>"+response.getResponseCode()+"</b><br>"+response.getContentText()).
setSandboxMode(HtmlService.SandboxMode.NATIVE);
}

Related

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

How to integrate Gumroad API with Google Apps Script

I'm trying to see if a user is a paying customer for my gumroad product. I'm trying to integrate the Gumroad API to Google Apps Script.
I have the following code
function checkAccount(){
var token = <<token>>;
var userEmail = Session.getActiveUser().getEmail();
var url = "https://api.gumroad.com/v2/sales";
var headers = {"access_token=" : token};
var options = {
"method" : "GET",
"email" : userEmail,
"headers" : headers
};
var response = UrlFetchApp.fetch(url, options);
var jsonObject = JSON.parse(response.getContentText());
Logger.log(jsonObject);
}
I get the following error Exception: Request failed for https://api.gumroad.com returned code 401 which Gumroad is telling me 401 Unauthorized you did not provide a valid access token. I've checked the token and it's correct. I've logged the options and headers, and they show up correctly.
I'm just not sure why it's giving me a 401.
Try changing headers to this:
var headers = {
"Authorization": `access_token=${token}`
};
EDIT:
Based on this you could try:
headers: {
Authorization: `Bearer ${token}`}

Set up Twilio Client in a google apps script

Would any one have a sample script or method how to setup Twilio Client to make and receive calls directly in a browser with Google apps script as a webapp or the like.
Here is how to initiate a Twilio call from GAS, but I can't seem to figure out how to do Twilio Client.
function makeCall() {
var to = "+1xxxxxxxxxx";
var from = "+1xxxxxxxxxx";
var callsUrl = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxx/Calls.json";
var payload = {
"To": to,
"From" : from,
"Twiml" : '<Response><Say>Hello this is a Twilio call</Say></Response>',
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxxxxxxxxxxx:xxxxxxxxxxxxxx")
};
var res = UrlFetchApp.fetch(callsUrl, options);
Logger.log(res);
}

Using Google Apps Script and the Pastebin.com API to post a paste

I am trying to make a Pastebin.com paste using Google Apps Script from the spreadsheet script editor. Can anyone tell me what I'm doing wrong?
function postPastebinPost() {
var options, url, apiKey, payload, response;
apiKey = <api key goes here>;
payload = 'Hello World';
options = {
'method' : 'post',
'payload' : payload
};
url = 'https://pastebin.com/api/api_post.php'
+ '?api_dev_key=' + apiKey
+ '&api_option=paste'
+ '&api_paste_code=' + encodeURIComponent(payload);
response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I run this and my log reads Bad API request, invalid api_option. I've searched for solutions but I have not found any.
Documentation:
• Pastebin.com API
• Google Apps Script's UrlFetchApp Class
The parameters should be passed in the payload of the POST request.
function postPastebinPost() {
var apiKey = 'YOUR KEY GOES HERE';
var text = 'Hello World';
var payload = {
api_dev_key: apiKey,
api_option: 'paste',
api_paste_code: text
};
var options = {
method : 'POST',
payload: payload
};
var url = 'https://pastebin.com/api/api_post.php';
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
The following is in case the user wants to create a new paste as part of their own Pastebin account (and not «Paste as a guest»). It's just an adaptation of Amit Agarwal's answer.
function postPastebinPost() {
var title = 'abc';
var contents = 'Hello World \n next line of content \n more text';
var payload = {
api_dev_key: 'aa6f3ab...', // https://pastebin.com/api#1
api_option: 'paste',
api_paste_name: title,
api_paste_code: contents,
api_paste_private: '0', // public paste
api_user_name: 'diccionario...', // name of your Pastebin account
api_user_password: 'dk398d...', // password to your Pastebin account
api_user_key: '39dk3...', // https://pastebin.com/api/api_user_key.html
};
var options = {
method : 'POST',
payload: payload
};
var url = 'https://pastebin.com/api/api_post.php';
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
The whole documentation is at https://pastebin.com/api.

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.).