sparta-tigers / sparta-tigers/backend
[GUIDE] FCMService 활용 알림 발송하기 & 예제 코드
Open
@pottq577 is already working on this.
Since Sep 12, 2025.
good first issue
- Dominant language
- Java
- Stars
- 0
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
1. 사용 흐름 & 방식
사용 흐름
FCMService는 실제 사용 시 각 도메인의 서비스 계층에서 주입받아 호출합니다.Controller→Business Service→FCMServcice
사용 방식
FCMService중 알림을 보낼 때 필요한 정보는token,title,body입니다.token은 사용자 기기 식별,title은 알림의 제목,body는 알림의 내용입니다.FCMService를 라이브러리라 생각하고, 비즈니스 서비스 계층에서FCMService의sendMessageToToken(token, title, body)메서드를 정의해줍니다.
이후 컨트롤러 계층에서 서비스 계층의 메서드를 호출하여 사용합니다.
3. 사용 예시 (경기 예매 알림)
1. Service
@Service
@RequiredArgsConstructor
public class TicketNotificationService {
// 1. FCMService 주입
private final FCMService fcmService;
/**
* 특정 사용자에게 경기 예매 알림을 보냅니다.
* @param user 알림을 받을 사용자 (DB에서 조회한 User 엔티티)
* @param gameTitle 알림을 보낼 경기 제목 (예: "LG vs 두산")
*/
public void sendTicketReminder(User user, String gameTitle) {
// 2. 사용자의 FCM 토큰 유효성 검사
String fcmToken = user.getFcmToken();
if (fcmToken == null || fcmToken.isEmpty()) {
return;
}
// 3. 알림 내용 구성
String title = "⚾️ 야구 경기 예매 알림";
String body = String.format("잠시 후 8시에 '%s' 경기 예매가 시작됩니다! 놓치지 마세요!", gameTitle);
// 4. FCMService 호출
fcmService.sendMessageToToken(fcmToken, title, body);
}
}
2. Controller
@RestController
@RequestMapping("/api/admin/notifications")
@RequiredArgsConstructor
public class AdminNotificationController {
private final TicketNotificationService ticketNotificationService;
private final UserRepository userRepository;
public record ReminderRequest(Long userId, String gameTitle) {}
@PostMapping("/ticket-reminder")
public ApiResponse<String> sendReminder(@RequestBody ReminderRequest request) {
User user = userRepository.findByIdOrElseThrow(request.userId());
ticketNotificationService.sendTicketReminder(user, request.gameTitle());
return ApiResponse.success("알림 전송 요청이 완료되었습니다.");
}
}
4. FCM 토큰 데이터 흐름
1. 프론트엔드: 토큰 생성 및 요청
- 사용자가 알림을 허용하면, 프론트엔드의 Firebase SDK가 Google 서버에 기기 토큰을 요청합니다.
- Google 서버는 기기에 대한 고유한 토큰을 발급받아 프론트엔드에 전달합니다.
2. 프론트엔드 → 백엔드: 토큰 전송
- 프론트엔드는 발급받은 토큰을 백엔드 서버로 보냅니다.
- 보통 로그인 직후, "이 사용자의 기기 토큰은 이것입니다." 라고 알려주는 API를 호출하는 방식으로 이루어집니다.
- ex)
POST /api/users/fcm-token
- ex)
3. 백엔드: 토큰 저장
- API를 통해 전달받은 토큰을 DB에 저장합니다.
- 일반적으로
User테이블에fcm_token같은 컬럼을 만들어 사용자와 토큰을 1:1로 매핑합니다.
4. 백엔드: 알림 발송 시 토큰 사용
- 특정 알림 트리거가 발생하면, 백엔드는 알림을 받을 사용자를 DB에서 조회합니다.
- 해당 사용자의 정보에 저장된
fcm_token값을 꺼냅니다. - 이 토큰을
FCMService에 넘겨주어 Firebase 서버에 "이 토큰을 가진 기기로 알림을 보내"달라는 요청을 보냅니다.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.