how to call Google Local Services API from Google Sheets App script - google-apps-script

I am attempting to call Google Local Services API inside Google AppScript, I have followed the documentationDOCUMENTATION and a Guide but couldn't generate a token with .getAccessToken() how can i get it work?
function makeRequest() {
var adsService = getAdsService();
console.log(adsService.getAccessToken()) //I am Not getting Token here
var response = UrlFetchApp.fetch('https://localservices.googleapis.com/v1/accountReports:search?query=manager_customer_id:1GRTlAnR5J0YQmBJs2UixjAhpN34xHfwwkgv9S0XGSRZP-V_LMv5lU_7S', {
headers: {
Authorization: 'Bearer ' + adsService.getAccessToken()
}
});}

Related

Call external Api with Bearer Token From google App Script

I am calling External web api with Bearer Authorization Token from google AppScript but getting Bearer Token null. I tried from Postmann it is working properly but from appscript i am getting Authorization Null.
Here is my google App Script Code:
var headers = { Authorization: 'Bearer Token'
};
var requestOptions = {
'method': 'GET',
'header':headers,
'redirect': 'follow',
'muteHttpExceptions':true
};
var res=UrlFetchApp.fetch('myapp/api/getxml', requestOptions); //Add RESTAPI Endpoint where
var json=res.getContentText();
Logger.log(res);
can you please check and tell me if i am missing something.
Thank you so much for your time.

Google Ads API with Google Apps Script no access token received

I am trying to use Google Ads on Google Apps Script using this guide. I created client id and client secret on Google Console's API & Services.
Not too sure if this configuration is correct but the account is linked to Google Apps Script as I have pagespeed insights as well and there are some requests on the dashboard. I added https://www.googleapis.com/auth/drive as the scope. Again not too sure if I should add Google Ads to the scope. Lastly, got my refresh token from Google Auth playground. When I run the script above I got the following error:
Error: No access token received: {
"error": "invalid_client",
"error_description": "Unauthorized"
}
authenticate_ # test.gs:120
withRefreshToken # test.gs:144
initializeOAuthClient # test.gs:28
Honestly not too sure what I am doing wrong here so any help would be very much appreciated. Thank you.
Edit
Codes:
//From Google Console API & Services
var CLIENT_ID = '"MY_CLIENT_ID';
var CLIENT_SECRET = 'MY_CLIENT_SECRET';
//From Google Authplayground
var REFRESH_TOKEN = 'REFRESH_TOKEN';
// Enter scopes which should match scopes in File > Project properties
// For this project, e.g.: https://www.googleapis.com/auth/drive
var SCOPES = "https://www.googleapis.com/auth/adwords";
// Script ID taken from 'File > Project Properties'
var SCRIPT_ID = 'MY_SCRIPT_ID';
var authUrlFetch;
// Call this function just once, to initialize the OAuth client.
function initializeOAuthClient() {
if (typeof OAuth2 === 'undefined') {
var libUrl = 'https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library';
throw Error('OAuth2 library not found. Please take a copy of the OAuth2 ' +
'library from ' + libUrl + ' and append to the bottom of this script.');
}
var tokenUrl = 'https://accounts.google.com/o/oauth2/token';
authUrlFetch = OAuth2.withRefreshToken(tokenUrl, CLIENT_ID, CLIENT_SECRET,
REFRESH_TOKEN, SCOPES);
}
/**
* Execute a remote function.
* #param {string} remoteFunctionName The name of the function to execute.
* #param {Object[]} functionParams An array of JSON objects to pass to the
* remote function.
* #return {?Object} The return value from the function.
*/
function executeRemoteFunction(remoteFunctionName, functionParams) {
var apiParams = {
'function': remoteFunctionName,
'parameters': functionParams
};
var httpOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
payload: JSON.stringify(apiParams)
};
var url = 'https://script.googleapis.com/v1/scripts/' + SCRIPT_ID + ':run';
var response = authUrlFetch.fetch(url, httpOptions);
var data = JSON.parse(response.getContentText());
// Retrieve the value that has been returned from the execution.
if (data.error) {
throw Error('There was an error: ' + response.getContentText());
}
return data.response.result;
}
// Paste in OAuth2 library here, from:
// https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library
I have pasted the oauth2.0 library under the codes above.
Edit 2
I fixed the part of function initializeOAuthClient. It now shows execution complete, but when I try to run function executeRemoteFunction I am getting TypeError: Cannot read property 'fetch' of undefined. I am guessing I have to input remoteFunctionName and functionParams but where do I find them?

Upload to Google Cloud storage from App Script

