如何将客户端 firebase 云消息传递令牌获取到 google 云功能?

How do you get client-side firebase cloud messaging token into google cloud function?

我正在努力实现在更改 Firebase Firestore 文档时出现的推送通知。我正在使用 react-native-firebase 模块。我的 google 云功能会监听 firestore 的变化,然后通过 firebase-admin 发送消息。

google 的参考说明您可以指定一个设备来发送消息:

// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';

var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  token: registrationToken
};

// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

客户端在我的本机反应应用程序中我使用 react-native-firebase:

获得了一个令牌
function getToken() {
  let fcmToken = await AsyncStorage.getItem("fcmToken");
  if (!fcmToken) {
    fcmToken = await firebase.messaging().getToken();
    if (fcmToken) {
      await AsyncStorage.setItem("fcmToken", fcmToken);
    }
  }
}

我是否必须将 google 云消息传递令牌存储在异步存储以外的其他地方,或者有没有办法在我的 google 云功能中按原样访问它?看来我应该将身份验证令牌存储在 firestore 中并使用云功能访问 firestore。这是最好的方法吗?

您不需要 AsyncStorage 来访问令牌,它可以直接从您的代码中的 fcmToken = await firebase.messaging().getToken(); 获得。

您可以从那里将其发送到回调云函数,例如:

var sendMessage = firebase.functions().httpsCallable('sendMessage');
addMessage({ token: fcmToken }).then(function(result) {
  // ...
});

这基于文档 here 中的示例。然后,您可以在 Cloud Functions 代码中使用此值,通过 Admin SDK 调用 FCM API 来发送消息。

或者将其存储在数据库中,例如 Cloud Firestore,使用如下内容:

db.collection("tokens").add(docData).then(function() {
    console.log("Token successfully written to database!");
});

基于文档 here 中的示例。然后,您可以从 Cloud Function 中的数据库中读取此值,并使用它通过 Admin SDK 调用 FCM API 再次发送消息。