/**
|
|
* 微信小程序订阅消息工具
|
|
* 用于统一管理订阅消息通知功能
|
|
*/
|
|
|
|
/**
|
|
* 订阅模板消息
|
|
* @param {Array} templateIds - 模板ID数组,如果不传则使用默认模板
|
|
* @returns {Promise} 返回订阅结果
|
|
*/
|
|
export function subscribeMessage(templateIds = null) {
|
|
return new Promise((resolve, reject) => {
|
|
// 默认的模板ID列表
|
|
const defaultTemplateIds = [
|
|
'uXZnHWrjtcX9JHlnMpdlWmzgJp71sKxCRiMn3TrE-EE',
|
|
'gTzGpOfJcYxtbvPG9OHnhbureKz5XLG8NPyECUGb2lw',
|
|
];
|
|
|
|
// 使用传入的模板ID或默认模板ID
|
|
const tmplIds = templateIds || defaultTemplateIds;
|
|
|
|
wx.requestSubscribeMessage({
|
|
tmplIds: tmplIds, // 需要订阅的模板ID列表
|
|
success(res) {
|
|
resolve(res);
|
|
console.log('订阅消息调用成功', res);
|
|
|
|
// 遍历处理每个模板ID的订阅结果
|
|
tmplIds.forEach(tmplId => {
|
|
if (res[tmplId] === 'accept') {
|
|
console.log(`用户同意订阅模板ID:${tmplId}`);
|
|
// 这里可以添加用户同意后的逻辑,比如发送消息等(注意:发送消息需要在后端进行)
|
|
} else if (res[tmplId] === 'reject') {
|
|
console.log(`用户拒绝订阅模板ID:${tmplId}`);
|
|
} else {
|
|
console.log(`用户对该模板ID的订阅请求:${res[tmplId]}`); // 'ban' 表示用户被禁止订阅该模板
|
|
}
|
|
});
|
|
},
|
|
fail(err) {
|
|
resolve(err); // 即使失败也resolve,避免阻塞业务流程
|
|
console.error('订阅消息调用失败', err);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 在发布内容前调用订阅消息
|
|
* 这是一个便捷方法,用于在发布内容前统一处理订阅逻辑
|
|
* @param {Array} templateIds - 可选的模板ID数组
|
|
* @returns {Promise} 返回订阅结果
|
|
*/
|
|
export async function subscribeBeforePublish(templateIds = null) {
|
|
try {
|
|
const result = await subscribeMessage(templateIds);
|
|
return result;
|
|
} catch (error) {
|
|
console.error('订阅消息失败:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export default {
|
|
subscribeMessage,
|
|
subscribeBeforePublish
|
|
};
|