微信小程序加入页面访问统计功能

2025-09-12 18:31:11 阅读:4 编辑

app.js

// 单例模式导出
import tracker from '/zhy/resource/js/tracker';
  onShow(options) {
    // 记录启动事件
    tracker.trackPageView('launch');
     // ...
  }

mixins.js

// 单例模式导出
import tracker from '/zhy/resource/js/tracker';
 onShow(){
  // 记录页面访问
  tracker.trackPageView(getCurrentPages().slice(-1)[0].route);
  },

/zhy/resource/js/tracker.js

// utils/tracker.js

const STORAGE_KEY = 'page_events_cache';
const BATCH_SIZE = 5; // 批量上报条数
const REPORT_INTERVAL = 10000; // 10秒上报一次

class Tracker {
  constructor() {
    this.systemInfo = null;
    this.timer = null;
    this.init();
  }

  async init() {
    try {
      this.systemInfo = await wx.getSystemInfo();
    } catch (e) {
      console.error('获取设备信息失败:', e);
      this.systemInfo = {};
    }
    this.startReportTimer();
  }

  // 记录页面访问
  trackPageView(pagePath) {
    const event = {
      event_type: 'page_view',
      page_path: pagePath,
      timestamp: Date.now(),
      device_info: this.getDeviceInfo(),
      scene: this.getScene()
    };
    let user_id = this.getUserId();
    if(user_id){
      event.user_id = user_id;
    }

    this.cacheEvent(event);
  }
  getUserId(){
    let user_id = 0;
    let zhyshopInfo = wx.getStorageSync("zhyshopInfo");
    if (zhyshopInfo) {
      user_id = zhyshopInfo.id;
    }
    return user_id;
  }

  // 获取设备信息
  getDeviceInfo() {
    if (!this.systemInfo) return {};

    return {
      model: this.systemInfo.model,
      system: this.systemInfo.system,
      platform: this.systemInfo.platform,
      version: this.systemInfo.version,
      sdkVersion: this.systemInfo.SDKVersion,
      screen_width: this.systemInfo.screenWidth,
      screen_height: this.systemInfo.screenHeight
    };
  }

  // 获取场景值
  getScene() {
    const scene = wx.getLaunchOptionsSync().scene;
    return {
      scene_id: scene,
      scene_desc: this.getSceneDesc(scene)
    };
  }

