在SpringBoot java项目中获取firebase注册令牌



我的serser使用Java和SpringBoot,我的客户端是一个使用typescript的expo-react原生应用程序。我真的被这个功能屏蔽了:我想感应推送通知。我尝试了很多方法,但都没有成功。

我尝试使用Google FCM API发送推送通知,但我注意到我需要注册令牌,而我无法在BE端获得它们。

在官方文档中描述了该方法,但使用Android:https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId.

我有这样的东西:

服务

@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);
}
}

控制器

@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);
}

当我尝试发送通知时,我收到以下错误:

{
"multicast_id": 385944902818046340,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}

你知道我应该如何获得Java项目的注册令牌并向我的Expo客户端发送推送通知吗?

感谢

我的客户端是expo-react原生应用

由于FCM注册令牌特定于每个设备/应用程序组合,因此您需要将其放入React Native应用程序中。

如果您使用的是Firebase的常规JavaScript SDK,请参阅有关访问JavaScript SDK中的注册令牌的文档。

如果您正在使用React Native Firebase库,请按照此处和此处的说明进行操作:在React Native中获取FCM令牌

一旦你有了令牌,你就可以将其发送到服务器,然后在那里你可以使用它向特定的设备/应用程序组合发送消息。

最新更新