I am trying to trigger a Google cloud function using an HTTP request from a Google Apps Script connected to Google Sheets.
The cloud function (tested with a dummy request on GCP, this works) essentially gets the latest entry of the sheet as submitted by users using the Appsheet front-end. I would like it to be triggered whenever a new submission occurs. As such, I am using a onChange(e)
trigger to send the request. This is the code I have so far in the appscript.
function onChange(e) {
Logger.log('called');
var url = "https://MY_REGION-MY_PROJECT.cloudfunctions.net/MY_CLOUD_FUNCTION";
const token = ScriptApp.getIdentityToken();
const options = {
headers: {'Authorization': 'Bearer ' + token}
}
const response = UrlFetchApp.fetch(url, options);
Logger.log('Response Code: ' + response.getResponseCode());
}
The stackdriver logs give me the following error when a new Appsheet submission is made (thus calling onChange(e)
):
Exception: Request failed for https://MY_REGION-MY_PROJECT.cloudfunctions.net returned code 401. Truncated server response:
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>401 Unauthorized</title>
</head>
<body text=#000000 bgcolor... (use muteHttpExceptions option to examine full response)
at onChange(Code:9:32)
I have looked at and followed the solutions and comments here and here, but they didn't help me much; that is, I have made sure that the app script is connected to my project, re-deployed the cloud function, and added openid
to the scope to the manifest.
Given that it is still not working, I would like some guidance on this. Am I still missing something here?