- vừa được xem lúc

Firebase Cloud Messaging-FCM push notification in Spring Boot

0 0 324

Người đăng: Muhammad Tamzid

Theo Viblo Asia

Firebase Cloud Messaging

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app. Read details.

Push notification using FCM

Now we will build an FCM push notification application using Spring Boot. At first we need to generate Firebase SDK admin key.

Firebase SDK admin key

Got to firbase console: https://console.firebase.google.com/u/0/

  • Create a new project
  • Generate new private key (Project settings -> Service accounts -> Generate new private key)

Spring Boot application

Lets create a new Spring Boot project. Here is our project structure

Put generated Firebase Admin SDK JSON file inside project src/main/resources . Here is application.properties.

app.firebase-config=fcm-test-62dad-firebase-adminsdk-3pd7w-bdaed458f4.json

We need to add Firebase dependencies in pom.xml.

<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>6.9.0</version>
</dependency>

initialize Firebase app:

 @Value("${app.firebase-config}") private String firebaseConfig; private FirebaseApp firebaseApp; @PostConstruct private void initialize() { try { FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(GoogleCredentials.fromStream(new ClassPathResource(firebaseConfig).getInputStream())).build(); if (FirebaseApp.getApps().isEmpty()) { this.firebaseApp = FirebaseApp.initializeApp(options); } else { this.firebaseApp = FirebaseApp.getInstance(); } } catch (IOException e) { log.error("Create FirebaseApp Error", e); } }

Push notification to device token

To send Push notification to device token, we just need device token and notification data.

Controller:

 @PostMapping("/token") public String sendPnsToDevice(@RequestBody NotificationRequestDto notificationRequestDto) { return notificationService.sendPnsToDevice(notificationRequestDto); }

Dto:

@Data
public class NotificationRequestDto { private String target; private String title; private String body;
}

Service:

 public String sendPnsToDevice(NotificationRequestDto notificationRequestDto) { Message message = Message.builder() .setToken(notificationRequestDto.getTarget()) .setNotification(new Notification(notificationRequestDto.getTitle(), notificationRequestDto.getBody())) .putData("content", notificationRequestDto.getTitle()) .putData("body", notificationRequestDto.getBody()) .build(); String response = null; try { response = FirebaseMessaging.getInstance().send(message); } catch (FirebaseMessagingException e) { log.error("Fail to send firebase notification", e); } return response; }

Push notification to topic

To send Push notification to topic, at first we need to subscribe to topic by device token. So process will be subscribe to a topic by device token, send push notification by topic, we can unsubscribe from topic as well.

Controller:

 @PostMapping("/subscribe") public void subscribeToTopic(@RequestBody SubscriptionRequestDto subscriptionRequestDto) { notificationService.subscribeToTopic(subscriptionRequestDto); } @PostMapping("/unsubscribe") public void unsubscribeFromTopic(SubscriptionRequestDto subscriptionRequestDto) { notificationService.unsubscribeFromTopic(subscriptionRequestDto); } @PostMapping("/topic") public String sendPnsToTopic(@RequestBody NotificationRequestDto notificationRequestDto) { return notificationService.sendPnsToTopic(notificationRequestDto); }

Dto:

@Data
public class NotificationRequestDto { private String target; private String title; private String body;
}

Service:

 public void subscribeToTopic(SubscriptionRequestDto subscriptionRequestDto) { try { FirebaseMessaging.getInstance(firebaseApp).subscribeToTopic(subscriptionRequestDto.getTokens(), subscriptionRequestDto.getTopicName()); } catch (FirebaseMessagingException e) { log.error("Firebase subscribe to topic fail", e); } } public void unsubscribeFromTopic(SubscriptionRequestDto subscriptionRequestDto) { try { FirebaseMessaging.getInstance(firebaseApp).unsubscribeFromTopic(subscriptionRequestDto.getTokens(), subscriptionRequestDto.getTopicName()); } catch (FirebaseMessagingException e) { log.error("Firebase unsubscribe from topic fail", e); } } public String sendPnsToTopic(NotificationRequestDto notificationRequestDto) { Message message = Message.builder() .setTopic(notificationRequestDto.getTarget()) .setNotification(new Notification(notificationRequestDto.getTitle(), notificationRequestDto.getBody())) .putData("content", notificationRequestDto.getTitle()) .putData("body", notificationRequestDto.getBody()) .build(); String response = null; try { FirebaseMessaging.getInstance().send(message); } catch (FirebaseMessagingException e) { log.error("Fail to send firebase notification", e); } return response; }

Summary

Here in this post we tired to cover Firebase Cloud Messaging integration using Spring Boot. Scource code available in GitHub .

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Cài đặt WSL / WSL2 trên Windows 10 để code như trên Ubuntu

Sau vài ba năm mình chuyển qua code trên Ubuntu thì thật không thể phủ nhận rằng mình đã yêu em nó. Cá nhân mình sử dụng Ubuntu để code web thì thật là tuyệt vời.

0 0 374

- vừa được xem lúc

Đặt tên commit message sao cho "tình nghĩa anh em chắc chắn bền lâu"????

. Lời mở đầu. .

1 1 701

- vừa được xem lúc

Tìm hiểu về Resource Controller trong Laravel

Giới thiệu. Trong laravel, việc sử dụng các route post, get, group để gọi đến 1 action của Controller đã là quá quen đối với các bạn sử dụng framework này.

0 0 335

- vừa được xem lúc

Phân quyền đơn giản với package Laravel permission

Như các bạn đã biết, phân quyền trong một ứng dụng là một phần không thể thiếu trong việc phát triển phần mềm, dù đó là ứng dụng web hay là mobile. Vậy nên, hôm nay mình sẽ giới thiệu một package có thể giúp các bạn phân quyền nhanh và đơn giản trong một website được viết bằng PHP với framework là L

0 0 421

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414