liaolx
2026-01-28 800921d1019814acce308db825662cdb3878842c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// 对订阅弹窗状态进行控制,包括订阅次数控制、订阅弹窗、订阅结果
// 订阅频控接入步骤:
// 1. 定义页面对应订阅弹窗type,补充到subscribeFields列表中,用于初次接入小程序清空订阅次数
// 2. 在页面中引入subscribe.ts,调用addSubscribeCount方法,传入type、模板id列表、频控次数limit,返回是否可以继续订阅
// 3. (若弹窗内全部模板同意时不需要继续弹窗)调用Taro.requestSubscribeMessage订阅消息,在订阅成功后success函数中调用checkSubscribeStatus方法,传入type、模板id列表、订阅结果result、频控次数limit,用于检查订阅勾选状态
 
import Taro from "@tarojs/taro";
import { checkOtp } from "./tools";
 
// 需要频控的订阅字段,用于清空订阅次数
const subscribeFields = [
  "STATION_DETAIL",
  "PRICE_INFO",
  "STATION_LIST",
  "VOUCHER_ENTRY",
];
 
// 增加订阅次数并返回是否可以继续订阅
/** 
 * @param {string} type 订阅弹窗类型
 * @param {string[]} tmplIds 模板id列表
 * @param {number} limit 频控次数
 * @param {boolean} needlogin 是否需要登录
 * @return {boolean} 是否可以继续订阅
 */
export async function addSubscribeCount(type, tmplIds, limit = 3, needlogin = true) {
  const isLogin = await checkOtp();
  if (!isLogin && needlogin) return false;
  const userInfo = Taro.getStorageSync(type);
  console.log(userInfo, "userInfo");
  Taro.setStorageSync(type, userInfo + 1 || 1);
  return new Promise((resolve, reject) => {
    Taro.getSetting({
      withSubscriptions: true,
      success(res) {
        if (res.subscriptionsSetting?.itemSettings) {
          let allSetting = true;
          tmplIds.forEach((item) => {
            if (!res.subscriptionsSetting?.itemSettings[item]) {
              allSetting = false;
            }
          });
          if (allSetting) {
            resolve(true);
          } else {
            resolve(userInfo < limit);
          }
        } else {
          resolve(userInfo < limit);
        }
      },
    });
  });
}
 
// 订阅次数清空
export function clearSubscribeCount() {
  subscribeFields.forEach((item) => {
    Taro.setStorageSync(item, 0);
  });
}
 
// 检查订阅勾选状态
export function checkSubscribeStatus(type, tmplIds, result, limit = 3) {
  let allSetting = true;
  tmplIds.forEach((item) => {
    if (result[item] !== "accept") {
      allSetting = false;
    }
  });
  if (allSetting) {
    Taro.setStorageSync(type, limit);
  }
}
 
 
// 获取登录状态
export function getLoginStatus() {
  checkOtp().then(otp => {
    if (!otp) {
      return false;
    }else{
      return true;
    }
  })
}