When trying to send FCM notifications I found out that Google has changed their API specifications. The legacy API still works but if you want to use the latest v1 API you need to make several changes.
Using the request from my previous project, my request in Node JS was as follows:
The list of changes is listed on their site so I won't be repeating them again but I'll just mention some of the things that caused some trial and error on my project. The official guide from Google is here : Official Migration Guide to v1.
The request must have a Body with the JSON containing the message data. Most importantly it needs to have "message" field which must contain the target of the notification. Usually this is a Topic, or Device IDs. Since my previous project was using GAS, my request had a field called "payload" instead of "body".
Using the request from my previous project, my request in Node JS was as follows:
request({
url: 'https://fcm.googleapis.com/v1/projects/safe-door-278108/messages:send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'Bearer ' + token
},
payload: JSON.stringify(
{
"message": {
"topic": topic,
"notification": {
"title": "Face Verification",
"body": msg
},
"data": {
"story_id": "story_12345"
}
}
}
)}, function(error, response, body) {
if (error) {
console.error(error, response, body);
}
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body);
}
else {
console.log('Done!')
}
});
Observe the JSON was sent as payload instead of body. This was the reason I had an error which says that "the message recipient not set". I spent around a whole day before I realized that the payload should have been "body".
Oh, and I also found out that once you create a Topic, it can take around one day to be implemented in FCM, so you may want to wait one day to see if this is the cause of your calls failing. (In my case, it wasn't though).
I finally got it to work and now happily using HTTP v1 of the FCM API!
Comments
Post a Comment