Call external Api with Bearer Token From google App Script - google-apps-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.

Related

how to call Google Local Services API from Google Sheets App 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()
}
});}

Sheets & Appscripts Hubspot POST Request with Authentication Token Problem

I've created a GAS app to provide better pipeline reporting from our Hubspot instance. So far the app works and I have successfully created a Sales Pipeline that shows up in Google sheets. I am trying to add a capability that requires a POST method to query Hubspot's CRM V3. I got it to work in Postman but cannot replicate it in GAS.
The error I get is "Authentication credentials not found." The headers print to the log so I assume they are being generated properly. My guess is that my access Token and payload are not being passed properly to the API during the request. Any help on the matter would be much appreciated.
function getConversions() {
// Prepare authentication to Hubspot
var service = getService();
var headers = {headers: {'Authorization': 'Bearer ' + service.getAccessToken()}};
Logger.log(headers);
var raw = JSON.stringify({"filterGroups":[{"filters":[{"propertyName":"hs_analytics_last_visit_timestamp","operator":"GT","value":"1561514165666"}]}],"limit":100,"after":0});
var options = {
'method' : 'post',
headers: headers,
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
body : raw,
redirect: 'follow',
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch('https://api.hubapi.com/crm/v3/objects/contacts/search?', options);
var result = JSON.parse(response.getContentText());
Logger.log(result);
};
How about this modification?
Modification points:
When I checked the official document of Search of HubSpot API, I found the curl sample. When this sample is converted to Google Apps Script, I noticed several modification points in your script.
UrlFetchApp.fetch has no properties of body and redirect.
About followRedirects, the official document says as follows.
If false the fetch doesn't automatically follow HTTP redirects; it returns the original HTTP response. The default is true.
In your URL, https://api.hubapi.com/crm/v3/objects/contacts/search? is used. If you don't use the API key, how about modifying to https://api.hubapi.com/crm/v3/objects/contacts/search?
When above modification is reflected to your script, it becomes as follows.
Modified script:
Please modify as follows.
From:
var options = {
'method' : 'post',
headers: headers,
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
body : raw,
redirect: 'follow',
"muteHttpExceptions": true
};
To:
var options = {
method : 'post',
headers: headers,
contentType: 'application/json',
payload : raw,
muteHttpExceptions: true
};
Note:
Above modification is required for your script. But I'm worry about the error of Authentication credentials not found.. In this modification, it supposes that your access token of service.getAccessToken() can be used for this request. When I saw the official document, the API key can be also used. If the access token cannot be used, how about using the API key? It's like below.
https://api.hubapi.com/crm/v3/objects/contacts/search?hapikey=YOUR_HUBSPOT_API_KEY
References:
Search of HubSpot API
fetch(url, params)
function getConversions() {
// Prepare authentication to Hubspot
var service = getService();
var headers = {headers: {'Authorization': 'Bearer ' + service.getAccessToken()}};
var url = 'https://api.hubapi.com/crm/v3/objects/contacts/search'
//Logger.log(headers);
var raw = {"filterGroups":[{"filters":[{"propertyName":"hs_analytics_last_visit_timestamp","operator":"GT","value":"1561514165666"}]}],"limit":100,"after":0};
var options = {
method : 'post',
contentType: "application/json",
// Convert the JavaScript object to a JSON string.
payload : JSON.stringify(raw),
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch('https://api.hubapi.com/crm/v3/objects/contacts/search?hapikey=myapikey',options);
var result = JSON.parse(response.getContentText());
Logger.log(response)
Logger.log(result);
};

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.

Blank response from UrlFetchApp in Google App Script

I'm trying to test the endpoints of an API and all the responses return blank with no errors.
I've tested using curl and the response actually has data in:
curl --request GET https://myapiurl.com/endpoint --header "authorization: bearer TOKEN"
Here's the segment of GAS code. The token property is set when I run a POST call to retrieve it, it expires after a while:
var url = 'https://myapiurl.com/endpoint';
var token = 'bearer TOKEN';
var headers = {
'authorization': token
};
var options = {
'headers' : headers
};
var response = UrlFetchApp.fetch(url,options);
var data = JSON.parse(response.getContentText());
The response should be a JSON object with a full list of keys/values. The response from curl is exactly what it should be, but the GAS version is blank, no errors.
I am completely at a loss, any help would be much appreciated!

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
}