I am trying to send a WhatsApp message using twilio's HTTP endpoint but it is failing with error
{"code": 21602, "message": "Message body is required.", "more_info": "https://www.twilio.com/docs/errors/21602", "status": 400}
I did not purposefully add 'content-type': 'application/x-www-form-urlencoded' as the URLFetchApp adds the same automatically.
function sampletTextMessage(){
var ACCOUNT_SID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var ACCOUNT_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var options = {
"method" : "post",
'headers' : {
"Authorization" : "Basic " + Utilities.base64Encode(ACCOUNT_SID + ":" + ACCOUNT_TOKEN),
},
'payload' :{
'body' : 'Your Twilio code is 1238432',
'to' : 'whatsapp:+91XXXXXXXXX3',
'from': 'whatsapp:+1XXXXXXXXX6',
},
'muteHttpExceptions' : true
};
var url="https://api.twilio.com/2010-04-01/Accounts/" + ACCOUNT_SID + "/Messages.json";
var response = UrlFetchApp.fetch(url,options);
Logger.log(response);
}
It looks like your case is wrong, capitalize To, From, and Body.
Reference:
How to Send SMS from a Google Spreadsheet
var payload = {
"To": to,
"Body" : body,
"From" : "YOURTWILIONUMBER"
};
Related
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.
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
}
I'm receiving the error: Passed parameter type mismatch: 'fields' when I try to do a POST request using Google Apps Script.
I've tried adding JSON.stringify(requestBody) on the payload and that didn't work either. Where am I going wrong here?
var fields = ["id","name","group_name"]
var requestBody = {
"project_id": "3259344",
"fields": fields,
"limit": "30"
}
var options =
{
'method' : 'POST',
'headers' : {
'User-Id' : email,
'Authorization' : 'Bearer '+ apiKey
},
'payload' : requestBody
};
var response = UrlFetchApp.fetch("https://api.test.com/v2/json/get/keywords", options);
I'm not sure about the detail specification of the API you want to use. So from the error message in your question, how about the following 3 modification patterns?
Pattern 1:
Modified script:
var fields = ["id","name","group_name"];
var requestBody = {
"project_id": "3259344",
"fields": fields,
"limit": "30"
};
var options = {
'method' : 'POST',
'headers' : {
'User-Id' : email,
'Authorization' : 'Bearer ' + apiKey
},
'payload' : JSON.stringify(requestBody), // Modified
'contentType': 'application/json' // Added
};
var response = UrlFetchApp.fetch("https://api.test.com/v2/json/get/keywords", options);
Pattern 2:
Modified script:
var fields = "id,name,group_name"; // Modified
var requestBody = {
"project_id": "3259344",
"fields": fields,
"limit": "30"
};
var options = {
'method' : 'POST',
'headers' : {
'User-Id' : email,
'Authorization' : 'Bearer ' + apiKey
},
'payload' : JSON.stringify(requestBody), // Modified
'contentType': 'application/json' // Added
};
var response = UrlFetchApp.fetch("https://api.test.com/v2/json/get/keywords", options);
Pattern 3:
Modified script:
var fields = "id,name,group_name"; // Modified
var requestBody = {
"project_id": "3259344",
"fields": fields,
"limit": "30"
};
var options = {
'method' : 'POST',
'headers' : {
'User-Id' : email,
'Authorization' : 'Bearer ' + apiKey
},
'payload' : requestBody
};
var response = UrlFetchApp.fetch("https://api.test.com/v2/json/get/keywords", options);
Reference:
Class UrlFetchApp
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.
tl;dr I am new to JavaScript and Google Apps Script and I have no idea how to add the 'fields' property to a Google Drive v3 API call.
I am trying to modify file permissions in a G Suite domain using Google Apps Script, a service account, and the OAuth 2 sample from Google. I wrote a function for Drive API v3 to replace Drive API v2 getIdForEmail, but API v3 requires the 'fields' query parameter to request specific fields.
The error given when I run the script is:
Request failed for https://www.googleapis.com/drive/v3/about returned code 400. Truncated server response: { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "The 'fields' parameter is required for this meth...
I found the answer in a different programming language but can't translate it to Google Apps Script / JavaScript. See Fields on the previous answer: Google Drive API v3 Migration. How do I add the 'fields' property to request 'permissionId'?
function getPermissionIdForEmail(userEmail) {
var service = getService(userEmail);
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/drive/v3/about';
var options = {
'method': 'get',
'contentType': 'application/json'
};
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log('getPermissionIdForEmail result: %s', JSON.stringify(result, null, 2));
} else {
Logger.log('getPermissionIdForEmail getLastError: %s', service.getLastError());
}
}
Edit: Thank you Cameron Roberts for the help. The solution I used is
var url = 'https://www.googleapis.com/drive/v3/about' + '?fields=user/permissionId';
I can't recall offhand if Google will accept a POST request here, if they will this could be passed as a request payload:
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
payload: {
fields: 'kind,user,storageQuota'
}
});
Or if it must be a GET request you can append the parameters directly to the url:
url = url+'?fields=kind,user,storageQuota'
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});