简体   繁体   中英

Mapping FCM(Firebase Cloud Messaging) Token to Custom UserID

My existing app has login and registration functionality. What I'm trying to achieve is mapping FCM token ( https://firebase.google.com/docs/cloud-messaging/android/client#kotlin+ktx ) with my custom user ID on my server.

The main issue I have is that onNewToken in the service will be called even before my user registration is done, as soon as the app is installed/initialised. So, then I wouldn't be able to map it to my custom user Id.

I can generate a token whenever I want with FirebaseMessaging.getInstance().token.addOnCompleteListener , but then I would lose out if there was a change in the token. I don't want the onNewToken method to be triggered before the user has completed registration, or even in case it does, I don't want to make the API call to my backend server before registration. Any suggestions or links would be greatly beneficial. Thank you for taking the time to read my question.

TLDR

I'm trying to create a mapping between my custom user ID and FCM tokens. Once user completes registration, I will share the token to my backend server. If the token changes, I will update the mapping with this new token. Any suggestions/guidelines on how to implement this?

My recommendation is that from javascript you send the User ID to Kotlin (app), then from the app you send the token and the user I with PHP to save it in the Database, I did that and it works.

script.js

function showAndroidToast() {
   Android.showToast("18");// ID de Usuario
}
showAndroidToast();

WebAppInterface.kt

/** Instantiate the interface and set the context  */
class WebAppInterface(private val mContext: Context) {

    /** Show a toast from the web page  */
    @JavascriptInterface
    fun showToast(id_usuario: String) {

        Toast.makeText(mContext, "ID-Usuario>"+id_usuario, Toast.LENGTH_SHORT).show()

        FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                Log.w(ContentValues.TAG, "Fetching FCM registration token failed", task.exception)
                return@OnCompleteListener
            }

            // Obtenga un nuevo token de registro de Firebase Cloud Messaging (FCM)
            val token = task.result

            // MOSTRAR LOG Y TOAST
            //val msg = getString(R.string.msg_token_fmt, token)
            val msg = "TOKENdesdeJavascript>$token"
            Log.d(ContentValues.TAG, msg)
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()

            // Todo ENVIA TOKEN Y USUARIO A LA BBDD
            val urlServer ="http://example.com/AP_RegistrarToken.php"

            val stringRequest: StringRequest = object : StringRequest(Request.Method.POST, urlServer,
                Response.Listener<String> {
                    fun onResponse(response: String?) {
                        val mensaje = "Registro Satisfactorio TOKEN y USUARIO"
                        Log.d(ContentValues.TAG, mensaje)
                        Toast.makeText(mContext, mensaje, Toast.LENGTH_LONG).show()
                    }
                }, Response.ErrorListener {
                    fun onErrorResponse(error: VolleyError?) {
                        Toast.makeText(mContext, "Error en la Conexión TOKEN y  USUARIO", Toast.LENGTH_LONG).show()
                    }
                }) {
                @Throws(AuthFailureError::class)
                override fun getParams(): Map<String, String> {
                    val params = HashMap<String, String>()
                    params.put("id_usuario_kotlin",id_usuario)
                    params.put("token_kotlin", token)
                    return params
                }
            }

            Log.d(ContentValues.TAG, "SE REGISTRO EXITOSAMENTE")

            val requestQueue: RequestQueue = Volley.newRequestQueue(mContext)
            requestQueue.add(stringRequest)


        }) // FirebaseMessaging

        Toast.makeText(mContext, "SE REGISTRO EXITOSAMENTE", Toast.LENGTH_SHORT).show()

    } // FIN FUNCION

}

In this way you send the token to the database, only when the user is already registered.

I hope it helps you. I did this yesterday and it works and like you, I'm working on an app with webview to send notifications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM