Error while calling freshchat APIs from google apps script - google-apps-script

I am trying to call FreshChat API from google apps script. GET request of outbound-messages is working fine but POST request is failing with error
Exception: Request failed for http://api.in.freshchat.com returned code 400. Truncated server response: {"success":false,"errorCode":0,"errorMessage":"HTTP 405 Method Not Allowed","errorData":null,"errorName":null} (use muteHttpExceptions option to examine full response)
Below are the details of request
function myFunctiontest() {
var url = "http://api.in.freshchat.com/v2/outbound-messages/whatsapp";
var headersPOST = {
'Authorization': 'Bearer XXXXXX',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headersPOST,
'payload': JSON.stringify(bodyPayload),
'muteHttpExceptions':true
};
var response = UrlFetchApp.fetch(url, options);
console.log(response.getAllHeaders());
Logger.log(JSON.parse(response.getContentText()));
}
Same headers are working for GET request. Also same post request is working from POSTMAN.

Freshchat support helped for solving the issue.
There are two major changes
use https instead of http
Added contentType inside headers.
function myFunctiontest() {
var url = "https://api.in.freshchat.com/v2/outbound-messages/whatsapp";
var headersPOST = 'Bearer XXXXXX';
var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+ XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
method: 'POST',
//content-type: 'application/json',
headers: { Authorization: headersPOST, 'content-type': 'application/json'},
payload: JSON.stringify(bodyPayload),
muteHttpExceptions:true
};
var response = UrlFetchApp.fetch(url, options);
var text = response.getResponseCode();
}

Related

UrlFetchApp fetch method fails with 404 error, but same URL works with Curl and browsers

If I execute below code, it works fine:
curl 'http://performance.morningstar.com/perform/Performance/stock/trailing-total-returns.action?&t=DAL&region=usa&culture=en_US&comparisonRemove=true&cur=&ops=clear&ep=true&align=d&annlz=true'
I can also execute this URL from any browser and it returns expected results
http://performance.morningstar.com/perform/Performance/stock/trailing-total-returns.action?&t=DAL&region=usa&culture=en_US&comparisonRemove=true&cur=&ops=clear&ep=true&align=d&annlz=true
However, below code fails with error 404.
function fetchFromURLTemp() {
let url = "http://performance.morningstar.com/perform/Performance/stock/trailing-total-returns.action?&t=DAL&region=usa&culture=en_US&comparisonRemove=true&cur=&ops=clear&ep=true&align=d&annlz=true";
var options = {
'method': 'GET',
'headers': { 'Accept': '*/*' },
'muteHttpExceptions': true,
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*; q = 0.8'
};
let httpResponse = UrlFetchApp.fetch(url, options);
let status = httpResponse.getResponseCode()
let urlData = httpResponse.getContentText();
console.info("Response Status : " + status + ", Response Content : " + urlData)
}
It prints following message on the console
Response Status : 404, Response Content : The report is no longer supported
Can someone please advise what changes I need to get the response.
Thanks!
It works fine for me, just change let to var
function fetchFromURLTemp() {
var url = "http://performance.morningstar.com/perform/Performance/stock/trailing-total-returns.action?&t=DAL&region=usa&culture=en_US&comparisonRemove=true&cur=&ops=clear&ep=true&align=d&annlz=true";
var options = {
'method': 'GET',
'headers': { 'Accept': '*/*' },
'muteHttpExceptions': true,
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*; q = 0.8'
};
var httpResponse = UrlFetchApp.fetch(url, options);
var status = httpResponse.getResponseCode()
var urlData = httpResponse.getContentText();
Logger.log("Response Status : " + status + ", Response Content : " + urlData)
}

put works in postman but not google scripts

