bad request with UrlFetchApp - google-apps-script

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
}

Related

Google scripts basic authentication

Im trying to log the json data after making an api call however Google always asks for authorisation and I need it to automatically authenticate using the api key provided .
Putting the url into the browser directly , I only need to supply the api key as the username .
The code im using is as follows :
function testapi(){
var encode = Utilities.base64Encode('apikey', Utilities.Charset.UTF_8);
Logger.log(encode);
var option = {
headers : {
Authorization: "Basic "+ encode
}
}
var url = "https://apiurl.json";
var response = UrlFetchApp.fetch(url, option).getContentText()
response = JSON.parse(response);
Logger.log(response);
}

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.

Apps Script to get the users signature

I have created an apps script that will do a simple mail merge using contact details to create a new email draft. It works as expected, but I would like to use the current user's signature in the template.
Documentation on this is dated and incomplete. I created the code below from what I have found, but have had to make a total guess as to what it needs because I can't find the official documentation.
var params;
params = {method:"post",
contentType: "application/json",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true
};
var resp = UrlFetchApp.fetch("https://apps-apis.google.com/a/feeds/emailsettings/2.0/{domain}/me/signature", params);
var rCode = resp.getResponseCode();
var rText = resp.getContentText();
This is the response:
rCode = 400
rText = Invalid request URI
What is the correct request URI? Is there a new API for this?
Gmail signatures are now accessible from the gmail API. I added a one liner below to get the signature of the current user. I used list instead of get because a user may send email as a different user by default then their logged in account. So I list all accounts and filter out the default one.
https://developers.google.com/gmail/api/v1/reference/users/settings/sendAs
var signature = Gmail.Users.Settings.SendAs.list("me").sendAs.filter(function(account){if(account.isDefault){return true}})[0].signature;

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)
};

SSL Error when making a request via UrlFetchApp

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);