My serser uses Java with SpringBoot and my client is an expo react native app which uses typescript. I am really blocked by this feature: I want to sens push notifications. I tried a lot of methods, but I didn't succeed.
I tried to use Google FCM API to send the push notifications, but I noticed that I need the REGISTRATION TOKENS and I can't get them on the BE side.
In the official documentation is described the method, but using Android: https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId.
I have something like:
The service
@Service
public class FirebaseMessagingService {
private static final String FIREBASE_SERVER_KEY = server key from firebase project from cloud messaging section;
private static final String FIREBASE_API_URL = "https://fcm.googleapis.com/fcm/send";
@Async
public CompletableFuture<String> send(HttpEntity<String> entity) {
RestTemplate restTemplate = new RestTemplate();
ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor("Authorization", "key=" + FIREBASE_SERVER_KEY));
interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/json"));
restTemplate.setInterceptors(interceptors);
String firebaseResponse = restTemplate.postForObject(FIREBASE_API_URL, entity, String.class);
return CompletableFuture.completedFuture(firebaseResponse);
}
}
And
The Controller
@Autowired
FirebaseMessagingService firebaseMessagingService;
@RequestMapping(value = "/send", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> send(){
JSONObject body = new JSONObject();
body.put("to", "GM4nGHeift2zv4IDm9O75");
body.put("priority", "high");
JSONObject notification = new JSONObject();
notification.put("title", "JSA Notification");
notification.put("body", "Happy Message!");
JSONObject data = new JSONObject();
data.put("Key-1", "JSA Data 1");
data.put("Key-2", "JSA Data 2");
body.put("notification", notification);
body.put("data", data);
HttpEntity<String> request = new HttpEntity<>(body.toString());
CompletableFuture<String> pushNotification = firebaseMessagingService.send(request);
CompletableFuture.allOf(pushNotification).join();
try {
String firebaseResponse = pushNotification.get();
return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
}
When I try to send a notification, I receive the following error:
{
"multicast_id": 385944902818046340,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}
Do you have any idea about how should I proceed to get the registration tokens on a Java project and send push notifications to my Expo client?
Thanks