如何将客户端Firebase云消息传递令牌转换为Google Cloud函数?

吉姆

我正在努力实现在更改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云消息传递令牌,或者是否可以在Google Cloud函数内部按原样访问它?看来我应该将auth令牌存储在firestore中,并使用云函数访问firestore。这是最好的方法吗?

弗兰克·范普菲伦

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

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

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

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

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将文本框客户端ID传递给JavaScript函数

如何使用客户端库将格式传递给Google Cloud Translation API?

从Firebase Cloud函数调用函数

如何将Flask应用程序转换为Google Cloud函数

k8s go客户端:如何将v1.Deployment类型传递给函数

将变量传递给Google Cloud函数

Firebase Web 客户端重写了 https.onRequest 函数返回的错误消息,如何防止?

如何将有状态客户端传递给lambda函数?

在 Firebase HTTP 云函数中,如何在条带收费函数中将对象返回给客户端应用程序?

未调用 Firebase Cloud 函数

Firebase 云函数错误:“在将标头发送到客户端后无法设置标头”

Google Cloud Storage Python客户端库中list_blobs函数中的分页如何工作

如何使用SAP Cloud SDK调用Java客户端内部的绑定函数/动作?

如何将函数的输出发送到 NodeJS 中的客户端?

如何从Firebase Cloud Function调用异步函数

如何将转换转换为函数?

如何将HTTP可调用云函数响应转换为POJO?

Google Cloud / Firebase函数,处理每个函数的依赖性

Firebase 函数:如何维护“应用全局”API 客户端?

Firebase 函数:如何从客户端获取 IP 地址?

Firebase 云消息传递 - 从 JavaScript 客户端订阅主题

如何从python函数登录Google Cloud Storage?

Cloud Firestore、nodejs(云函数)、同步访问

Firebase:客户端事务和云函数事务之间有区别吗?

Firebase云函数即使成功也向客户端返回null

Firebase Cloud Messaging Java客户端

如何编写一个 http 触发的 Firebase 云函数,该函数使用来自客户端的输入信息注册用户

Google Cloud Storage客户端

如何从Python Cloud函数触发/调用Cloud Build