feat(cloud): 实现微信云函数 - 订阅管理与每日运势推送
- subscribe: 用户订阅/取消订阅/查询订阅状态 - daily-push: 定时查询订阅用户、生成运势、发送订阅消息 - push-test: 推送调试云函数 - 定时触发器配置,每日 7:00/12:00/18:00 推送
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
// 云函数:subscribe
|
||||
// 用户订阅每日运势推送,存储生辰信息和订阅偏好
|
||||
const cloud = require('wx-server-sdk')
|
||||
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||
const db = cloud.database()
|
||||
|
||||
exports.main = async (event, context) => {
|
||||
const { birthInfo, templateId, pushTime } = event
|
||||
const { OPENID } = cloud.getWXContext()
|
||||
|
||||
// 参数校验
|
||||
if (!birthInfo || !templateId) {
|
||||
return { success: false, error: '参数不完整' }
|
||||
}
|
||||
|
||||
if (!birthInfo.birthDate || birthInfo.birthHour == null || birthInfo.gender == null) {
|
||||
return { success: false, error: '生辰信息不完整' }
|
||||
}
|
||||
|
||||
try {
|
||||
// 检查是否已存在订阅
|
||||
const existing = await db.collection('subscriptions').where({
|
||||
openid: OPENID,
|
||||
}).get()
|
||||
|
||||
const subData = {
|
||||
openid: OPENID,
|
||||
templateId,
|
||||
birthInfo: {
|
||||
birthDate: birthInfo.birthDate,
|
||||
birthHour: birthInfo.birthHour,
|
||||
birthMinute: birthInfo.birthMinute || 0,
|
||||
birthPlace: birthInfo.birthPlace || '',
|
||||
longitude: birthInfo.longitude || 0,
|
||||
latitude: birthInfo.latitude || 0,
|
||||
gender: birthInfo.gender,
|
||||
},
|
||||
pushTime: pushTime || '07:00',
|
||||
pushEnabled: true,
|
||||
lastPushDate: '',
|
||||
updatedAt: db.serverDate(),
|
||||
}
|
||||
|
||||
if (existing.data.length > 0) {
|
||||
// 更新现有订阅
|
||||
await db.collection('subscriptions').doc(existing.data[0]._id).update({
|
||||
data: subData,
|
||||
})
|
||||
} else {
|
||||
// 新建订阅
|
||||
subData.subscribedAt = db.serverDate()
|
||||
await db.collection('subscriptions').add({
|
||||
data: subData,
|
||||
})
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
} catch (err) {
|
||||
console.error('[subscribe] Error:', err)
|
||||
return { success: false, error: err.message }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user