개발 - 안드로이드

안드로이드 FCM 스프링 서버에서 특정 사용자에게 notification 예제 #03

개미v 2023. 9. 9. 18:57

FCM admin SDK를 사용해서 스프링에서 notification 메시지를 특정 사용자에게 보내는 방법입니다.

 

admin SDK 특정 사용자에게 notification

pom.xml
기존 파일에서 maven dependency를 추가 합니다.

		<!-- 제이슨 파싱 -->
		<dependency>
			<groupId>com.googlecode.json-simple</groupId>
			<artifactId>json-simple</artifactId>
			<version>1.1.1</version>
		</dependency>
		
		<!-- FCM 시작 -->
		<dependency>
			<groupId>com.google.api-client</groupId>
			<artifactId>google-api-client</artifactId>
			<version>1.26.0</version>
		</dependency>
		
		<dependency>
			<groupId>com.google.oauth-client</groupId>
			<artifactId>google-oauth-client</artifactId>
			<version>1.26.0</version>
		</dependency>
		
		<dependency>
			<groupId>com.google.http-client</groupId>
			<artifactId>google-http-client</artifactId>
			<version>1.26.0</version>
		</dependency>
		
		<dependency>
			<groupId>com.google.http-client</groupId>
			<artifactId>google-http-client-jackson2</artifactId>
			<version>1.26.0</version>
		</dependency>  
		
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>27.0.1-jre</version>
		</dependency>
		<!-- FCM 끝 -->

 

소스
손쉽게 테스트 할 수 있는 임의의 Controller에 작성 하였습니다.


비공개키 파일, 사용자 토큰,  프로젝트ID 본인의 것으로 기재 해야 합니다.
- 비공개키 파일 : Firebase console → 프로젝트 설정 → 서비스 계정 → Firebase Admin SDK 메뉴
- 사용자 토큰 : 앱 실행시 디버깅해서 확인
- 프로젝트ID : Firebase console → 프로젝트 설정 → 일반  메뉴

@Controller
@RequestMapping("/fcm")
public class FcmController {

	// FCM 테스트
	@RequestMapping(value = "/fcmTest.do", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
	public void fcmTest() throws Exception {

		try {
			// TODO : 본인의 비공개키 파일로 교체 필요
			String path = "D:/metalk-27e80-firebase-adminsdk-22qp0-a89559b63e.json";

			String MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
			String[] SCOPES = { MESSAGING_SCOPE };

			GoogleCredential googleCredential = GoogleCredential.fromStream(new FileInputStream(path))
					.createScoped(Arrays.asList(SCOPES));
			googleCredential.refreshToken();

			HttpHeaders headers = new HttpHeaders();
			headers.add("content-type", MediaType.APPLICATION_JSON_VALUE);
			headers.add("Authorization", "Bearer " + googleCredential.getAccessToken());

			// notification
			JSONObject notification = new JSONObject();
			notification.put("body", "TEST1 body");
			notification.put("title", "TEST1 title");
			
			// data
			JSONObject data = new JSONObject();
			data.put("body", "TEST2 body");
			data.put("title", "TEST2 title");

			JSONObject message = new JSONObject();

			// TODO : 본인의 스마트폰 앱에 발급된 사용자 토큰으로 교체 필요
			message.put("token", "fdQLBpfTSR-1wa6OWNwJQd:APA91bF8DUc_hIiYK3kU_kLt_aFNjMrRcnVubnTMyWQP_yMtAA0z-fzWmcmyZxzh1A4CNc8U5YggsQfyiCln3XOBWEZ9MMUF-k4Pf4a0PuVvJu9fGdGtr8JR6jOjrvSZxV7QeFKNlrLN");
			message.put("notification", notification);
			message.put("data", data);
			
			JSONObject jsonParams = new JSONObject();
			jsonParams.put("message", message);

			HttpEntity<JSONObject> httpEntity = new HttpEntity<JSONObject>(jsonParams, headers);
			RestTemplate rt = new RestTemplate();

			// TODO : 본인의 프로젝트ID로 수정 필요
			ResponseEntity<String> res = rt.exchange("https://fcm.googleapis.com/v1/projects/metalk-27e80/messages:send", HttpMethod.POST, httpEntity, String.class);

			if (res.getStatusCode() != HttpStatus.OK) {
				System.out.println("FCM-Exception");
				System.out.println(res.getStatusCode().toString());
				System.out.println(res.getHeaders().toString());
				System.out.println(res.getBody().toString());

			} else {
				System.out.println(res.getStatusCode().toString());
				System.out.println(res.getHeaders().toString());
				System.out.println(res.getBody().toLowerCase());
			}
            
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

해석

해당 token의 사용자 1명에게만 FCM notification 메시지를 보낼 수 있습니다.
admin SDK를 사용해서 전체 사용자에게는 못 보내고, 그룹 단위로 보낼 수 있습니다. (해보지는 않음)

FCM HTTP API가 구버전이 있고 신버전(v1)이 있는데, 위 코드는 v1 버전 입니다.