【问题标题】:How do you get client-side firebase cloud messaging token into google cloud function?您如何将客户端 Firebase 云消息传递令牌放入谷歌云功能?
【发布时间】:2020-02-24 05:56:00
【问题描述】:

我正在努力实现对 Firebase Firestore 文档进行更改时出现的推送通知。我正在使用 react-native-firebase 模块。我的谷歌云功能会监听对 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 应用程序中,我使用 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);
    }
  }
}

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

【问题讨论】:

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


    【解决方案1】:

    您不需要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 来使用它再次发送消息。

    【讨论】:

    • 设备令牌通过可调用函数自动发送。 firebase.google.com/docs/reference/functions/…
    • 太酷了。我不知道。 :) 在这种情况下更容易,您可以从 context.instanceIdToken 获取可调用 Cloud Function 中的实例 ID 令牌。
    • 请注意,在您的客户端应用程序中,如果您在验证后保存了新用户,那么当您运行 firestore().collection(users).doc(uid).get() 时,原始响应对象包含 fcmToken,因此您可以将其写入数据库,然后将其放入您的使用用户 ID 的云函数,这里是一个示例:github.com/firebase/functions-samples/blob/master/…
    猜你喜欢
    • 2021-02-07
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多