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
Related
I keep getting a 500 response code in an API call to the Cardpointe gateway (cardconnect) any insight will help.
(I was able to verify the test credentials by just posting to the URL without the auth endpoint)
Here is my code in a Google apps script:
function myFunction() {
var messagesUrl = "https://fts-uat.cardconnect.com/cardconnect/rest/auth";
var cred = "testing:testing123";
var payload = JSON.stringify({
"merchid" : "496160873888",
"account": "4788250000121443",
"expiry": "1218",
"cvv2": "123",
"amount": "100",
"phone": "15558889999",
"capture": "y"
});
var options = {
"method" : "put",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode(cred)
},{
"Content-Type" : "application/json"
}
var res = UrlFetchApp.fetch(messagesUrl, options);
Logger.log(res);
}
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode(cred)
},{
"Content-Type" : "application/json"
}
Here content type is not set to options.headers.
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const options ={};
options.headers = {
"Authorization" : "Basic " + "b64"
},{
"Content-Type" : "application/json"
}
console.log(options)
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
headers should be a single object with multiple keys:
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode(cred),
"Content-Type" : "application/json"
}
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const options={}
options.headers = {
"Authorization" : "Basic " + "b64",
"Content-Type" : "application/json"
}
console.log(options)
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
let a;
a = 1,3;
console.log(a);// no 3
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
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"
};
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.
var trackingnumber = SpreadsheetApp.getActiveSheet().getRange('G2').getValue();
var header = {
"aftership-api-key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Content-Type" : "application/json"
};
var payload = {
"lang": "en"
};
var slug = "china-post";
var tracking_number = trackingnumber;
var options = {
"method": "get",
"headers": header,
"payload": (payload)
};
var trackLastcheckpoint = UrlFetchApp.fetch("https://api.aftership.com/v4/last_checkpoint/"+slug+"/"+tracking_number, options);
Everything works fine without the payload, but when I add payload I got a return code 400
"Request failed for https://api.aftership.com/v4/last_checkpoint/china-post/XXXXXXXXXXXXX returned code 400. Truncated server response: {"meta":{"code":4001,"message":"Invalid JSON data. (001)","type":"BadRequest"},"data":{}} (use muteHttpExceptions option to examine full response) (line 123, file "Code")"
Where exactly to put the lang:en?
Last Checkpoint API Doc
How about the following modifications?
In the document of getRequest(url, params), it is "Certain HTTP methods (e.g. GET) do not accept a payload." So it uses the optional parameter as the URL query parameter.
From :
var trackingnumber = SpreadsheetApp.getActiveSheet().getRange('G2').getValue();
var header = {
"aftership-api-key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Content-Type" : "application/json"
};
var payload = {
"lang": "en"
};
var slug = "china-post";
var tracking_number = trackingnumber;
var options = {
"method": "get",
"headers": header,
"payload": JSON.stringify(payload)
};
var trackLastcheckpoint = UrlFetchApp.fetch("https://api.aftership.com/v4/last_checkpoint/"+slug+"/"+tracking_number, options);
To :
var trackingnumber = SpreadsheetApp.getActiveSheet().getRange('G2').getValue();
var header = {
"aftership-api-key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Content-Type" : "application/json"
};
var slug = "china-post";
var tracking_number = trackingnumber;
var options = {
"method": "get",
"headers": header
};
var url = "https://api.aftership.com/v4/last_checkpoint/"+slug+"/"+tracking_number+"?lang=en";
var trackLastcheckpoint = UrlFetchApp.fetch(url, options);
If this didn't work, I'm sorry.
I am developing multi-language website using Angularjs and a Web api as backend. I am trying to send RequestedPlatform and RequestedLanguage in the header whenever I make an API call.
Below is my Ajax request call.
$http.post(url,RegistrationData).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function (error) {
toastr.error('', 'Error Occured');
});
updated code
var RegistrationData = {
FirstName: $scope.user.Fname,
LastName: $scope.user.Lname,
Password: $scope.user.password,
Gender: "Male",
DateOfBirth: "2017-04-04",
Nationality: $scope.user.selectedGlobe,
Mobile_CountryCod: "91",
MobileNumber: $scope.user.mobilenumber,
EmailId: $scope.user.email,
Home_Location: $scope.user.homeLocation,
Home_City: $scope.user.homeCity,
Home_Neighbourhood: $scope.user.homeNeighbourhood,
Home_HouseNumber: $scope.user.housenumber,
Home_MainStreet: $scope.user.homemainstreet,
Home_SubStreet: $scope.user.homesubstreet,
Work_Location: $scope.user.worklocation,
Work_City: $scope.user.workcity,
Work_Neighbourhood: $scope.user.workNeighbourhood,
Work_HouseNumber: $scope.user.workhousenumber,
Work_MainStreet: $scope.user.workmainstreet,
Work_SubStreet: $scope.user.worksubstreet
};
var req = {
method: 'POST',
url: url,
data: { RegistrationData: RegistrationData },
headers: {
RequestedPlatform: "Web",
RequestedLanguage: "English"
}
}
$http(req).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function () {
toastr.error('', 'Error Occured');
});
May I get some help to set headers in Ajax. Any help would be appreciated.
you can send headers with headers property of $http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
and if you want headers for all the requests that can be fully configured by accessing the $httpProvider.defaults.headers configuration object,
Reference
There are few ways and I have posted one which I have been using it for a while. I hope you are looking for the below
$http.post('test', data, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
})