"401 Error Code" using google script app fetch post - javascript

Hi everyone recently i have been trying to do a fetch post in app script, from an api called salesbinder(inventory system), i have managed to fetch and pulls all inventory data down, however i have been struggling to post and add document to it and received an error code ->
"Truncated server response: {"message":"Unauthorized","url":"\/api\/2.0\/documents.json","code":401}"
since I am using the same username and password I can assure that the details are correct for the authentication, would appreciate a lot if anyone could help me to solve the problem.
Here are the api documentaion (https://www.salesbinder.com/api/documents/add/) and the code i have been using.
function posting(){
var Username = "{API KEY}"
var Password = "x"
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(Username+ ':' + Password)
};
var url ='{API URL}'
var data ={
"document":{
"customer_id": 'a93a9e9a-5837-4ec5-9dc7-47cc8cfd84e4',
"issue_date":"2022-05-09",
"context_id":5,
"document_items":[
{
"quantity":2,
"price":134,
"item_id":" b04993fe-7b17-42a1-b5e5-2d34890794c9"
}
]
},
};
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
UrlFetchApp.fetch(url, option);
}

I think that your error message of "message":"Unauthorized" is due to "headers": {headers},. This has already been mentioned in chrisg86's comment.
And also, from this document, it seems that the request body is required to be sent with Content-Type: application/json.
From:
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
To:
var option = {
"method": "post",
"payload": JSON.stringify(data),
headers, // or "headers": headers
"contentType": "application/json"
};
Note:
In this modification, it supposes that the values of "Basic " + Utilities.base64Encode(Username+ ':' + Password), data and url are correct. Please be careful this.

Related

Issue with POST request with API oauth2 / return: error 415

I have some issues with an API with oauth2 authentication.
After I get the token, and I want to sent my POST request but it still gives me a 415 error (Unsupported Media Type). I'm sure my payload's fields are good because I tried with postman and it works, but I don't know if I have to JSON stringify the header (the payload I think, but I'm not sure at 100%). I run my code on Google apps script so I thought the problem came from apps script, but I can get the token and send GET request on it.
function post_pers() {
var url = "(my url)";
var data = {
"id": 32,
"nom": "apij",
"prenom": "joseph",
"civiliteLongue": "Monsieur",
"idTypePersonne": "PERSTPHYSIQUE ",
"ligne1Adresse": " ",
"ligne2Adresse": " ",
"ligne3Adresse": " ",
"codePostal": " ",
"commune": " ",
"idPays": "FR",
"iban": " ",
"bic": " ",
"titulaireCompte": " ",
"domiciliationBanque": " ",
"assujettiTva": true,
"mediaPrefere": "Mail",
}
var payload = JSON.stringify(data);
Logger.log("payload; "+payload)
Logger.log("data; "+data)
var header1 = {
"accept": "application/json",
"authorization": "Bearer (my access token)",
"content-type": "application/json"
}
var header = JSON.stringify(header1);
Logger.log("header; "+header)
Logger.log("header1; "+header1)
var options = {
"method": "POST",
"header": header,
"payload": payload
}
var response = UrlFetchApp.fetch(url, options);
Logger.log(response)
}
415 is unsupported media. This is usually due to Content-Type header typos. Your script is stringifying headers, which would make header unreadable by the server. Try
var options = {
"method": "POST",
"header": /*header*/header1,
"payload": payload
}

Create/Update Subtask for a Jira Story

I am new to Jira API & I am currently creating a google form to create a subtask automatically for any ad-hoc requests attaching to an existing story that is already created manually.
URL: https://<subdomain>.atlassian.net/jira/software/c/projects/<PROJECTID>
STORY CREATED: PROJECTID-XXX
I have the following sample code to test:
function createSubTask(summary, description) {
var URL = 'https://<subdomain>.atlassian.net/rest/api/3/issue';
var username = '<user-name>';
var password = '<api-key>';
var userCreds = "Basic " + Utilities.base64Encode(username + ':' + password);
var data = {
"project": {"key": "PROJECTID"},
"parent": {"key": "PROJECTID-XXX"},
"summary": summary,
"description": description,
"issuetype": {"name":"Sub-task"}
};
var payload = JSON.stringify(data);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": userCreds,
"muteHttpExceptions": "True"
};
var options = {
"method": "POST",
"headers": headers,
"payload": payload
}
var response = UrlFetchApp.fetch(URL, options);
Logger.log(response);
}
I am getting the following error:
Exception: Request failed for https://<subdomain>.atlassian.net returned code 400. Truncated server response: {"errorMessages":[],"errors":{"project":"Specify a valid project ID or key"}} (use muteHttpExceptions option to examine full response)
Not sure, what I am doing wrong.
"muteHttpExceptions": true
muteHttpExceptions be in the options block and true should be a bool not a string.
I was getting the Specify a valid project ID or key error, then swapped this in the options block and got a response error that was actually the problem.
Use the following payload format. It will fix the problem.
{
"fields": {
"project":
{
"key": "TEST"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
}

Subscription failed using Stripe API in Google Apps Script

I'm trying to make an add-on using Google Apps Script & Stripe where user can subscribe for an item as an yearly subscription. Every time I purchase the subscription from Stripe checkout, I get error like this,
{
"error": {
"code": "parameter_unknown",
"doc_url": "https://stripe.com/docs/error-codes/parameter-unknown",
"message": "Received unknown parameter: #45b5a607",
"param": "#45b5a607",
"type": "invalid_request_error"
}
}
When I check the log in Stripe Dashboard I get the POST body like this,
{
"items": "[Ljava.lang.Object",
"#45b5a607": null,
"customer": "cus_Dix0eSYM5qP0kx"
}
This is my code in Google Apps Script,
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
var customer = {
'email': customerEmail,
'source': token
};
var optCreate = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : customer,
'muteHttpExceptions' : true
};
var createCustomer = UrlFetchApp.fetch(urlCreate, optCreate);
var respCreate = JSON.parse(createCustomer.getContentText());
var customerId = respCreate.id;
if (customerId == null) { return "Error"; }
var data = {
"customer" : customerId,
"items" : [
{
"plan" : "plan_Diuw7CdAGcSrhm"
}
]
};
var options = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : data,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
var resp = JSON.parse(response.getContentText());
Logger.log(resp);
I think I must be doing something wrong in my data JSON object. The items field is not working correctly that's why POST body is weird. What is the correct way here?
You need to stringify the payload.
var options = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : JSON.stringify(data),
'muteHttpExceptions' : true
};
It looks like you're POSTing JSON data, but Stripe's API does not accept JSON — you need to use form encoding. i.e your code needs to set data to be in this format:
items[0][plan]=plan_CvVNfwZ4pYubYg&customer=cus_Diygqj4wAq6L9T
You can refer to cURL examples in Stripe's API docs for this. Generally you should use an official library to simplify making API requests, but that may not be possible with Apps Script.

