瑶都万能墙
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.4 KiB

  1. /**
  2. * 微信小程序订阅消息工具
  3. * 用于统一管理订阅消息通知功能
  4. */
  5. /**
  6. * 订阅模板消息
  7. * @param {Array} templateIds - 模板ID数组如果不传则使用默认模板
  8. * @returns {Promise} 返回订阅结果
  9. */
  10. export function subscribeMessage(templateIds = null) {
  11. return new Promise((resolve, reject) => {
  12. // 默认的模板ID列表
  13. const defaultTemplateIds = [
  14. 'uXZnHWrjtcX9JHlnMpdlWmzgJp71sKxCRiMn3TrE-EE',
  15. 'gTzGpOfJcYxtbvPG9OHnhbureKz5XLG8NPyECUGb2lw',
  16. ];
  17. // 使用传入的模板ID或默认模板ID
  18. const tmplIds = templateIds || defaultTemplateIds;
  19. wx.requestSubscribeMessage({
  20. tmplIds: tmplIds, // 需要订阅的模板ID列表
  21. success(res) {
  22. resolve(res);
  23. console.log('订阅消息调用成功', res);
  24. // 遍历处理每个模板ID的订阅结果
  25. tmplIds.forEach(tmplId => {
  26. if (res[tmplId] === 'accept') {
  27. console.log(`用户同意订阅模板ID:${tmplId}`);
  28. // 这里可以添加用户同意后的逻辑,比如发送消息等(注意:发送消息需要在后端进行)
  29. } else if (res[tmplId] === 'reject') {
  30. console.log(`用户拒绝订阅模板ID:${tmplId}`);
  31. } else {
  32. console.log(`用户对该模板ID的订阅请求:${res[tmplId]}`); // 'ban' 表示用户被禁止订阅该模板
  33. }
  34. });
  35. },
  36. fail(err) {
  37. resolve(err); // 即使失败也resolve,避免阻塞业务流程
  38. console.error('订阅消息调用失败', err);
  39. }
  40. });
  41. });
  42. }
  43. /**
  44. * 在发布内容前调用订阅消息
  45. * 这是一个便捷方法用于在发布内容前统一处理订阅逻辑
  46. * @param {Array} templateIds - 可选的模板ID数组
  47. * @returns {Promise} 返回订阅结果
  48. */
  49. export async function subscribeBeforePublish(templateIds = null) {
  50. try {
  51. const result = await subscribeMessage(templateIds);
  52. return result;
  53. } catch (error) {
  54. console.error('订阅消息失败:', error);
  55. return null;
  56. }
  57. }
  58. export default {
  59. subscribeMessage,
  60. subscribeBeforePublish
  61. };