FCM [2] Web Push 알림 발송

Maven 의존성 주입

FCM 엔진을 이용해 Web Push 알림을 발송하기에 앞서, Maven 의존성 주입을 작성해줘야한다. 필자는 9.3.0 버전을 사용했지만, 읽는 이들은 쓰고 싶은 버전 쓰면 될 것 같다. 물론 그에 따른 method 지원 양상에 대해서는... 알아서들 JAVA DOC 읽어보면서 파악하자. 사실 필자도 더 오래전 버전을 쓰다가, 알고보니 해당 버전대에서 알림을 발송하는 method 일부가 더이상 제공되지 않는 것을 뒤늦게 확인한 바가 있다. 항상 JAVA DOC 잘 읽자...

<!-- Firebase Admin SDK -->
<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>9.3.0</version>
</dependency>

 


 

FCM Web Push 발송 순서

시작하기에 앞서 FCM 엔진을 이용한 Web Push 발송 순서를 간략하게 설명하겠다.

  1. Firebase Admin SDK 초기화
  2. WebpushNotification Builder 설정(title 및 message 값 builder 내 설정)
  3. WebpushNotification Build
  4. MulticastMessage 객체 생성 및 설정(Push 알림에 대한 구체화)
  5. FCM Web Push 발송
  6. 결과 확인

어차피 상세한 내용은 예제 소스코드 내 주석으로 다 적혀있으니까, 요즘 잘 되어있는 ChatGPT 또는 구글링을 통해 더 자세한 정보를 찾아보면 좋을 것 같다. 애초에 그렇게 작성한 것이 이 글이지만.

 


 

소스코드

import com.google.api.core.ApiFuture;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.*;

public void test() throws Exception {
	try {

        // FCM Web Push 알림에 필요한 변수 선언
        String url     = "Push 알림 클릭 시, 이동할 URL";
        String title   = "Push 알림 제목";
        String message = "Push 알림 내용";
        String token   = "Push 알림 발송 대상 Token";

        // token 설정
        List<String> tokenList = new ArrayList();
        tokenList.add(token);

        // Firebase Admin SDK 설정 파일 경로
        String fcmPushKeyJsonPath = "발급 받은 json 파일의 경로";
        File dir = new File(fcmPushKeyJsonPath);

        // Firebase Admin SDK 초기화
        try (FileInputStream serviceAccount = new FileInputStream(dir)) {
            if (FirebaseApp.getApps().isEmpty()) {
                FirebaseOptions options = FirebaseOptions.builder()
                        .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                        .build();
                FirebaseApp.initializeApp(options);
            }
        }

        // WebpushNotification Builder 선언
        WebpushNotification.Builder builder = WebpushNotification.builder();

        // title 및 message 값 builder 내 설정
        builder.setTitle(title);
        builder.setBody(message);

        // WebpushNotification Build
        WebpushNotification notification = builder.build();

        // MulticastMessage 객체 생성 및 설정
        MulticastMessage oMessage = MulticastMessage.builder()
                .setWebpushConfig(WebpushConfig.builder()
                        .setNotification(notification)
                        .setFcmOptions(WebpushFcmOptions.builder()
                                .setLink(url) // 알림 클릭 시 이동할 URL 설정
                                .build())
                        .putData("url", url)
                        .build())
                .addAllTokens(partitionedTokensByLimit.get(j))
                .build();

        // 작업 처리 (MulticastMessage)
        ApiFuture<BatchResponse> future = FirebaseMessaging.getInstance().sendEachForMulticastAsync(oMessage);
        BatchResponse response = future.get();

        // 성공 및 실패 토큰 수 확인
        Integer successTokenCount = response.getSuccessCount();
        Integer failedTokenCount  = response.getFailureCount();
        System.out.println("");
        System.out.println("success Token Count : " + successTokenCount);
        System.out.println("failed  Token Count : " + failedTokenCount);
        System.out.println("");


        /** ==================================================
         *   발생한 오류에 대한 내용은 다음의 링크를 통해 확인하도록 하자.
         *   https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode?hl=ko
         ** ================================================== */
        // 실패한 메시지에 대한 처리
        SendResponse sendResponse = response.getResponses().get(0);
        FirebaseMessagingException exception = sendResponse.getException();
        if (CommonUtil.isNotEmpty(exception)) {
            System.out.println("");
            System.out.println("MessagingErrorCode : " + exception.getMessagingErrorCode());
            System.out.println("ErrorCode : " + exception.getErrorCode());
            System.out.println("Message   : " + exception.getMessage());
            System.out.println("Cause     : " + exception.getCause());
            System.out.println("");
        }
    }
    catch (Exception e) {
        /**
         *  FCM Web Push 발송 간 발생한 오류를 확인할 수 있다.
         *  필자는 해당 영역에 로그를 적재하도록 처리하였다.
         */
    }
}



 

[ FCM [0] FCM Console ]

[ FCM [1] Device Token 발급 ]

[FCM [2] Web Push 알림 발송]  ←  현재글

728x90

'Java > FCM (Back-end)' 카테고리의 다른 글

FCM 개요  (0) 2024.10.25