OAuth problem with Apps Script and Google Chat - google-apps-script

I'm currently trying to make a google chat bot on Apps Script, using webhooks that supposedly don't require any authentification.
However, when I run my Apps Script function from Apps Script, it seems like I have to allow my account to "use external web apps" or something along these lines.
I developped the Apps Script as an API, so that I could call the functions from an external point, but it says that I need OAuth credentials to do so. And I know how to implement OAuth credentials, I just have no idea what scope I'm supposed to use since webhooks are supposed to work without authentification.
Here's the function:
function sendText(text) {
var url = "https://chat.googleapis.com/v1/spaces/[space]/messages?key=[webhook-key]&token=[token]";
message = { 'text': text };
var message_headers = {};
const response = UrlFetchApp.fetch(url, {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(message),
});
Logger.log(response);
}

okay I found the answer myself;
scope is : https://googleapis.com/auth/script.external_request

Related

Google app script runs in debug mode, not in run mode

Hello Google Script experts, I'm new to google script and trying something related to HTTP POST from google docs.
I've a google app script that sends a post request (API) on opening a google doc.
function onOpen() {
var ui = DocumentApp.getUi(); // Same variations.
var actDoc = DocumentApp.getActiveDocument();
var docID = actDoc.getId();
var repeater = 0;
var data = {
'bstask': text,
'docid': docID
};
console.log(data);
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
ui.alert("Sending request with the payload" + data.bstask + " and " + data.docid);
var response = UrlFetchApp.fetch('https://test.com/path', options);
ui.alert("Response is: " + response.getResponseCode());
if (response.getResponseCode() == 200) {
Logger.log(response.getContentText() + response.getAllHeaders());
ui.alert('Yey!! Document refreshed.');
}
else{
ui.alert('Opps!! Document refresh failed.'+ response.getContent());
}
}
This script is used to provide an option to the user to update the document when it is opened or refreshed. This script runs fine and invoking the API when I test it in debug mode. But, when I want this script to be executed on opening the document, it is not invoking the API and the rest of the UI prompts are working fine. Am I missing something here or something wrong with the script? I really appreciate any help!!
Simple Triggers – Restrictions
Because simple triggers fire automatically, without asking the user for authorization, they are subject to several restrictions:
They cannot access services that require authorization. For example, a simple trigger cannot send an email because the Gmail service requires authorization, but a simple trigger can translate a phrase with the Language service, which is anonymous.
In other words, the UrlFetchApp.fetch() call will not execute when opening the document because it requires authorization. You should be able to see this failure in the execution logs as well.

Publish a AppScript Project as a webApp from the same Script file

I want to create a method, with which I can publish a appScript code as a webapp from the same script file.
Though there are REST api to do the same, I am trying to figure out a wat to do it though appScript it self.
You can deploy a web app from any script project, including a script project that is bound to a Docs Editor file such as a spreadsheet.
See the Web App Demo answer for more information and sample code.
Answer
There is no method within the ScriptApp class to deploy.
Work-around
You can make an API call to the projects.deployments.create method with the UrlFetchApp class. In order to make a successful call you must activate the Apps Script API.
var scriptId = 'some id'
var url = `https://script.googleapis.com/v1/projects/${scriptId}/deployments`
var formData = {
"versionNumber": 1,
"description": "DeployFromApi",
"manifestFileName": "appsscript"
}
var options = {
'method' : 'post',
'payload' : formData
};
UrlFetchApp.fetch('https://httpbin.org/post', options);

Programmatically connect Sheets / request access

