首页 > 解决方案 > 在特定条件下触发通知在 Firebase 上满足

问题描述

嗨,我想向那些将商品添加到购物车并且在 7 天内未购买的用户触发通知。

我想自动完成。在 firebase 上实现这个的正确方法是什么?

标签: androidfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


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 链接,您可以在控制台中捕获错误。


推荐阅读