EPguy
[FCM] FCM V1 으로 마이그레이션 본문
기존 FCM API deprecated 되어서 v1으로 마이그레이션 함.
// 데이터 + 메세지
public int sendMessage(String token, String title, String body, HashMap<String, String> data) throws IOException {
String message = makeMessage(token, title, body, data);
return sendMessageToFCM(message);
}
private String makeMessage(String token, String title, String body, HashMap<String, String> data) throws JsonProcessingException {
ObjectMapper om = new ObjectMapper();
FcmMessageDto fcmMessageDto = FcmMessageDto.builder()
.message(FcmRequestDto.builder()
.token(token)
.data(data)
.notification(FcmRequestDto.Notification.builder()
.title(title)
.body(body)
.build())
.build())
.build();
return om.writeValueAsString(fcmMessageDto);
}
private int sendMessageToFCM(String message) throws IOException {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
String accessToken = getAccessToken();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer " + accessToken);
System.out.print("Access Token: " + accessToken);
HttpEntity<String> entity = new HttpEntity<>(message, headers);
String API_URL = "https://fcm.googleapis.com/v1/projects/project/messages:send";
ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, entity, String.class);
// 푸시 알림 결과 출력
System.out.println("Response Status Code: " + response.getStatusCode());
System.out.println("Response Body: " + response.getBody());
return response.getStatusCode() == HttpStatus.OK ? 1 : 0;
}
private String getAccessToken() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new ClassPathResource(firebaseKeyPath).getInputStream())
.createScoped(List.of("https://www.googleapis.com/auth/cloud-platform"));
googleCredentials.refreshIfExpired();
return googleCredentials.getAccessToken().getTokenValue();
}
'개발 > Java' 카테고리의 다른 글
[Spring] Spring Security + JWT + 카카오 로그인 구현 (1) | 2023.10.05 |
---|---|
[MyBatis] Invalid bound statement (not found) (0) | 2023.09.27 |
JsonMappingException: No suitable constructor found for type 에러 해결법 (0) | 2023.09.26 |