Is there a way for Google Script to request access to a Google Sheet using the Document Key? I've tried openById() and was hoping for it to trigger a request, but nope...
I have found a way which seems to work for me, but I will caveat it with the fact that it is not documented, so neither likely to be supported or recommended, and I imagine it could probably change at any time.
It requires making OAuth2 authenticated requests with the server, so there are a number of steps involved:
Ensure Drive is an enabled scope on your script
Under File > Project Properties > Scopes, check that the following scope is listed:
https://www.googleapis.com/auth/drive
If it isn't listed then running a simple call like:
DriveApp.createFile('', '');
Should prompt you to allow access to Drive. Once done, you can remove this line from your script.
Verify that the required Drive scope is now listed.
Make a request for the file you wish access for
This sample function worked for me, but YMMV:
function requestShare(spreadsheetId) {
var request = {
requestType: 'requestAccess',
itemIds: spreadsheetId,
foreignService: 'explorer',
shareService: 'explorer',
authuser: 0
};
var url = 'https://docs.google.com/sharing/commonshare';
var params = {
method: 'POST',
payload: request,
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
},
contentType: 'application/x-www-form-urlencoded'
};
var response = UrlFetchApp.fetch(url, params);
Logger.log(response.getContentText());
}
Call the requestShare function with the ID of the spreadsheet you are wishing to request access to.
I tested this between two accounts, and received sharing request emails, which when clicked, showed the dialog with the correct requestor details in.
Hope this helps.

How can I call to Smartsheet API using Google Apps script?

