반응형

푸시메세지 전송 테스트를 하는데 

클라우드 메시징에서 Google Cloud 콘솔에서 API 관리 눌러서 하라는 글이 많은데 아무리 찾아도 없어서 다른 방법을 찾았다

 

https://console.firebase.google.com/u/0/

Firebase의 설정 아이콘 클릭 > 프로젝트 설정 > 서비스 계정 > Firebase Admin SDK > Admin SDK 구성 스니펫을 자바

'새 비공개 키 생성을 클릭'

 

다운로드 받은 파일을

resources로 옮기면 됨 (파일명은 변경해도 됨)

 

아래 디펜던시 추가

dependencies {
	implementation 'com.google.auth:google-auth-library-oauth2-http:1.18.0'
}

 

FCM_API_URL에 PROJECT_ID는 파이어베이스에 등록한 프로젝트 id를 입력하면 된다

import com.google.auth.oauth2.GoogleCredentials;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class FCMService {

    private static final String FCM_API_URL = "https://fcm.googleapis.com/v1/projects/PROJECT_ID/messages:send";

    private static String getAccessToken() throws IOException {
        FileInputStream serviceAccount = new FileInputStream("src/main/resources/project-firebase-key.json");
        GoogleCredentials googleCredentials = GoogleCredentials
                .fromStream(serviceAccount)
                .createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
        googleCredentials.refreshIfExpired();
        return "Bearer " + googleCredentials.getAccessToken().getTokenValue();
    }

    public static void sendPushNotification(String fcmToken, String title, String message) {
        try {
            RestTemplate restTemplate = new RestTemplate();

            Map<String, Object> messageBody = new HashMap<>();
            messageBody.put("token", fcmToken);
            messageBody.put("notification", Map.of("title", title, "body", message));

            Map<String, Object> body = new HashMap<>();
            body.put("message", messageBody);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", getAccessToken());

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);
            ResponseEntity<String> response = restTemplate.exchange(FCM_API_URL, HttpMethod.POST, request, String.class);

            System.out.println("FCM Response: " + response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

반응형