0

I want to send push notification to certain user of my app by using Firebase FCM Messaging cloud in Kotlin.

First I set FirebaseMessagingService as below.

class MyFirebaseMessagingService: FirebaseMessagingService() {

    companion object {
        val CHANNEL_ID : String = "onldocc"
        val CHANNEL_NAME : String = "CommentPush"

    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        // token을 서버로 전송

    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        // 수신한 메세지를 처리

        val notificationManager = NotificationManagerCompat.from(applicationContext)
        var builder : NotificationCompat.Builder

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            if(notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
                val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(channel)
            }
            builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
        } else {
            builder = NotificationCompat.Builder(applicationContext)
        }

        val title = message.notification?.title
        val body = message.notification?.body

        builder.setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_illustimage)

        val notification = builder.build()
        notificationManager.notify(1, notification)
    }
}

And whenever user write comment I want to send notification.

So I get ready with this function for this.

I use okHttps3 for this work.

fun sendPushNotification(token: String?, title: String, body: String) {
    val url = "https://fcm.googleapis.com/fcm/send"

    val bodyJson = JSONObject()
    bodyJson.put("to", token)
    bodyJson.put("notification",
        JSONObject().also {
            it.put("title", title)
//            it.put("subtitle", subtitle)
            it.put("body", body)
            it.put("sound", "social_notification_sound.wav")
        }
    )
//    bodyJson.put("data", JSONObject(data))

    val request = okhttp3.Request.Builder()
        .url(url)
        .addHeader("Content-Type", "application/json")
        .addHeader("Authorization", "key=$key")
        .post(
            bodyJson.toString().toRequestBody("application/json; charset=utf-8".toMediaType())
        )
        .build()

    val client = OkHttpClient()

    client.newCall(request).enqueue(
        object : okhttp3.Callback {
            override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                Log.d("푸시", "성공: ${response.body?.string()}")

            }

            override fun onFailure(call: okhttp3.Call, e: IOException) {
                Log.d("푸시", "실패: ${e.message.toString()}")
            }
        }
    )
}

Last, when user write comment I call above function with message's content after getting message.

 FirebaseMessaging.getInstance().token.addOnSuccessListener (object : OnSuccessListener<String> {
                    override fun onSuccess(myToken: String?) {
                        sendPushNotification(myToken, "오늘도청춘", description.toString())
                    }
                })

I check that client.newCall(request).enqueue is get onResponse, not onFailure.

But when I print response.body, result looks like below:

   <HEAD>
    <TITLE>INVALID_KEY</TITLE>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
    <H1>INVALID_KEY</H1>
    <H2>Error 401</H2>
    </BODY>
    </HTML>

I think something goes wrong, and of course, notification push doesn't appear.

I check token is correctly printed.

What is the problem here?

I'm new to it, please help me.

And I also want send push notification to certain user, not all, How can I make it?

Hyejung
  • 902
  • 1
  • 8
  • 22
  • Where is the auth key coming from here? `.addHeader("Authorization", "key=$key")` - and is that even correct? Are you sure you're not just sending `Authorization: key=$key` to Firebase? – cardouken Apr 08 '23 at 13:38
  • *firebaser here* Calls to the FCM REST API require that you specify the FCM *server** key in your code. As its name implies, this key should only be used in server-side code, or in an otherwise trusted environment. The reason for this is that anyone who has the FCM server key can send whatever message they want to all of your users. By including this key in your Android app, a malicious user can find it and you're putting your users at risk. See https://stackoverflow.com/a/37993724 for a better solution. – Frank van Puffelen Apr 08 '23 at 13:49

0 Answers0