SSL Error when making a request via UrlFetchApp - google-apps-script

I'm trying to make a simple GET request to a site with a valid SSL certificate using UrlFetchApp, but I continuously encounter this error:
ScriptError: SSL Error https://dev.kaizena.com/api/config
Interestingly enough, the same request works as expected when I make a request to https://kaizena.com/api/config
Here's the code I'm using:
var url = "https://dev.kaizena.com/api/config";
var payload = JSON.stringify(data);
var headers = { "Accept":"application/json",
"Content-Type":"application/json"//,
};
var options = { "method":"GET",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
}
var response = UrlFetchApp.fetch(url);
Again, the code works as expected if I change the URL to https://kaizena.com/api/config (which also has a valid SSL certificate). Could someone let me know specifically what an "SSL Error" is?
Thanks,
Edward

You can use validateHttpsCertificates to ignore this SSL error.
var options = {
'validateHttpsCertificates' : false
};
var response = UrlFetchApp.fetch(url, options);

It looks like the issue is with Google not recognizing the provider of the SSL Certificate I used. For reference, I was using PositiveSSL, which provided a valid certificate but didn't seem to make Apps Script very happy. I switched to RapidSSL today and now it all works.
Thank you all for the help.

The syntax for urlFetchApp is:
fetch(url)
or
fetch(url, params)
urlFetchApp
You are creating a payload, header and options, but then not using them.
var response = UrlFetchApp.fetch(url);
Should be:
var response = UrlFetchApp.fetch(url, options);

Related

OAuth2 access token coming back as Null in Google App Script

Apologies if this is a silly question, I am very new to programming in general and I have never worked with OAuth before.
I am currently trying to build a Google App Script which interacts with an external service and authenticates using OAuth2.
I am having a lot of trouble with OAuth2... for starters, I'm not sure I am using the correct library for this. I am going off the one recommended by Google for ads script - https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library
I know there is another popular one available in GitHub https://github.com/googleworkspace/apps-script-oauth2
I was not able to use it because everything comes out as 'is not a function', no matter how I add the library, manually or through the built-in feature.
I started building the API call, based on the first library and I had some partial success, I started getting back a 500 error message and I realized my accessToken is null.
function SHICall(){
var tokenUrl = "X/token";
const scriptProperties = PropertiesService.getScriptProperties();
var clientId = scriptProperties.getProperty('CLIENT_ID');
var clientSecret = scriptProperties.getProperty('SECRET');
var opt_scope = "CustomerAPI.Public";
// Access token is obtained and cached.
const authUrlFetch = OAuth2.withClientCredentials(tokenUrl, clientId, clientSecret, opt_scope);
const url = "X";
Logger.log(authUrlFetch);
var options = {
headers: { 'Content-Type': "application/json", 'Accept': "application/json"},
muteHttpExceptions: true,
method: "GET",
contentType: "application/json",
validateHttpsCertificates: false,
};
// Use access token in each request
const response = authUrlFetch.fetch(url, options);
// ... use response
Logger.log(response);
}
Any clue why the token is coming back as null? I based my API Call on google's documentation again https://developers.google.com/google-ads/scripts/docs/features/third-party-apis#oauth_2

How to integrate Gumroad API with Google Apps Script

I'm trying to see if a user is a paying customer for my gumroad product. I'm trying to integrate the Gumroad API to Google Apps Script.
I have the following code
function checkAccount(){
var token = <<token>>;
var userEmail = Session.getActiveUser().getEmail();
var url = "https://api.gumroad.com/v2/sales";
var headers = {"access_token=" : token};
var options = {
"method" : "GET",
"email" : userEmail,
"headers" : headers
};
var response = UrlFetchApp.fetch(url, options);
var jsonObject = JSON.parse(response.getContentText());
Logger.log(jsonObject);
}
I get the following error Exception: Request failed for https://api.gumroad.com returned code 401 which Gumroad is telling me 401 Unauthorized you did not provide a valid access token. I've checked the token and it's correct. I've logged the options and headers, and they show up correctly.
I'm just not sure why it's giving me a 401.
Try changing headers to this:
var headers = {
"Authorization": `access_token=${token}`
};
EDIT:
Based on this you could try:
headers: {
Authorization: `Bearer ${token}`}

Can Google Sites API still be authorized?

