3

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"}}

Scott
  • 3,663
  • 8
  • 33
  • 56

1 Answers1

7

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)
};
Community
  • 1
  • 1
Scott
  • 3,663
  • 8
  • 33
  • 56
  • This worked for me!! In my case I'm using Firebase Cloud messaging. I added the JSON.stringify yo my payload and started to work. – Juan Pablo Nov 03 '16 at 18:48