您如何将客户端Firebase云消息传递令牌放入Google云功能?

时间:2019-10-29 00:02:44

标签: javascript firebase firebase-cloud-messaging google-cloud-functions react-native-firebase

我正在努力实现在更改Firebase Firestore文档时出现的推送通知。我正在使用react-native-firebase模块。我的Google Cloud函数侦听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 cloud消息传递令牌,或者是否可以在我的google cloud函数内部按原样访问它?看来我应该将auth令牌存储在firestore中,并使用云函数访问firestore。这是最好的方法吗?

1 个答案:

答案 0 :(得分:1)

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

您可以从那里将其发送到回调的Cloud Function,例如:

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

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

或将其存储在数据库(例如Cloud Firestore)中,如下所示:

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

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