I tested it in the Google OAuth 2.0 Playground and it looked like I could return info from the site, but when I set up the OAuth2 code from Github, I can't seem to do a UrlFetchApp request as I get
the error returned code 403. Truncated server response: Not authorized to access this feed
I am not sure if this is because it is not enabled in the API console, but I can't find it there or under Advanced Google Services.
This is the section of code I am falling down at:
var service = getService();
if (service.hasAccess()) {
Logger.log("initial xml has access "service.hasAccess());
var headers = {
"Authorization": "Bearer " + service.getAccessToken()
};
var MyAttachmentsURL = 'https://sites.google.com/feeds/content/[DOMAIN]/[SITE NAME]?kind=attachment';
var response = UrlFetchApp.fetch(MyAttachmentsURL, headers);
};
The script from Github worked for me and I authorized when the message came up. This is what is in my scope tab:
7 OAuth Scopes required by the script:
https://sites.google.com/feeds
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/script.container.ui
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/script.scriptapp
https://www.googleapis.com/auth/spreadsheets
https://www.googleapis.com/auth/userinfo.email
According to the Protocol Guide's "Authorizing requests with OAuth 2.0" You must activate the Google Sites API in the API Console if you can see that option (Step 2).
The only other issue I can see is the requiring to specify a version as GData-Version: 1.4.
So your code would change to something like this:
var service = getService();
if (service.hasAccess()) {
Logger.log("initial xml has access "service.hasAccess());
var headers = {
"GData-Version": "1.4",
"Authorization": "Bearer " + service.getAccessToken()
};
var MyAttachmentsURL = 'https://sites.google.com/feeds/content/[DOMAIN]/[SITE NAME]?kind=attachment';
var response = UrlFetchApp.fetch(MyAttachmentsURL, headers);
};
As long as the scope is mentioned in the code, it doesn't need to be passed, so that wasn't the issue. This was one of many variations I had been trying and I blame missing the post method on it being the wee hours. This code works (for now).
var service = getService();
if (service.hasAccess()) {
Logger.log("initial xml has access "+service.hasAccess());
var headers = {
// "GData-Version" : "1.4",
"Authorization" : "Bearer "+service.token_.access_token
};
var params = {"headers": headers, 'method':'get', 'muteHttpExceptions':true};
var MyAttachmentsURL = 'https://sites.google.com/feeds/content/[DOMAIN]/[SITE NAME]?kind=attachment';
var response = UrlFetchApp.fetch(MyAttachmentsURL, params);
};
It appears that "GData-Version" : "1.4" is returned in the response header so is not needed in the request. What is needed is the access token and although all the other API's seem to be able to make use of .getAccessToken, I had to amend this to .token_.access_token - this may be just for Google Sites.
I appreciate those who had a look at this and thank you Chris for responding.

AUTHENTICATION_FAILED when querying CloudKit public database with CloudKit Web Services API in Google Apps Script

