腾讯MTA统计小程序端代码注解

使用文档地址:https://mta.qq.com/docs/wechat_mini_program.html

var MTA_CONFIG = {
  app_id: "",
  event_id: "",
  api_base: "https://pingtas.qq.com/pingd",
  prefix: "_mta_",
  version: "1.3.6",
  stat_share_app: !1,
  stat_pull_down_fresh: !1,
  stat_reach_bottom: !1
};

function getNetworkType(cb) {
  wx.getNetworkType({
    success: function (res) {
      cb(res.networkType);
    }
  });
}

function getSystemInfo() {
  var info = wx.getSystemInfoSync();
  return {
    adt: encodeURIComponent(info.model), // 手机型号
    scl: info.pixelRatio, // 设备像素比
    scr: info.windowWidth + "x" + info.windowHeight, // 可使用窗口宽度/高度
    lg: info.language, // 微信设置的语言
    fl: info.version, // 微信版本号
    jv: encodeURIComponent(info.system), // 操作系统版本
    tz: encodeURIComponent(info.platform) // 客户端平台
  };
}

// 用户id,第一次运行时生成,清理小程序会重新生成
function getUID() {
  try {
    return wx.getStorageSync(MTA_CONFIG.prefix + "auid");
  } catch (e) {}
}

function setUID() {
  try {
    var uid = getRandom();
    wx.setStorageSync(MTA_CONFIG.prefix + "auid", uid);
    return uid;
  } catch (e) {}
}

// 会话id,每次重新启动小程序,会重新生成
function getSID() {
  try {
    return wx.getStorageSync(MTA_CONFIG.prefix + "ssid");
  } catch (a) {}
}

function setSID() {
  try {
    var sid = "s" + getRandom();
    wx.setStorageSync(MTA_CONFIG.prefix + "ssid", sid);
    return sid;
  } catch (e) {}
}

function getRandom(a) {
  for (var b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], c = 10, d = 0; 1 < c; c--) {
    d = Math.floor(10 * Math.random());
    var f = b[d];
    b[d] = b[c - 1];
    b[c - 1] = f;
  }
  for (c = d = 0; 5 > c; c++) d = 10 * d + b[c];
  return (a || "") + (d + "" + new Date());
}

// 获取当前页面路径地址
function getPagePath() {
  try {
    var pages = getCurrentPages(),
      root = "/";
    if (0 < pages.length) {
      root = pages.pop().__route__;
    }
    return root;
  } catch (e) {
    console.log("get current page path error:" + c);
  }
}

// 获取主要信息?每次请求都会发送
function getMainInfo() {
  var info = {
    dm: "wechat.apps.xx", // 上报类型
    url: getPagePath(), // 页面路径
    pvi: "", // 用户id
    si: "", // 会话id
    ty: 0 // 是否是新用户
  };
  info.pvi = function () {
    var uid = getUID();
    if (!uid) {
      uid = setUID();
      info.ty = 1;
    }
    return uid;
  }();
  info.si = function () {
    var sid = getSID();
    if (!sid) {
      sid = setSID();
    }
    return sid;
  }();
  return info;
}

// 获取基本信息,包含系统信息和网络类型
function getBasicInfo() {
  var info = getSystemInfo();
  getNetworkType(function (res) {
    try {
      var ntype = res.networkType;
      wx.setStorageSync(MTA_CONFIG.prefix + "ntdata", ntype);
    } catch (e) {}
  });
  info.ct = wx.getStorageSync(MTA_CONFIG.prefix + "ntdata") || "4g"; // 网络类型
  return info;
}

// 获取扩展信息,用户信息,微信,版本,appid
function getExtentInfo() {
  var user = MTA.Data.userInfo;
  var b = [],
    c;
  for (c in user) {
    if (user.hasOwnProperty(c)) {
      b.push(c + "=" + user[c]); // 分号分割的等号拼接
    }
  }
  user = b.join(";");
  return {
    r2: MTA_CONFIG.app_id,
    r4: "wx",
    ext: "v=" + MTA_CONFIG.version + (null !== user && "" !== user ? ";ui=" + encodeURIComponent(user) : "")
  };
}

