I am attempting to send push notifications to a ios devices from node just through firebase.
Here is what I did.
- Generate the APNSToken in the app using
await messaging().getAPNSToken(); - Send the token to the backend to save it. Before storing the token...
- Convert it to an FCM token using the following function
- Then use the new FCM token to send the notification as seen below
- And the response I get is shown below.
export const convertAPNSToFCMToken = async token => {
const fcmMessage = {
application: 'com.xxxx.xxxx',
sandbox: false,
apns_tokens: [token]
}
const options = {
headers: {
Authorization: `Bearer ${accessToken}`,
access_token_auth: true
}
}
try {
const { data } = await axios.post('https://iid.googleapis.com/iid/v1:batchImport', fcmMessage, options)
return data.results[0].registration_token
} catch (error) {
winston.error('Unable to send message to Firebase')
winston.error(error)
}
}
This is the method that attempts to send notifications
const sendFCMMessage = async ({ accessToken = '', fcmToken = '', title = '', body = '' }) => {
try {
const fcmMessage = JSON.stringify({
message: {
data: {},
notification: {
title: title,
body: body
},
token: fcmToken
}
})
const options = {
hostname: 'fcm.googleapis.com',
path: `/v1/projects/${process.env.GOOGLE_SERVICE_ACCOUNT_PROJECT_ID}/messages:send`,
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`
}
}
const request = https.request(options, resp => {
resp.setEncoding('utf8')
resp.on('data', data => {
winston.info('Message sent to Firebase for delivery, response:')
winston.info(data)
})
})
request.on('error', err => {
winston.error('Unable to send message to Firebase')
winston.error(err)
})
request.write(fcmMessage)
request.end()
} catch (e) {
winston.error(e.message)
return Promise.reject(e)
}
}
I get the following response
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
"errorCode": "INVALID_ARGUMENT"
},
{
"@type": "type.googleapis.com/google.firebase.fcm.v1.ApnsError",
"statusCode": 400,
"reason": "BadDeviceToken"
}
]
}
}
Note:
- I generated and linked all required auth data to firebase message console as shown below