  // 场景值描述
  getSceneDesc(scene) {
    const scenes = {
      1001: '发现栏小程序主入口',
      1005: '顶部搜索框的搜索结果页',
      1006: '发现栏小程序主入口搜索框的搜索结果页',
      1007: '单人聊天会话中的小程序消息卡片',
      1008: '群聊会话中的小程序消息卡片',
      1011: '扫描二维码',
      1012: '长按图片识别二维码',
      1013: '手机相册选取二维码',
      1014: '小程序模板消息',
      1017: '前往体验版的入口页',
      1019: '微信钱包',
      1020: '公众号 profile 页相关小程序列表',
      1022: '聊天顶部置顶小程序入口',
      1023: '安卓系统桌面图标',
      1024: '小程序 profile 页',
      1025: '扫描一维码',
      1026: '附近小程序列表',
      1027: '顶部搜索框搜索结果页「使用过的小程序」列表',
      1028: '我的卡包',
      1029: '卡券详情页',
      1030: '自动化测试下打开小程序',
      1031: '长按图片识别一维码',
      1032: '手机相册选取一维码',
      1034: '微信支付完成页',
      1035: '公众号自定义菜单',
      1036: 'App 分享消息卡片',
      1037: '小程序打开小程序',
      1038: '从另一个小程序返回',
      1039: '摇电视',
      1042: '添加好友搜索框的搜索结果页',
      1043: '公众号模板消息',
      1044: '带 shareTicket 的小程序消息卡片',
      1047: '扫描小程序码',
      1048: '长按图片识别小程序码',
      1049: '手机相册选取小程序码',
      1052: '卡券的适用门店列表',
      1053: '搜一搜的结果页',
      1054: '顶部搜索框小程序快捷入口',
      1056: '音乐播放器菜单',
      1057: '钱包中的银行卡详情页',
      1058: '公众号文章',
      1059: '体验版小程序绑定邀请页',
      1064: '微信连Wi-Fi状态栏',
      1067: '公众号文章广告',
      1068: '附近小程序列表广告',
      1069: '移动应用',
      1071: '钱包中的银行卡列表页',
      1072: '二维码收款页面',
      1073: '客服消息列表下发的小程序消息卡片',
      1074: '公众号会话下发的小程序消息卡片',
      1077: '摇周边',
      1078: '微信连Wi-Fi成功提示页',
      1079: '微信游戏中心',
      1081: '客服消息下发的文字链',
      1082: '公众号会话下发的文字链',
      1084: '朋友圈广告',
      1089: '微信聊天主界面下拉',
      1090: '长按小程序右上角菜单唤出最近使用历史',
      1091: '公众号文章商品卡片',
      1092: '城市服务入口',
      1095: '小程序广告组件',
      1096: '聊天记录',
      1097: '微信支付签约页',
      1099: '页面内嵌插件',
      1102: '公众号 profile 页服务预览',
      1103: '发现栏小程序主入口,「我的小程序」列表',
      1104: '微信聊天主界面下拉,「我的小程序」栏',
      1106: '聊天主界面下拉,从顶部搜索结果页进入',
      1107: '订阅消息,打开小程序',
      1113: '安卓手机负一屏卡片',
      1114: '安卓手机侧边栏',
      1124: '扫「一物一码」打开小程序',
      1125: '长按图片识别「一物一码」',
      1126: '扫描手机相册中选取的「一物一码」',
      1129: '微信爬虫访问',
      1131: '浮窗',
      1144: '公众号文章 - 视频',
      1145: '公众号文章 - 音频',
      1146: '小程序 profile 页相关小程序列表',
      1148: '发现栏 - 小程序个性化推荐',
      1150: '浮窗时打开的系统导航栏',
      1151: '浮窗时打开的系统导航栏,快捷入口',
      1152: '小程序 profile 页 - 右上角菜单',
      1153: '发现栏小程序主入口,各个生活服务入口',
      1154: '微信支付完成页',
      1155: '公众号广告',
      1157: '发现栏 - 小程序测评',
      1158: '发现栏 - 小程序测评结果',
      1167: '加群结果页',
      1169: '聊天素材用小程序打开',
      1171: '视频号主页 - 商品tab',
      1173: '视频号直播 - 商品',
      1175: '视频号主页 - 服务菜单',
      1176: '视频号主播个人主页 - 服务菜单',
      1177: '微信搜一搜 - 服务搜索',
      1178: '聊天顶部搜索框 - 服务搜索',
      1179: '微信搜一搜 - 品牌搜索',
      1181: '视频号 - 商品橱窗',
      1183: '视频号直播 - 活动',
      1185: '搜一搜 - 小程序',
      1186: '发现栏 - 发现小程序',
      1187: '发现栏 - 我的小程序',
      1188: '发现栏 - 最近使用',
      1189: '发现栏 - 附近的小程序',

    };
    return scenes[scene] || '未知场景';
  }
  // 缓存事件
  cacheEvent(event) {
    wx.getStorage({
      key: STORAGE_KEY,
      success: (res) => {
        const events = res.data || [];
        events.push(event);
        wx.setStorage({
          key: STORAGE_KEY,
          data: events,
          complete: () => {
            this.checkAndReport();
          }
        });
      },
      fail: () => {
        wx.setStorage({
          key: STORAGE_KEY,
          data: [event],
          complete: () => {
            this.checkAndReport();
          }
        });
      }
    });
  }

  // 启动定时上报
  startReportTimer() {
    if (this.timer) clearInterval(this.timer);
    this.timer = setInterval(() => {
      this.reportEvents();
    }, REPORT_INTERVAL);
  }

  // 检查并上报
  checkAndReport() {
    wx.getStorage({
      key: STORAGE_KEY,
      success: (res) => {
        if (res.data && res.data.length >= BATCH_SIZE) {
          this.reportEvents();
        }
      }
    });
  }

  // 上报事件
  reportEvents() {
    const app = getApp();
    /* let url = app.siteInfo.siteroot + "?i=" + app.siteInfo.uniacid + "&t=0&v=1.0&from=wxapp&c=entry&a=wxapp&do=Api_track|batch&m=zhyshop_sun"; */
    let url = "https://bigdata.n7y.cn/api/track/batch";
    wx.getStorage({
      key: STORAGE_KEY,
      success: (res) => {
        const events = res.data || [];
        if (events.length === 0) return;
        wx.request({
          url: url,
          header: {
            "content-type": "application/json", // 默认值
          },
          method: 'POST',
          data: {
            events: events,
            app_version: this.getAppVersion()
          },
          success: () => {
            // 上报成功后清空缓存
            wx.setStorage({
              key: STORAGE_KEY,
              data: []
            });
          },
          fail: (err) => {
            console.error('上报失败:', err);
            // 失败后保留数据下次重试
          }
        });
      }
    });
  }
  // 获取小程序版本信息
  getAppVersion() {
    const accountInfo = wx.getAccountInfoSync();
    return {
      version: accountInfo.miniProgram.version,
      env: accountInfo.miniProgram.envVersion
    };
  }
}
// 单例模式导出
export default new Tracker();