FCM PUSH(IOS) - Java Spring Boot Server HTTP v1 사용하여 PUSH 알림 적용하기
드디어 마무리 단계에 접어들어 PUSH를 적용하기로 했다.
회사에서 사용했던 PUSHY는 중국서비스에서 적용하기 위해 사용했기 때문에
이번에는 FCM을 사용해보기로 했다.
공식문서는 아래에서 확인 가능합니다.
firebase.google.com/docs/cloud-messaging/migrate-v1?authuser=0
JAVA 서버에서 적용하는 내용임을 알려드립니다! 프론트에서 설정해주는 부분은 따로 있습니다!
우선 프론트에서 파이버베이스 작업이 끝났다고 가정하고 시작하겠습니다.
앱추가된 프로젝트이름 클릭 - 톱니바퀴 모양 클릭하여 프로젝트 설정으로 들어가세요
이 설정안에서 json 파일을 다운받습니다. 여기 안에 필요한 key값들이 있으니 노출되지 않도록 조심해야합니다!
그리고 이 파일을 src-main-resources 안에 넣어줍니다.
그리고 application.yml에 의존성을 추가 해줍니다.
// FCM push
implementation 'com.google.firebase:firebase-admin:6.8.1'
//okhttp3
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.2.2'
okhttp3 는 API통신을 위해 사용합니다. 클래스 내에 초기화를 해줍니다!
동기처리를 위해 execute를 사용했습니다. clinet.newCall()안에 Request 오브젝트를 넣어줍니다.
OkHttpClient client = new OkHttpClient();
try {
Response response = client.newCall(request).execute();
String message = response.body().string();
System.out.println(message);
} catch (IOException e) {
System.err.println(e.toString());
}
Request는 이런 방식으로 되어있습니다
// message는 밑에서 만들겁니다!
RequestBody requestBody =
RequestBody.create(message, MediaType.get("application/json; charset=utf-8"));
Request request =
new Request.Builder()
.url(API_URL)
.post(requestBody)
.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + getAccessToken())
.build();
API_URL은 다음과 같이 넣어주시면 됩니다.
POST https://fcm.googleapis.com/v1/{parent=projects/*}/messages:send
getAccessToken 메서드는
private String getAccessToken() throws IOException {
GoogleCredentials googleCredentials =
GoogleCredentials.fromStream(new ClassPathResource(firebaseConfigPath).getInputStream())
.createScoped(List.of("https://www.googleapis.com/auth/cloud-platform"));
googleCredentials.refreshIfExpired();
return googleCredentials.getAccessToken().getTokenValue();
}
여기서 firebaseConfigPath는 아까 받은 json 파일의 경로를 적어주시면 됩니다. 저는 따로 resources안에 폴더를 생성해서 넣지않아서 파일 이름 그대로 넣어줬습니다!
이제 메시지를 만들어줄겁니다!
package com.tickettaca.commons.firebase.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
@Builder
@AllArgsConstructor
@Getter
public class NotificationRequest {
private boolean validate_only;
private Message message;
@Builder
@AllArgsConstructor
@Getter
public static class Apns{
private Payload payload;
}
@Builder
@AllArgsConstructor
@Getter
public static class Payload{
private Aps aps;
}
@Builder
@AllArgsConstructor
@Getter
public static class Aps{
private String sound;
}
@Builder
@AllArgsConstructor
@Getter
public static class Message {
private Notification notification;
private String token;
private Apns apns;
}
@Builder
@AllArgsConstructor
@Getter
public static class Notification {
private String title;
private String body;
private String image;
}
}
private String makeMessage(String pushToken, String title, String body) {
NotificationRequest fcmMessage =
NotificationRequest.builder()
.message(
NotificationRequest.Message.builder()
.token(pushToken)
.notification(
NotificationRequest.Notification.builder()
.title(title)
.body(body)
.image(null)
.build())
.apns(
NotificationRequest.Apns.builder()
.payload(
NotificationRequest.Payload.builder()
.aps(NotificationRequest.Aps.builder().sound("default").build())
.build())
.build())
.build())
.validate_only(false)
.build();
String fcmMessageString = "";
try {
fcmMessageString = objectMapper.writeValueAsString(fcmMessage);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return fcmMessageString;
}
공식문서에서 필요한 변수명을 dto에 만들어줍니다. 여기서 공식문서에서 확인한 부분은 애플일 경우 소리르 따로 정해주지 않으면 진동도 소리도 안나는 마법,, 위 코드에서 apns 가 진동이나 소리를 내주는 변수입니다. default로 정해두면 아이폰 기본음으로 전송이 됩니다.
기본적인 메시지 전송 방법이었습니다. 나머지 필요한 변수들은 공식문서를 참고해주세요!
혹시 몰라서 사용법도 올립니다! \u 로 시작하는 문자는 이모티콘 입니다^.^
private final FCMService fcmService;
fcmService.sendMessageTo(
lover.getPushToken(),
user.getName() + "이(가) 쿠폰을 사용하셨습니다. \uD83D\uDE03",
couponEntity.getBookEntity().getName());
'기타' 카테고리의 다른 글
Thymeleaf로 Pageable 적용하기! (0) | 2021.02.05 |
---|