Spring Boot에서 Fcm 푸쉬 보내기 - link-hpcnt-zz/Fcm-Server GitHub Wiki
Spring Boot에서 Fcm 푸쉬 보내기
Fcm
Server 와 Client app 간에 푸쉬 메시지를 보낼 수 있는 서비스로 Firebase Cloud Messaging의 줄임말이다.
Gcm의 확장판으로 android, ios, mobile web 등 다양한 플랫폼을 커버할 수 있다.
Firebase Console에서 프로젝트 등록
https://console.firebase.google.com/?hl=ko 프로젝트 추가를 통해 등록
Push를 위한 준비
Fcm 서버를 통해 푸쉬를 보내기 위해선 다음과 같은 값들을 필요로 한다.
Checklist
- Server key(Api key)
- Sender id
- Registration token
- Api Url
그중 server key와 sender id는 프로젝트 설정
으로 들어가 클라우드 메시징
탭을 확인하면 볼 수 있다.
Registration token
On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token.
HTTP v1 API로 이전하면서 새로워진것
Fcm이 기존 http api에서 http vi api로 넘어오면서 바뀐 부분이 있다.
- 엔드 포인트 URL 업데이트 (경로에 v1 추가)
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
- 전송시 Authorization 형식 변화
Authorization: Bearer <valid Oauth 2.0 token>
원래는 key로 매칭되던게 Bearer로 바뀌고 유효한 토큰값을 넣어주면 된다.
- Payload 형식 개선
중복 코드를 제거하여 플랫폼별 타켓팅이 더 쉽게 가능하게 개선되었다.
"message": {
"topic": "news",
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"data": {
"story_id": "story_12345"
}
"android": {
"notification": {
"click_action": "TOP_STORY_ACTIVITY"
}
},
"aps": {
"category": "NEW_MESSAGE_CATEGORY"
}
}
}
같은 메세지 내용을 담고 있어도 android와 ios 따로 json을 만들어주던것을 없애고 한번에 타켓팅이 되게끔 만들어졌다. 그리고 topic이 to를 대체하게 되었다.
Json 형태의 Push Message 만들기
push에 담을 내용과 함께 token값과 기기별 설정값을 customize해서 주입해준다.
data class FcmEvent(
val name: String,
val data: Any?,
val notification: Notification?,
val android: AndroidConfig?,
val apns: ApnsConfig?,
val token: String
)
data class Notification(
val title: String? = null,
val body: String? = null
)
푸쉬를 보내기 위한 WebClient
Spring 5에는 RestTemplate보다 reactive하게 http request를 가능하게 해주는 WebClient가 있다.
필요한 dependency와 설명은 http://www.baeldung.com/spring-5-webclient를 참고.
mono와 flux는 둘 다 퍼블리셔로 차이점은 한건의 데이터를 처리할지 여러건을 처리 할지에 따라 다르게 쓰인다.
mono가 데이터 한건을 처리해서 만약 잘 처리가 되었다면 원하는 데이터를 Subscriber에게 전달할 것이고, 문제가 생기면 에러를 보내준다.
WebClient를 통해 Fcm Server에게 요청을 보내면 서버에서 토큰 유효성 검사를 한 후 succeed/fail 응답을 보내준다.
val webClient : WebClient = WebClient.create()
val response: Mono<String.Companion> = webClient.post()
.uri(FCM_API_URL)
.body(BodyInserters.fromObject(makeJsonObject(fcmRequest)))
.header("Authorization", "Bearer $FCM_SERVER_KEY","Content-Type" ,MediaType.APPLICATION_JSON_VALUE)
.retrieve()
.bodyToMono(String.javaClass)
response.subscribe(){
it -> log.debug("FCM PUSH RESPONSE IS : ", it)
}
부족한 내용
- refresh token
- 전체적인 흐름에 대한것
- test
- push 실제로 해본것에 대한(클라우드 콘솔로 테스트 해볼까) 과정 설명