I have used Postman and Charles to see if my Smartsheet GET function works, and all is well, I get the data json string back.
I have tried running the call from local code and from a Google app script html page.
But I get this error from the Google app script page:
"XMLHttpRequest cannot load https://api.smartsheet.com/2.0/sheets/ MY SMART SHEET ID. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://n-n662xy6uqbadudjpoghatx4igmurid667k365ni-script.googleusercontent.com' is therefore not allowed access."
It is my aim to update a Google sheet automatically from a Smartsheet sheet.
My Ajax request looks like this:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.smartsheet.com/2.0/sheets/SHEET_ID",
"method": "GET",
"headers": {
"authorization": "Bearer MY_SECRET_ACCESS_TOKEN",
"cache-control": "no-cache",
"postman-token": "SOME_LONG_TOKEN"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
You cannot call the Smartsheet API from client-side JavaScript due to the fact that the API doesn't support CORS at this time.
You can call the Smartsheet API directly from a Google Apps Script. In fact, we/Smartsheet publish two Google Add-ons that both use the Smartsheet API from scripts (1,2).
The Google apps-script-oauth2 project provides a complete example of using the Smartsheet API in their sample directory on GitHub. See samples/Smartsheet.gs.
With the OAuth token out of the way, you can make requests to the Smartsheet API like so:
var url = 'https://api.smartsheet.com/2.0/users/me';
var options = {
'method': 'get'
, 'headers': {"Authorization": "Bearer " + getSmartsheetService().getAccessToken() }
};
var response = UrlFetchApp.fetch(url, options).getContentText();
Logger.log("email:" + JSON.parse(response).email);
Note that getSmartsheetService() in the above example is just like getDriveService() in Google's Readme except for Smartsheet. The full code is below:
function getSmartsheetService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('scott_smartsheet')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://app.smartsheet.com/b/authorize')
.setTokenUrl('https://api.smartsheet.com/2.0/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId(SMARTSHEET_CLIENT_ID)
.setClientSecret(SMARTSHEET_CLIENT_SECRET)
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
.setScope('READ_SHEETS')
// Set the handler for adding Smartsheet's required SHA hash parameter to the payload:
.setTokenPayloadHandler(smartsheetTokenHandler)
;
}
Under external APIs under Google Apps Script API,
Google Apps Script can interact with APIs from all over the web.
Connecting to public APIs
Dozens of Google APIs are available in Apps Script, either as built-in services or advanced services. If you want to use a Google (or non-Google) API that isn't available as an Apps Script service, you can connect to the API's public HTTP interface through the URL Fetch service.
The following example makes a request to the YouTube API and returns a feed of videos that match the query skateboarding dog.
var url = 'https://gdata.youtube.com/feeds/api/videos?'
+ 'q=skateboarding+dog'
+ '&start-index=21'
+ '&max-results=10'
+ '&v=2';
var response = UrlFetchApp.fetch(url);
Logger.log(response);
Here is a related SO ticket that connected his code in google apps script to smartsheet api.

Calling a Google Apps Script web app with access token

I need to execute a GAS service on behalf of a user that is logged to my system. So I have her/his access token. I would like somehow to transfer the token to the web app and without having to authorize again the user to use it for some activities. Can this be accomplished? Thank you.
EDIT: I think I didn't explain right what I try to accomplish. Here is the work flow I try to achieve:
We authorize a user visiting our website using OAuth2 and Google;
We get hold of her/his access token that Google returns;
There is a Google Apps Script web app that is executed as the user running the web app;
We want to call this app (3) by providing the access token (2) so Google not to ask again for authorization;
Actually, we want to call this app (3) not by redirecting the user to it but by calling it as a web service.
Thanks
Martin's answer worked for me in the end, but when I was making a prototype there was a major hurdle.
I needed to add the following scope manually, as the "automatic scope detection system" of google apps script did not ask for it: "https://www.googleapis.com/auth/drive.readonly". This resulted in UrlFetchApp.fetch always giving 401 with additional information I did not understand. Logging this additional information would show html, including the following string
Sorry, unable to open the file at this time.</p><p> Please check the address and try again.
I still don't really understand why "https://www.googleapis.com/auth/drive.readonly" would be necessary. It may have to do with the fact that we can use the /dev url, but who may use the /dev url is managed is checked using the drive permissions of the script file.
That said, the following setup then works for me (it also works with doGet etc, but I chose doPost). I chose to list the minimally needed scopes explicitly in the manifest file, but you can also make sure the calling script will ask for permissions to access drive in different ways. We have two google apps script projects, Caller and WebApp.
In the manifest file of Caller, i.e. appsscript.json
{
...
"oauthScopes":
[
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/script.external_request"]
}
In Code.gs of Caller
function controlCallSimpleService(){
var webAppUrl ='https://script.google.com/a/DOMAIN/macros/s/id123123123/exec';
// var webAppUrl =
// 'https://script.google.com/a/DOMAIN/macros/s/id1212121212/dev'
var token = ScriptApp.getOAuthToken();
var options = {
'method' : 'post'
, 'headers': {'Authorization': 'Bearer '+ token}
, muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(webAppUrl, options);
Logger.log(response.getContentText());
}
In Code.gs of WebApp (the web app being called)
function doPost(event){
return ContentService.createTextOutput("Hello World");
}
The hard answer is NO you can't use the built-in services of Apps Script with a service token. But if you already have the token for a user generated by a service account, access to the users data is pretty similar to any other language. All calls would be to the REST interface of the service your token is scoped for.
Take this small script for example. It will build a list of all the user's folders and return them as JSON:
function doGet(e){
var token = e.parameter.token;
var folderArray = [];
var pageToken = "";
var query = encodeURIComponent("mimeType = 'application/vnd.google-apps.folder'");
var params = {method:"GET",
contentType:'application/json',
headers:{Authorization:"Bearer "+token},
muteHttpExceptions:true
};
var url = "https://www.googleapis.com/drive/v2/files?q="+query;
do{
var results = UrlFetchApp.fetch(url,params);
if(results.getResponseCode() != 200){
Logger.log(results);
break;
}
var folders = JSON.parse(results.getContentText());
url = "https://www.googleapis.com/drive/v2/files?q="+query;
for(var i in folders.items){
folderArray.push({"name":folders.items[i].title, "id":folders.items[i].id})
}
pageToken = folders.nextPageToken;
url += "&pageToken="+encodeURIComponent(pageToken);
}while(pageToken != undefined)
var folderObj = {};
folderObj["folders"] = folderArray;
return ContentService.createTextOutput(JSON.stringify(folderObj)).setMimeType(ContentService.MimeType.JSON);
}
You do miss out on a lot of the convenience that makes Apps Script so powerful, mainly the built in services, but all functionality is available through the Google REST APIs.
I found a way! Just include the following header in the request:
Authorization: Bearer <user's_access_token>