I am trying to push sheets data from a quiz to an api. The put works fine in postman but I can't seem to get it to work in google scripts.
Postman
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Basic bmljazpuaWNr");
myHeaders.append("Cookie", "FB_ResponseHeaders=%7b%22X-XSS-Protection%22%3a%7b%22Key%22%3a%221%3b+mode%3dblock%22%2c%22Value%22%3a%225C-58-58-82-DB-E9-4D-AD-BF-23-F8-5A-65-1E-EE-7B-96-94-7C-E6%22%7d%2c%22X-Content-Type-Options%22%3a%7b%22Key%22%3a%22nosniff%22%2c%22Value%22%3a%22E9-85-E8-2B-38-74-3B-AA-71-5A-41-1D-65-49-06-A7-FF-B3-D2-57%22%7d%2c%22Strict-Transport-Security%22%3a%7b%22Key%22%3a%22max-age%3d31536000%3b+includeSubDomains%22%2c%22Value%22%3a%221D-31-04-88-80-8A-6A-27-8E-2D-72-C5-32-98-74-A9-F8-E8-0C-E7%22%7d%7d; fbd_cooked=!/muNNuj9SlbMhC0PporV/qqu1cgGGvczJaMywTIzq+9GDRYedxCjdCU9X3WnSt1ijLXqndrZJ1DCTVw=");
var raw = JSON.stringify({
"fieldName": "SingleLineText5",
"fieldValue": "question1test"
});
var requestOptions = {
method: 'PUT',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
Google Scripts
// put em in a payload
var payload = {
"fieldName": "SingleLineText7",
"fieldValue": "question1googleSheet" }
var encodedAuth = Utilities.base64Encode("nick:nick");
var headers = [{"Authorization" : "Basic " + encodedAuth},{"Content-Type":"application/json"}];
var options = {
'method': 'PUT',
'body': JSON.stringify(payload),
'headers': headers,
'redirect': 'follow'
}
response = UrlFetchApp.fetch(url, options);
//log the response
Logger.log(JSON.stringify(response));
Am receiving
Exception: Attribute provided with invalid value: headers
If i remove the "Content-Type" I get no error but send no data just returns {}
According to the documentation you are using the wrong parameter. It should be:
const options = {
method : "PUT", // this was correct
payload: JSON.stringify(payload), // correct this
followRedirects : true, // correct this
headers: headers
}

LinkedIn API OAUTH returning "grant_type" error

I am pretty new to coding, but trying to write a simple script using LinkedIn's API that will pull an organizations follower count into google app script. Before I can even query the API, I have to authenticate using oath explained in the LinkedIn API here.
This function returns with an error response
function callLinkedAPI () {
var headers = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
"headers": headers,
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}
When I try sending the headers through I get this error as a response
{"error":"invalid_request","error_description":"A required parameter \"grant_type\" is missing"}
grant_type, client_id, client_secret do not go in the header of the request. Instead, try to put them in the body of the POST request with the content type x-www-form-urlencoded as you already had in the headers of the code you posted.
For example:
fetch('https://www.linkedin.com/oauth/v2/accessToken/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: '78ciob33iuqepo',
client_secret: 'deCgAOhZaCrvweLs'
})
})
.then(response => response.json())
.then(responseData => {
console.log(JSON.stringify(responseData))
})
Using Apps Script you should send the payload like so:
Example:
function callLinkedAPI() {
var payload = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true,
"payload":payload
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}

Posting to Bitly api with Google App Script returns 403

Hey Stackoverflow fellows!
I have been trying to writing an automation for my google sheets using an api from bit.ly to shorten my tons of link. Right now, I am at the fundamental stage and trying to log what the api return to me. Could you guys help an see what is wrong with the code? I am expecting the 200 returning back to me but it keep returning 403 forbidden to me.
var form =
{"long_url": "https://dev.bitly.com", "domain": "bit.ly", "group_guid": "MY GROUP ID" };
var option = {'header':'Authorization: Bearer{MY TOKEN}',
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(form)
};
var response = UrlFetchApp.fetch('https://api-ssl.bitly.com/v4/shorten', option);
Logger.log (response);
}
P.S. I tried to further expand the code by using adding title (succeeded) and customized link (short half // after bit.ly/ ). The second part keep return me 404. Or should I use Post/custom_bitlinks instead?
Here is my current code:
function bitlyori (i, title){
var form = {
"group_guid": "MINE",
"domain": "bit.ly",
"long_url": i,
"title" : title
};
const MY_TOKEN = "MINE";
const option = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(form),
};
var result = UrlFetchApp.fetch('https://api-ssl.bitly.com/v4/bitlinks', option);
return (JSON.parse(result.getContentText()));
}
function bitly(url,title,custom) {
var temp = bitlyori(url, title);
var form_2 = {
"custom_bitlinks": [temp] ,
};
const MY_TOKEN = "MINE";
const option_2 = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'patch',
payload: form_2};
var temp_link = 'https://api-ssl.bitly.com/v4/bitlinks/'+ JSON.stringify(temp)["id"];
var result_2 = UrlFetchApp.fetch(temp_link, option_2);
return (JSON.parse(result_2.getContentText()));
}
Headers should be a object with key "headers" inside options:
const MY_TOKEN = "dfjkgsa";
const option = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(form),
};
See:
Urlfetchapp ยง Advanced parameters

How to use Google Apps Script to create issues in Redmine?

I'm trying to create an issue in Redmine using Google Apps Script, the code is following:
function create_issue() {
var payload = {
'project_id': 'helpdesk',
'subject': 'This is a test ticket',
'description': 'This is just a genius test ticket',
'category_id': 1
};
var headers = {
'X-Redmine-API-Key': '<myapikey>',
'Content-Type': 'application/json'
};
var url = 'http://myredmine.com/issues.json';
var options = {
'method': 'POST',
'headers': headers,
'payload': payload,
//uteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
Every time I ran that script, it threw the following exception:
Execution failed: Request failed for http://myredmine.com/issues.json
returned code 422. Truncated server response: {"errors":["Subject
can't be blank"]} (use muteHttpExceptions option to examine full
response) (line 25, file "Code") [0.645 seconds total runtime]
But as you see, the "subject" parameter was passed in the payload already. What am I missing?
Thanks,
Trinh
I found the problem, I need to indicate the issue in the payload:
function create_issue() {
var issue = {
"description": "Test ticket",
"subject": "Genius ticket"
}
var payload = {
"issue": issue,
"key": "<myapikey>",
"project_id": "helpdesk",
};
payload = JSON.stringify(payload);
var headers = {
'X-Redmine-API-Key': '<myapikey>',
'Content-Type': 'application/json'
};
var url = 'http://myredmine.com/issues.json';
var options = {
'method': 'POST',
'headers': headers,
'payload': payload,
'contentType': 'application/json',
//'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
And it works!