HTTPS request not posting body of REST request

I'm trying to POST to an API endpoint on my server. I know my endpoint works because if I use Advanced REST Client, I can hit it and get a JSON response as expected. The problem seems to be that no data is being sent in the body of my request despite calling request.write(postData) which contains a key, value pair. Without this data being sent in the body, my server returns a 401 error as expected without this information. Printing out the content of the POST server-side is empty but I'm clueless as to why it's empty.
var postData = querystring.stringify({
"access_token" : accessToken,
"id": applianceId
});
var serverError = function (e) {
log("Error", e.message);
context.fail(generateControlError(requestName, "DEPENDENT_SERVICE_UNAVAILABLE", "Unable to connect to server"));
};
var callback = function(response) {
var str = "";
response.on("data", function(chunk) {
str += chunk.toString("utf-8");
});
response.on("end", function() {
result = generateResult(CONTROL, requestName.replace("Request", "Confirmation"), messageId);
context.succeed(result);
});
response.on("error", serverError);
};
var options = {
hostname: REMOTE_CLOUD_HOSTNAME,
port: 443,
path: REMOTE_CLOUD_BASE_PATH + "/" + endpoint,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
var request = https.request(options, callback);
request.on("error", serverError);
//This doesn't seem to write anything since if I print out the POST
//data server-side it's empty; however, if I print out the value of
//postData here, it looks as expected: 'access_token=xxxxx'
request.write(postData);
request.end();
I have testing you code again httpbin.org/post and it seems that it is working.
I believe that the issue related to, that your should POST application/json and not "application/x-www-form-urlencoded
Please try to change the header
headers: {
"Content-Type": "application/json"
}
Then, try to change the postData to JSON string:
var postData=JSON.stringify({access_token:"xxxxx"})
To be sure that problem you success to send and the problem is not local (maybe there is an issue in your server), change the target to mirror URL:
var options = {
hostname: "httpbin.org",
path:'/post',
port: 443,
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
If there is no problem in your NodeJS version, the is the response you should get: (It is mean that the server got the posted data)
{
"args": {},
"data": "{\"access_token\":\"xxxxx\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "24",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": {
"access_token": "xxxxx"
},
"origin": "5.29.63.30",
"url": "https://httpbin.org/post"
}
BTW: I really recommend you to move to a library to manage the request for you:
https://github.com/request/request - Very popular
https://github.com/request/request-promise - For popular who like to use the Promise syntax (The next thing in JavaScript)
https://github.com/visionmedia/superagent - For people who like to write same code in Browser & Server

"JSON_PARSING_ERROR: Unexpected character (d) at position 0." when sending GCM request from GAS

This seems very similar to a number of other questions and it seems obvious that the error indicates there's something wrong with my JSON payload. But I'm at a loss as to why.
I'm running a Google Apps Script to test sending a message to Google Firebase Cloud Messaging.
My code:
function SendGCMessage() {
var url = "https://gcm-http.googleapis.com/gcm/send";
var apiKey = "AbCdEfG";
var to = "ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"
var payload = {
"data": {
"message" : "This is the message"
},
"to":to
};
var sendCount = 1;
var headers = {
"Content-Type": "application/json",
"Authorization": "key=" + apiKey
};
var params = {
headers: headers,
method: "post",
payload: payload
};
var response = UrlFetchApp.fetch(url, params);
return {message: "send completed: " + response.getContentText()};
}
When I run this in debug mode, the object payload looks fine - like a normal Javascript object. params as well. UrlFetchApp takes a Javascript object, not a String in JSON notation. However I did try "JSON.stringify(params)" and I got an error. What did I do wrong?
Note: params looks like this when I pause it in the debugger:
{"headers":{"Content-Type":"application/json","Authorization":"key=AbCdEfG"},"method":"post","payload":{"data":{"message":"This
is the message"},"to":"ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"}}
I discovered the problem, thanks to https://stackoverflow.com/a/10894233/3576831
the 'payload' parameter must be a string as specified here:
https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.
Adjusting this section of the script works:
var params = {
headers: headers,
method: "post",
payload: JSON.stringify(payload)
};

Categories