UrlFetchApp fetch a google apps script - google-apps-script

From a Google apps script I'm trying to use UrlFetchApp to fetch another Google apps script. I tried to make it as basic as possible but it's still giving me an error.
The first script called 'frontend' executes as the user and the second script 'backend' executes as the owner of 'backend'.
frontend
var backend = 'https://script.google.com/macros/s/AKfycbwdwQdYYMwqofjEqFn3ozz_LqQ87qj7ZX19sYmelX9dUtP8aNxf/exec';
function doGet(e) {
return UrlFetchApp.fetch(backend)
}
backend
function doGet(e) {
return doPost(e);
}
function doPost(e) {
var app = UiApp.createApplication();
app.add(app.createLabel('Backend'));
return app;
}
frontend is published here
extra information
Logger.log(UrlFetchApp.getRequest(backend)) =>
{useIntranet=false,
followRedirects=true,
payload=,
method=get,
validateHttpsCertificates=true,
contentType=application/x-www-form-urlencoded,
url=https://script.google.com/macros/s/AKfycbwdwQdYYMwqofjEqFn3ozz_LqQ87qj7ZX19sYmelX9dUtP8aNxf/exec}
Using instead an html form I can correctly sent POST/GET parameters from one google script to another using hidden input elements to define parameters.
If I try to do what the html form is doing using javascript - jquery ajax the request returns an error.
I'm very confused as to why a simple html form within a google script can request another google script but a javascript request from a google script to another google script is denied by what appears to be security policy issues.

You dont say how youve published them exactly but i bet your backend isnt published to allow anonymous users. Do so.

Related

Oauth2 service creation hasAccess() fails in Google Sheets script for all users except owner

I'm using the https://github.com/googleworkspace/apps-script-oauth2 library in a Google Sheet script to call an external API. It works well for the owner of the sheet. For all other users it fails in creating the service/property store? It fails the "Service.hasAccess()" condition.
I suspect I am missing some sort of permissions somewhere. I have given users Edit permissions on the Sheet and have gone through other various gyrations trying to figure this out. I decided to apply this script via a Standard Project.
Scope are applied explicitly in the manifest and all works swimmingly for the sheet owner.
''''''''Google Apps Script, Spreadsheet Script in GCP Standard Project
function authorizeUser() {
var myService = getMyService();
if (myService.hasAccess()) {
>FAILS THIS CONDITION for all except spreadsheet owner
}
}
function getMyService() {
return OAuth2.createService('sky')
.setAuthorizationBaseUrl('https://oauth2../authorization')
.setTokenUrl('https://oauth2.../token')
.setClientId('fee......')
.setClientSecret('Ighh.....')
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
//.setScope('https://www.googleapis.com/auth/drive')
// Below are Google-specific OAuth2 parameters.
.setParam('login_hint', Session.getEffectiveUser().getEmail())
}
>I believe the failure is occurring in OAuth2.gs here
function createService(serviceName) {
return new Service_(serviceName);
}
OAuth2.gs: https://github.com/googleworkspace/apps-script-oauth2/tree/master/dist
Any thoughts?
D M
Apparently the suggested code to validate the service state in the apps-script-oauth2 library is not indicative of whether or not the Oauth process can be completed.
Direct the user to the authorization URL
Apps Script UI's are not allowed to redirect the user's window to a new URL, so you'll >need to present the authorization URL as a link for the user to click. The URL is >generated by the service, using the function getAuthorizationUrl().
function showSidebar() {
var driveService = getDriveService();
if (!driveService.hasAccess()) {
I was able to complete my Oauth process regardless of the state returned by has.Access() . I'm not sure if this is a time sensitive operation or something else is at play. At any rate I was able to proceed and develop a final solution as a GAS web app.

HTTP Request to a function in Google Scripts

Since I'm not experienced at all with HTTP Request and Google Scripts, I'm having trouble wraping my head around it.
So, my problem is the following:
I'm currently trying to get information in my lua script and send it to a google Spreadsheet. However, the way the google spreadsheet should save the info would be dependent on which function on the Google Script I'm calling and passing information.
SO, my question is: How would my lua script (that only gives me access to HTTP Requests at this time) connect to a specific function like the one bellow?
function callName(name) {
// Get the last Row and add the name provided
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow() + 1,1).setValue([name]);
}
Also, I think my script is wrong as well, but I'm more worried about how to actually make the connection.
Answer:
You can publish your script as a Web Application and use URL parameters to pass the script the information you need.
More Information:
From the Google documentation about web apps:
If you build a user interface for a script, you can publish the script as a web app. For example, a script that lets users schedule appointments with members of a support team would best be presented as a web app so that users can access it directly from their browsers.
However, even without building a user interface, you can use this functionality to run scripts on your sheet by utilising HTTP requests.
Modifying your Script:
In order to allow your script to accept URL parameters, you must first modify your code so that processing is done on a HTTP GET request. You can do this with the Apps Script doGet() function and the event parameter e:
function doGet(e) {
callName(e.parameter.name);
}
function callName(name) {
// Get the last Row and add the name provided
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow() + 1,1).setValue([name]);
}
Setting up the Web App:
From the Apps Script user interface, follow the Publish > Deploy as web app... menu item, and in the newly-opened modal window, you'll want to select the following settings:
Project version: New
Execute the app as: Me (your-email#address.here)
Who has access to the app: Anyone, even anonymous
And click Deploy. Here, you will be given a URL in a new, smaller modal in the following form:
https://script.google.com/a/your-domain.com/macros/s/some-script-id/exec
Making the request:
The rest of this is now trivial - you can make your HTTP request to the script URL in the previous step, but providing the URL parameter that you need in order to give te app the information of the value you wish to set.
For example, if you want to set the value to the number 20, make your get request as so:
GET https://script.google.com/a/your-domain.com/macros/s/some-script-id/exec?name=20
Note the ?name=20 at the end gives the Web App the parameter name with a value of 20. The doGet(e) function reads this from e.parameter.name and sends it to your callName(name) function for processing and execution.
References:
Web Apps | Apps Script | Google Developers
Request Parameters

Apps Script Refused to Connect

I am trying to learn Apps Script and some fron-end web dev. I wrote some some code in Apps Script and I am trying to render it in a Google Site.
Here is the doGet function that I use in my Apps Script:
function doGet() {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Interestingly, the script renders itself when I use the Google-given URL:
https://sites.google.com/corp/view/vrajlinkshortener
However, that is not the case when I enter the custom domain:
www.wharton.ml
I checked the documentation and I still could not figure out why a custom domain would prohibit Apps Script form working.
Any tips? Thanks!
You need to set the option XFrameOptionsMode to ALLOWALL.
XFrameOptionsMode
https://developers.google.com/apps-script/reference/html/x-frame-options-mode
Setting XFrameOptionsMode.ALLOWALL will let any site iframe the page, so the developer should implement their own protection against clickjacking.
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
As stated in the comments below (Shan Eapen Koshy said) check that your browser is logged into one Google account only.
Just add below, it is working
function doGet(e){
var temp = HtmlService.createTemplateFromFile('html')
return temp.evaluate().setTitle("Booking Window").setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}

receive parameters from another server POST request using apps script

I have some technical question about using apps script.
A third party server is sending me parameters in POST method and the request looks like this: https://script.google.com/macros/s/AKfycbyJYVLO46T1LnQKktaMrROclCOqgawcVfZaRbm_oXfJaMIYcPj8/exec?value=$postback_params_test$ (so I need to receive $postback_params_test$ as value)
I used doPost(e) function but with no success, I thing the problem is because apps script is based on client java script and it c'ant talk with server language, am I right? or there is an option to do it anyway through apps script?
my code:
function doPost(e){
var param = e.parameter.value;
var doc = SpreadsheetApp.openById("106jpepwZZWXtpO4Id45qmJovV68q_DIqpEmTQ0khf4E");
var cell = doc.getRange('a1');
cell.setValue(param);
}
8.6
Image added:
enter image description here
When deployed as a web app with settings "execute as: me" and "who has access to the app: anyone, even anonymous" your example code works.
Did you authorize the code? Before you can run it as a web app, you must run doPost() (or another function) once manually from within the script editor, so you can grant the appropriate permissions to the script.
If it's not the authorization issue, you can add a MailApp.sendemail() call to help you troubleshoot.
function doPost(e) {
MailApp.sendEmail('YOUR-EMAIL HERE','TEST doPost()',JSON.stringify(e));
This way you'll receive an email showing the raw request coming from the other server.
Be sure to re-run the script manually after adding the MailApp line so you can authorize it to send email, and update the published version.

How can I call Google Charts API from UrlFetch service in Google App Script?

I'm trying to write sort of a proxy to be able to query a Google Spreadsheet with Google Chart API without giving rights directly to the spreadsheet to people accessing the visualization.
In order to do that, I want to replace the calls like
var query = new google.visualization.Query('http://spreadsheets.google.com/tq?key=THE_KEY');
query.send(handleQueryResponse);
by calls of my Apps Script proxy (with JSONP).
I wrote the proxy as following :
(I'll add later an option to encapsulate the result in a function - JSONP)
function doGet(e) {
return ContentService
.createTextOutput(
UrlFetchApp
.fetch("http://spreadsheets.google.com/tq?tq="+e.parameter.q+"&key="+e.parameter.key))
.setMimeType(ContentService.MimeType.JSON);
}
When trying to get a response, I obtain this error : google.visualization.Query.setResponse({"version":"0.6","status":"error","errors":[{"reason":"user_not_authenticated","message":"User not signed in","detailed_message":"\u003ca target=\u0022_blank\u0022 href=\u0022https://spreadsheets.google.com/spreadsheet/\u0022\u003eSign in\u003c/a\u003e"}]});
like if the user was not authenticated. I think it's weird because my script is deployed as a web app to be executed by my user, who has the rights on the spreadsheet. I guess we must use some OAuth, but I don't know how to authenticate the query that way.
So my question is :
How to authenticate a query with Apps Script to access data with the access rights I defined when deploying as web app ?
See the urlfetch docs. You are missing all the oauth stuff.
The way you are doing it will only work for a public ss.