How to verify FCM registration token on server?

后端 未结 4 1565
独厮守ぢ
独厮守ぢ 2020-11-29 09:43

I got my Firebase Cloud Messaging registration token for web push. And I sent this to my server to save in database for later push. But how can I verify this token is valid

相关标签:
4条回答
  • 2020-11-29 10:13

    When sending to an invalid registration token, you'll should receive 200 + error:InvalidRegistration:

    Check the format of the registration token you pass to the server. Make sure it matches the registration token the client app receives from registering with Firebase Notifications. Do not truncate or add additional characters.

    This is the response when you try to send a simple cURL request where the registration token is just randomly made:

    curl --header "Authorization: key=$[your_server_key_here]" \
           --header Content-Type:"application/json" \
           https://fcm.googleapis.com/fcm/send \
           -d "{\"registration_ids\":[\"ABC\"]}"
    

    Notice that I added in "ABC", in the registration_ids parameter. If ever it is a valid registration token, but is not associated to your project, you'll probably receive 200 + error:NotRegistered.

    You can try sending a test message from your server to see the response without sending an actual message towards the device by using the dry_run parameter:

    This parameter, when set to true, allows developers to test a request without actually sending a message.

    0 讨论(0)
  • 2020-11-29 10:15

    If anyone using firebase Admin SDK for node.js, there is no need to manually send the request using the server_key explicitly. Admin SDK provide sending dry_run push message to verify the fcm_token.

    function verifyFCMToken (fcmToken) => {
        return admin.messaging().send({
            token: fcmToken
        }, true)
    }
    

    Use this method like following

    verifyFCMToken("YOUR_FCM_TOKEN_HERE")
    .then(result => {
        // YOUR TOKEN IS VALID
    })
    .catch(err => {
        // YOUR TOKEN IS INVALID
    })
    
    0 讨论(0)
  • 2020-11-29 10:22

    One way is to send a message with the dry_run option = true, as is described by AL. in the other answer.

    Another way is to use the InstanceId server API:
    https://developers.google.com/instance-id/reference/server

    0 讨论(0)
  • 2020-11-29 10:24

    According to the docs, you can use validate_only for testing the request without actually delivering the message.

    https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send

    0 讨论(0)
提交回复
热议问题