I'm trying to use the CloudKit Web Services API to fetch Article records from my production CloudKit container's public database within Google Apps Script.
My request is based on the documentation on this page.
Here's my code:
// variables for the CloudKit request URL
var path = "https://api.apple-cloudkit.com";
var version = "1";
var container = "iCloud.com.companyname.My-Container-Name";
var environment = "production";
var database = "public";
var token = "8888888888888_my_actual_token_88888888888888888"
function showArticles() {
// assemble the URL
var url = path + "/database/" + version + "/" + container + "/" + environment + "/" + database + "/records/query?ckAPIToken=" + token;
// specify the record type to query
var query = {
recordType: "Article"
};
// specify the payload for the POST request
var payload = {
query : query
};
// set up the fetch options for the fetch request
var options = {
method : "POST",
payload : payload
};
// make the request
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
UrlFetchApp.fetch(url, options) fails with this error:
Request failed for https://api.apple-cloudkit.com/database/1/iCloud.<?>-Container-Name/development/public/records/query?ckAPIToken=8888888888888_my_actual_token_88888888888888888 returned code 401. Truncated server response: {"uuid":"7d8a8547-ad08-4090-b4b3-917868a42f6f","serverErrorCode":"AUTHENTICATION_FAILED","reason":"no auth method found"} (use muteHttpExceptions option to examine full response) (line 30, file "Code")
I've been troubleshooting for a few hours and I can't figure out what I'm doing wrong. I've tried it with a separate token on my development environment, too, and the same thing happens.
This page mentions the ckWebAuthToken parameter and says "if omitted and required, the request fails," but I can't find anything that says what requests require a ckWebAuthToken. I'm assuming I don't need ckWebAuthToken since the records I'm trying to access are in my container's public database, and I'm getting an AUTHENTICATION_FAILED error rather an AUTHENTICATION_REQUIRED error.
One part that confuses me is this URL that comes up in the error message:
https://api.apple-cloudkit.com/database/1/iCloud.<?>-Container-Name/development/public/records/query?ckAPIToken=8888888888888_my_actual_token_88888888888888888
I would expect it to be:
https://api.apple-cloudkit.com/database/1/iCloud.com.companyname.My-Container-Name/development/public/records/query?ckAPIToken=8888888888888_my_actual_token_88888888888888888
But I can't tell if that's actually the URL that's being requested, and when I log the url variable everything looks fine.
Thanks in advance for any troubleshooting tips or solutions!
UPDATE
I tried using Postman, and the request worked with same endpoint and POST data. It looks like the container component of the URL is getting corrupted by the Google Apps Script UrlFetchApp.fetch() method. The <?> seems to only show up when com. is in the URL.
I'm not sure why this is the answer, but I was able to get it working by using JSON.stringify() on the payload in options:
var options = {
method : "POST",
payload : JSON.stringify(payload)
};

bad request with UrlFetchApp

Looking for some help connecting to this service and returning the xml.
Here are the instructions (from here):
The state of the inputs and relays can be monitored by sending a
request to port 80 (or port specified in setup) for the XML page
state.xml. The relays can be controlled by sending GET requests to the
same page on port 80 (or port specified in setup). This can be
demonstrated by entering commands into the URL line of a web browser.
Request the current state: http://"ip address"/state.xml
...
If the control password is enabled in the WebRelay-DualTM unit and
the state.xml page is requested through a browser, the browser will
prompt the user for the password. If the XML request is sent from
another application and not a browser, the html request will need to
contain the password encoded using the base 64 encoding scheme. The
html request header without the password looks like this:
GET /state.xml?relay1State=1&noReply=1 HTTP/1.1 (Ends with two \r\n)
The html request header with the password looks like this:
GET /state.xml?relay1State=1&noReply=1 HTTP/1.1(\r\n here)
Authorization: Basic bm9uZTp3ZWJyZWxheQ== (Ends with two \r\n)
where bm9uZTp3ZWJyZWxheQ== is the base 64 encoded version of the
user name and password none:webrelay
Code:
function webRelay(){
//working url http://75.65.130.27/state.xml
var url = 'http://75.65.130.27/';
var params = encodeURIComponent('state.xml');
Logger.log(params);
var headers = {
"Authorization" : "Basic" + Utilities.base64Encode('none:webrelay')
};
var options =
{
"method" : "get",
"headers" : headers
};
var state = UrlFetchApp.fetch(url+params, options);
Logger.log('1: '+state);
Logger.log(parse(state));
}
function parse(txt) {
var doc = Xml.parse(txt, true);
}
Any help is much appreciated.
There are a couple of coding errors that you can easily take care of:
In the Authorization header you need a space after "Basic".
Authorization : "Basic " + Utilities.base64Encode(username+':'+password)
urlFetchApp.fetch() returns an HTTP Response object, so you need to extract the contents for parsing.
var result = UrlFetchApp.fetch(url, options);
var state = result.getContentText();
You aren't returning anything from your parse() function.
You should check result.getResponseCode() after .fetch(), and handle errors before proceeding with parsing.
That said, I keep getting Bad request: http://75.65.130.27/state.xml errors, so something is still not right. This is an HTTP 400 response, and google's servers don't return anything to the script debugger to dig into it. You should check the username & password, although I'd expect a 401-Unauthorized response if they were wrong. I tried including a payload of relay1State=2, and got the same Bad request result. If you can capture the HTTP Request hitting your server, there may be a clue to what is malformed. This could also be the result of a firewall.
Once that's sorted, this tutorial should help with the XML Parsing.
Here's my edit of your code:
function webRelay(){
var url = 'http://75.65.130.27/state.xml';
var username = "none";
var password = "webrelay";
var headers =
{
Authorization : "Basic " + Utilities.base64Encode(username+':'+password)
}
var options =
{
"method" : "get",
"headers": headers
};
// Getting "bad request" here - check the username & password
var result = UrlFetchApp.fetch(url, options);
var state=result.getContentText();
// You should check state.getResponseCode()
Logger.log('1: '+state);
Logger.log(parse(state));
}
function parse(txt) {
var doc = Xml.parse(txt, true);
return doc; // Return results
}