import cloud from '@lafjs/cloud'; import Utils from "@/Utils"; const db = cloud.database(); const MONTH_CARD_DURATION = 30 * 24 * 60 * 60 * 1000; export default async function (ctx: FunctionContext) { const action = ctx.body.action; const uid = ctx.body.uid; if (!action) { return { code: 0, data: null, msg: "未获取到action" }; } if (!uid) { return { code: 0, data: null, msg: "未获取到uid" }; } let dbname = "users"; const gameName = ctx.body.gameName; if (gameName == "iaa") { dbname = "usersAd"; } const res = await db.collection(dbname).where({ _id: uid }).getOne(); const token = ctx.body.token; if (res.data && res.data.token) { const isTokenValid = Utils.checkToken(token, res.data.token); if (!isTokenValid) { return { code: 0, data: null, msg: "token校验失败" }; } } switch (action) { case "save": { const now = Date.now(); const oldMonthCardTime = Number(res.data?.monthCardTime) || 0; const oldMonthCardReward = Number(res.data?.monthCardReward) || 0; const outTradeNo = ctx.body.outTradeNo; // 测试账号校验月卡订单,并确保同一订单只延长一次。 if (outTradeNo) { const order = await db.collection("order").where({ outTradeNo: outTradeNo }).getOne(); if (!order.data || order.data.itemid !== "month_Card" || order.data.openid !== res.data?.openid) { return { code: 0, data: null, msg: "月卡订单校验失败" }; } if (order.data.state !== 2) { return { code: 0, data: null, msg: "月卡订单尚未完成发货确认" }; } if (order.data.monthCardGranted === true) { return { code: 1, data: { monthCardTime: oldMonthCardTime, monthCardReward: oldMonthCardReward, alreadyGranted: true }, msg: "该月卡订单已续订" }; } } // 有效期内续订:从原到期时间继续加30天; // 已过期或首次购买:从当前时间加30天。 const monthCardTime = Math.max(oldMonthCardTime, now) + MONTH_CARD_DURATION; // 有效期内续订保留当天领取状态,避免同一天重复领取。 const monthCardReward = oldMonthCardTime > now ? oldMonthCardReward : 0; await db.collection(dbname).where({ _id: uid }).update({ monthCardTime: monthCardTime, monthCardReward: monthCardReward }); if (outTradeNo) { await db.collection("order").where({ outTradeNo: outTradeNo }).update({ monthCardGranted: true }); } return { code: 1, data: { monthCardTime: monthCardTime, monthCardReward: monthCardReward, alreadyGranted: false }, msg: "月卡记录成功" }; } case "read": { const monthCardTime = res.data?.monthCardTime || 0; const monthCardReward = res.data?.monthCardReward || 0; if (monthCardTime < Date.now()) { return { code: 0, data: { monthCardTime: monthCardTime, monthCardReward: monthCardReward }, msg: "不在有效期" }; } return { code: 1, data: { monthCardTime: monthCardTime }, msg: "成功" }; } default: return { code: 400, message: "无效的操作类型,请使用 save 或 read" }; } }