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)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With