I've been bashing my head at this for over a day, but I can't figure out how to upload data to Google Cloud Storage via an app script attached to a google sheet. I've been running into issues with authorisation. I've copied the getService method from here (pasted below) but the service keeps failing to receive authorisation. service.hasAccess() always returns false.
function uploadFileToGCS(dataJSON) {
var service = getService();
if (!service.hasAccess()) {
Browser.msgBox("Failed to grant service access")
return;
}
var url = 'https://www.googleapis.com/upload/storage/v1/b/BUCKET/o?uploadType=media&name=FILE'
.replace("BUCKET", params.BUCKET_NAME)
.replace("FILE", encodeURIComponent(params.FILE_PATH));
var response = UrlFetchApp.fetch(url, {
method: "POST",
payload: dataJSON,
contentType: "application/json",
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
}
function getService() {
return OAuth2.createService('ctrlq')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId(params.CLIENT_ID)
.setClientSecret(params.CLIENT_SECRET)
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('https://www.googleapis.com/auth/devstorage.read_write')
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force')
.setParam('login_hint', Session.getActiveUser().getEmail());
}
function authCallback(request) {
var service = getService();
var authorized = service.handleCallback(request);
if (authorized) {
return HtmlService.createHtmlOutput('Connected to Google Cloud Storage');
} else {
return HtmlService.createHtmlOutput('Access Denied');
}
}
I've created OAUTH credentials for a web-app on the Google Cloud Console. I've also enabled the Cloud Storage API and Google Cloud Storage JSON API. I'm unsure however on the redirect URL. (Ideally, I'd like to use a service account because I just want to take the values from the spreadsheet and upload them as a JSON file.)
Anyway, appreciate the help!
I think google app script project and google cloud project should be linked. You need to create a google cloud project to use this API.
I encountered a similar problem when I wanted to duplicate an object in Cloud Storage. Not sure if this is the solution for you, but I'm putting it here in case someone need it.
Just use the XML-formmatted REST API with OAuth2 token, and the code looks like this:
var objectSource = "SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME";
var url = "https://storage.googleapis.com/DESTINATION_BUCKET_NAME/NAME_OF_COPY";
var resp = UrlFetchApp.fetch(url, {
method: "PUT",
headers: {
Authorization: 'Bearer '+ OAUTH2_TOKEN,
"x-goog-copy-source": objectSource,
},
'muteHttpExceptions': true,
});
Check out the Cloud Storage's document for differences between copy and upload.

How to call a Web App only available to users inside domain from another google script?

I have a Google script deployed as a web app, unfortunately, due to the company policy, I have to deploy it and make it available to anyone inside the domain, not anyone even anonymous.
Here's the web app code
function doPost(e) {
var functionName = JSON.parse(e.postData.contents).functionName;
return ContentService.createTextOutput(JSON.stringify({result:functionName}))
.setMimeType(ContentService.MimeType.JSON);
}
Here's the Google Script code that I'm trying to call the web app through it, I tried to pass an access token in the request header.
function callWebApp(functionName) {
var response = UrlFetchApp.fetch(url, {
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken(),
},
contentType: 'application/json',
muteHttpExceptions:true,
method : 'post',
payload:JSON.stringify({functionName: functionName}),
});
Logger.log(response)
}
You can use something like the Session service and filter out users who are not in your company domain.
For example:
var user = Session.getActiveUser().getEmail();
if(user.split('#')[1] === 'your.company.domain') {
//do something
}

Google App Scripts and FusionTable

I am working on my first Google App Script (Script as Webapp) and trying to access a fusion table, but each time I try to access the fusion table I get back insufficient privileges. I am logged in as the owner of the app, so I am not sure why this is happening.
function getReports(){
var authToken = ScriptApp.getOAuthToken();
Logger.log(authToken);
var query = encodeURIComponent("Select * from " + tableId);
queryFusionTables(authToken, query);
}
function queryFusionTables(authToken, query) {
var URL = "https://www.googleapis.com/fusiontables/v1/query?sql="+query+"&key={myKey}";
Logger.log(query);
//Logger.log(authToken);
var response = UrlFetchApp.fetch(URL, {
method: "post",
headers: {
"Authorization": "Bearer " + authToken,
"X-JavaScript-User-Agent": "Google APIs Explorer",
},
});
Logger.log(response.getContentText());
return response.getContentText();
}
Does Anyone have any ideas as to why this is happening?
The OAuth token returned by ScriptApp.getOAuthToken() is only authorized for the scopes required by your script, which is determined by the Apps Script services you use. For instance, if you were to use DriveApp the Google Drive API scope would be requested.
The Apps Script code doesn't know you are attempting to use the Fusion Tables API, so it didn't request that scope. However, you are in luck! Apps Script has a built-in integration with Fusion Tables, using the Fusion Tables advanced service. Simply enable the service and Apps Script will take care of the authorization for you, plus provide you with auto-complete.