var MTA = {
  // 应用启动级别的初始化
  App: {
    init: function (params) {
      "appID" in params && (MTA_CONFIG.app_id = params.appID);
      "eventID" in params && (MTA_CONFIG.event_id = params.eventID);
      "statShareApp" in params && (MTA_CONFIG.stat_share_app = params.statShareApp);
      "statPullDownFresh" in params && (MTA_CONFIG.stat_pull_down_fresh = params.statPullDownFresh);
      "statReachBottom" in params && (MTA_CONFIG.stat_reach_bottom = params.statReachBottom);
      setSID(); // 重置会话ID
      try {
        // 设置启动参数记录
        "lauchOpts" in params && (MTA.Data.lanchInfo = params.lauchOpts, MTA.Data.lanchInfo.landing = 1);
      } catch (e) {}
    }
  },
  // 页面级别的功能
  Page: {
    // 初始化
    init: function () {
      var page = getCurrentPages()[getCurrentPages().length - 1];

      // 页面显示事件
      page.onShow && !
        function () {
          var b = page.onShow;
          page.onShow = function () {
            MTA.Page.stat();
            b.call(this, arguments);
          };
        }();

      // 下拉刷新事件
      MTA_CONFIG.stat_pull_down_fresh && page.onPullDownRefresh && !
        function () {
          var b = page.onPullDownRefresh;
          page.onPullDownRefresh = function () {
            MTA.Event.stat(MTA_CONFIG.prefix + "pulldownfresh", {
              url: page.__route__
            });
            b.call(this, arguments);
          };
        }();

      // 上拉事件
      MTA_CONFIG.stat_reach_bottom && page.onReachBottom && !
        function () {
          var b = page.onReachBottom;
          page.onReachBottom = function () {
            MTA.Event.stat(MTA_CONFIG.prefix + "reachbottom", {
              url: page.__route__
            });
            b.call(this, arguments);
          };
        }();

      // 分享事件
      MTA_CONFIG.stat_share_app && page.onShareAppMessage && !
        function () {
          var b = page.onShareAppMessage;
          page.onShareAppMessage = function () {
            MTA.Event.stat(MTA_CONFIG.prefix + "shareapp", {
              url: page.__route__
            });
            return b.call(this, arguments);
          };
        }();
    },
    multiStat: function (a, b) {
      if (1 == b) {
        MTA.Page.stat(a);
      } else {
        var page = getCurrentPages()[getCurrentPages().length - 1];
        page.onShow && !
          function () {
            var b = page.onShow;
            page.onShow = function () {
              MTA.Page.stat(a);
              b.call(this, arguments);
            };
          }();
      }
    },

    // 页面数据上报
    stat: function (data) {
      if ("" == MTA_CONFIG.app_id) return;
      var dataReq = [],
        extentInfo = getExtentInfo();
      if (data) extentInfo.r2 = data; // MTA_CONFIG.app_id,
      data = [getMainInfo(), extentInfo, getBasicInfo()];

      // 启动信息参数
      if (MTA.Data.lanchInfo) {
        data.push({
          ht: MTA.Data.lanchInfo.scene, // 启动场景值
          rdm: "/",
          rurl: MTA.Data.lanchInfo.path // 启动小程序时的路径
        });

        // 有渠道id
        MTA.Data.lanchInfo.query && MTA.Data.lanchInfo.query._mta_ref_id && data.push({
          rarg: MTA.Data.lanchInfo.query._mta_ref_id // 渠道id的设计
        });

        try {
          if (MTA.Data.lanchInfo.landing) {
            extentInfo.ext += ";lp=1"; // 表示会话第一次上报? 和userinfo信息放在一起
            MTA.Data.lanchInfo.landing = 0; // 仅仅提交一次
          }
        } catch (e) {}
      }
      data.push({
        rand: +new Date()
      });
      var index = 0;
      for (var d = data.length; index < d; index++) {
        for (var key in data[index]) {
          if (data[index].hasOwnProperty(key)) {
            dataReq.push(key + "=" + ("undefined" == typeof data[index][key] ? "" : data[index][key]));
          }
        }
      }
      // 使用get方式提交数据
      wx.request({
        url: MTA_CONFIG.api_base + "?" + dataReq.join("&").toLowerCase()
      });
    }
  },
  Event: {
    stat: function (url, params) {
      if ("" != MTA_CONFIG.event_id) {
        var dataReq = [],
          mainInfo = getMainInfo(),
          extentInfo = getExtentInfo();
        mainInfo.dm = "wxapps.click"; // 点击数据上报,类型不同时,参数意义不同
        mainInfo.url = url; // 数据路径
        extentInfo.r2 = MTA_CONFIG.event_id; // 事件ID;MTA_CONFIG.app_id?

        // 封装自定义业务参数到r5
        params = "undefined" === typeof params ? {} : params;
        var k = [];
        for (var key in params) {
          if (params.hasOwnProperty(key)) {
            k.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
          }
        }
        params = k.join(";");
        extentInfo.r5 = params; // 自定义参数数据,逗号分隔等号连接

        // 准备输出数据
        var index = 0;
        var data = [mainInfo, extentInfo, getBasicInfo(), {
          rand: +new Date()
        }];
        for (len = data.length; index < len; index++) {
          for (var key2 in data[index]) {
            if (data[index].hasOwnProperty(key2)) {
              dataReq.push(key2 + "=" + ("undefined" == typeof data[index][key2] ? "" : data[index][key2]));
            }
          }
        }

        // 发起http的get请求
        wx.request({
          url: MTA_CONFIG.api_base + "?" + dataReq.join("&").toLowerCase()
        });
      }
    }
  },
  Data: {
    userInfo: null,
    lanchInfo: null
  }
};
module.exports = MTA;

转载于:https://my.oschina.net/jdragon/blog/2987537

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值