android - 在特定条件下触发通知在 Firebase 上满足
问题描述
嗨,我想向那些将商品添加到购物车并且在 7 天内未购买的用户触发通知。
我想自动完成。在 firebase 上实现这个的正确方法是什么?
解决方案
const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp();
// timestamp the cart with last item added date/time
exports.timestampCartItem =
functions.database.ref('/users/{uid}/cart/{item}')
.onCreate((snapshot, context) => {
return snapshot.ref.parent('timestamp').set((new Date()).getTime()); // milliseconds
})
// Call this function every hour using https://cron-job.org/en/
const CART_EXPIRE_TIME = Number(7 * 24 * 60 * 60 * 1000); // days * hours * minutes * seconds * milliseconds
exports.scanZombieCarts = functions.https.onRequest((request, response) => {
const server_time = Number((new Date()).getTime());
const usersDBRef = admin.database().ref('users');
const notifyDBRef = admin.database().ref('notify'); // queue to send notifications with FCM
return usersDBRef.once('value')
.then(users => {
let zombie_promises = [];
users.forEach(usersnap => {
let userid = usersnap.key;
let user = usersnap.val();
if (user.hasOwnProperty('cart')) {
let cart_timestamp = Number(user.cart.timestamp || 0) + CART_EXPIRE_TIME;
if (cart_timestamp < server_time) {
zombie_promises.push(
notifyDBRef.push({
'notification': {
'body': `You have ${Object.keys(user.cart).length} items in your Cart.`,
'title': 'Sales end soon!'
},
'token': user.devicetoken
})
);
}
}
})
return Promise.all(zombie_promises);
})
.then(() => {
let elapsed_time = ((new Date()).getTime() - (server_time)) / 1000;
response.status(200);
response.send(`<h2>Finished scan of Zombie Carts...${elapsed_time} seconds</h2>`);
return null;
})
.catch(err => {
response.status(500);
response.send(`<h2>Scan failed</h2>`);
console.log(err);
})
});
// IMPORTANT:
// https://console.developers.google.com/apis search for and enable FCM
exports.sendReminder =
functions.database.ref('/notify/{message}')
.onCreate((snapshot, context) => {
let message = snapshot.val();
let send_and_consume = [
admin.messaging().send(message), // send message to device
snapshot.ref.remove() // consumes message from queue
]
return Promise.all(send_and_consume)
.catch(err => {
console.log(err); // probably bad token
})
})
备注 这假设当用户打开应用程序时,应用程序会使用从消息中获取的设备令牌写入“users/{uid}/devicetoken”键。
请参阅有关启用 FCM 和 CRON 触发器的内部注释。
测试
将所有这些添加到您的 index.js 文件中,用于firebase deploy
上传到服务器。
在控制台中手动编辑 Firebase 数据库以观察触发器自动添加/更新时间戳。
用于firebase serve --only functions
从您的机器本地测试/调试您的 https 触发器。它将为您提供运行的 localhost 链接,您可以在控制台中捕获错误。
推荐阅读
- react-native - 我的项目没有在 android 模拟器上运行,但可以在 iphone 上运行
- java - KeyListener is firering wrong Events
- python - 验证输入的第一个数字是 4
- python - 为什么 Numpy 掩码数组有用?
- javascript - javascript函数在雪花函数中给出NULL
- slurm - 如何强制用户在 slurm 中的某个目录中提交作业
- javascript - 如何在 Electron 中将 ImageData 保存为 PNG
- java - 如何使用 MenuItem 中的事件处理程序关闭窗口
- angular - 如何使用数组中的多个条件过滤对象?
- android - 设计选项卡未正确显示(内容被翻转)