文章

03 .FCM Server

03 .FCM Server

Firebase Admin SDK

FCM 的 Firebase Admin SDK

Admin FCM API 可处理后端身份验证工作,同时便于发送消息和管理主题订阅。借助 Firebase Admin SDK,您可以执行以下操作:

  • 向单个设备发送消息
  • 向主题和与一个或多个主题匹配的条件语句发送消息。
  • 为设备订阅和退订主题
  • 针对不同目标平台构建量身定制的消息载荷。

Admin Node.js SDK 提供了用于向设备组发送消息的方法。

Node.js

Java

集成

将 Firebase Admin SDK 添加到您的服务器

初始化

将 Firebase Admin SDK 添加到您的服务器

默认凭证
1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration  
public class FirebaseConfig {
	@Bean
	FirebaseApp firebaseApp() throws IOException {
		GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
		System.out.println("firebaseApp credentials=" + credentials);
		FirebaseOptions options = FirebaseOptions.builder()
				.setCredentials(credentials)
				.build();
	
		return FirebaseApp.initializeApp(options);
	}
}
非 Google 环境初始化

如需为您的服务账号生成私钥文件,请执行以下操作:

  1. 在 Firebase 控制台中,依次打开设置 > 服务账号
  2. 点击生成新的私钥,然后点击生成密钥进行确认。
  3. 妥善存储包含密钥的 JSON 文件。

  1. the-monkey-king-assistant-firebase-adminsdk-i4v7o-2c3047793a.json 下载该文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@Configuration
public class FirebaseConfig {

    private static final Logger logger = LoggerFactory.getLogger(FirebaseConfig.class);

    @Value("${firebase.config.file-path}")
    private String firebaseConfigPath;
//
    @Bean
    FirebaseApp firebaseApp(GoogleCredentials credentials) {
        System.out.println("firebaseApp credentials=" + credentials);
        FirebaseOptions options = FirebaseOptions.builder()
                .setCredentials(credentials)
                .build();

        return FirebaseApp.initializeApp(options);
    }

    @Bean
    GoogleCredentials googleCredentials() throws IOException {
        System.out.println("googleCredentials firebaseConfigPath=" + firebaseConfigPath);
        if (firebaseConfigPath != null) {
            // 服务账户密钥文件路径
            FileInputStream serviceAccount =
                    new FileInputStream("src/main/resources/the-monkey-king-assistant-firebase-adminsdk-i4v7o-2c3047793a.json");
//                    new FileInputStream(firebaseConfigPath);

            // 加载凭证
            GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);

            // 检查凭证是否有效
            if (credentials != null) {
                logger.info("GoogleCredentials loaded successfully.");
            }
            return credentials;
        } else {
            // Use standard credentials chain. Useful when running inside GKE
            return GoogleCredentials.getApplicationDefault();
        }
    }

    @Bean
    FirebaseMessaging firebaseMessaging(FirebaseApp firebaseApp) {
        System.out.println("firebaseMessaging FirebaseApp=" + firebaseApp);
        return FirebaseMessaging.getInstance(firebaseApp);
    }
}

问题

NOT_FOUND # Requested entity was not found

1
2
3
4
5
6
7
I understand you're getting token not found error (Unregistered) when sending message request to FCM servers. The Unregistered error  occurs when the token used is invalid and a new token must be used. As stated in our documentation, there are several possible causes that may cause the tokens to be invalid. Possible causes for invalid tokens are the following:
If the client app unregisters with FCM.
If the client app is automatically unregistered, which can happen if the user uninstalls the application.
If the client app is updated but the new version is not configured to receive messages.
The app is restored on a new device
The user clears app data.
Also, FCM invalidates FCM tokens that hasn't connected to servers for the past 270 days which leads to Unregistered error. Given that information, the best way to handle it would be to follow our best practices for FCM registration tokens and to monitor your token's freshness whenever a new one is generated. You'll need to implement it programmatically. Determining whether a token is fresh or stale is not always straightforward. To cover all cases, you should adopt a threshold for when you consider tokens stale; our recommendation is two months. Any token older than two months is likely to be an inactive device; an active device would have otherwise refreshed its token.

Ref

本文由作者按照 CC BY 4.0 进行授权