엔드포인트 확인 프로젝트 설정 -> 일반에 프로젝트 ID를 확인할 수 있을것이다. 요 프로젝트 ID를 서버 엔드포인트에 넣어줄것이다. https://firebase.google.com/docs/cloud-messaging/migrate-v1?hl=ko엔드포인트는 업데이트 이후 노란색 줄이 그어진 부분에 프로젝트 ID를 넣어주면 된다.
API 호출 FCM은 API Key를 사용해서 인증을 받았지만 업데이트 후에는 Access Token을 발급받아 인증하도록 변경되었다. 따라서 Firebase에서 Access Token을 발급받아 Push알림 요청을 보낼때 Header 첨부하여 요청한다. 참고
@RequiredArgsConstructor
public class FirebaseSender {
private final RestTemplate restTemplate;
// 비공개 키 경로
private final String CONFIG_PATH = "firebase/firebase-key.json";
// 토큰 발급 URL
private final String AUTH_URL = "https://www.googleapis.com/auth/cloud-platform";
// 엔드포인트 URL
private final String SEND_URL = "https://fcm.googleapis.com/v1/projects/프로젝트ID/messages:send";
private String getAccessToken() throws IOException { // 토큰 발급
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new ClassPathResource(CONFIG_PATH).getInputStream())
.createScoped(List.of(AUTH_URL));
googleCredentials.refreshIfExpired();
return googleCredentials.getAccessToken().getTokenValue();
}
@Getter
@Builder
private static class PushPayload { // API 호출시 Body에 보낼 객체
private boolean validate_only;
private PushMessage message;
@Getter
@Builder
private static class Message {
private String token;
private PushNotification notification;
}
@Getter
@Builder
private static class Notification {
private String title;
private String body;
private String image;
}
}
private PushPayload getBody(String to, String title, String body) {
return PushPayload.builder()
.validate_only(false)
.message(PushPayload.Message.builder()
.token(to)
.notification(PushPayload.Notification.builder()
.title(title)
.body(body)
.image(null)
.build())
.build())
.build();
}
public void pushBrowserSend(String to, String title, String body) { // 발송 API 호출
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + getAccessToken());
final HttpEntity<Object> entity = new HttpEntity<>(getBody(to, title, body), headers);
final ResponseEntity<String> response = restTemplate.exchange(SEND_URL, HttpMethod.POST, entity, String.class);
final HttpStatus status = response.getStatusCode();
final String responseBody = response.getBody();
if (status.equals(HttpStatus.OK)) {
// 발송 API 호출 성공
} else {
// 발송 API 호출 실패
}
}
}
여기서 pushBrowserSend함수의 to 매개변수는 앱 토큰이다. 아래에서 앱 토큰은 어떻게 발급받는지 알아보자.
앱 토큰 발급받기 프로젝트 개요 -> 앱 추가 -> 웹 해당 firebaseConfig 정보를 복사해서 resources/static/firebase-message-sw.js에 설정해준다. Firebase에서 http://localhost:8080/firebase-message-sw 경로로 조회를 하기 때문에 resources/static 폴더 안에 넣어주어야 한다.