I'm trying to subscribe users to firebase topic on the cloud function. So according to official docs I tried the following code
request({
method: 'POST',
url: "https://iid.googleapis.com/iid/v1:batchAdd",
json: true,
headers: {
'Content-Type':'application/json',
'Authorization':'key=server key,
},
body: JSON.stringify({
"to": "/topics/name",
"registration_tokens": ["token value"]
})
}, function (error, response, body){
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
});
But it's giving 400 status code instead of 200. Thank you.
I apparently found different documentation than you did for subscribing a device to a topic. This documentation says to use a URL formatted like this:
https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME
A variation on your code that uses this method is below. It works for me. But wouldn't it be much simpler to use admin.messaging().subscribeToTopic()?
const token = 'f_PWaiHMGvQ:APA91bGN...9F5D5avIpjY57Y098OFsxZLHUZubx0P_';
const serverKey = 'AAAAyq9marw:APA91b..._Xf-jV472nfn-sb';
request({
method: 'POST',
url: `https://iid.googleapis.com/iid/v1/${token}/rel/topics/myTopic`,
headers: {
'Content-Type':'application/json',
'Content-Length': 0,
'Authorization':`key=${serverKey}`,
}
}, function (error, response, body){
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
});
You need proper authorization to use Google API. Have you entered it? (on the headers part of your code). Maybe a clue: if you enter the URL indicated on your code in an address bar of a browser you find this:
{"error":"MissingAuthorization"}
As you pointed, error 400 is bad request, i.e., you probably are making some mistake on your requesting action. W3C states:
The request could not be understood by the server due to malformed syntax
Maybe this malformed syntax it's the absence of this authorization, raising this error 400.