INVALID_ARGUMENT: Request contains an invalid argument

27 Views Asked by At

I am attempting to send push notifications to a ios devices from node just through firebase.

Here is what I did.

  1. Generate the APNSToken in the app using await messaging().getAPNSToken();
  2. Send the token to the backend to save it. Before storing the token...
  3. Convert it to an FCM token using the following function
  4. Then use the new FCM token to send the notification as seen below
  5. 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

enter image description here

0

There are 0 best solutions below