Files
Mycontent/miniprogram/utils/trackClick.js
2026-04-28 18:39:08 +08:00

72 lines
2.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const app = getApp()
const GUEST_TRACK_STORAGE_KEY = 'guest_track_id_v1'
/**
* 未登录访客设备标识:持久化,用于埋点区分「人」——避免全部为 anonymous 导致后台只统计到 1 人
*/
function getGuestTrackId() {
try {
let id = wx.getStorageSync(GUEST_TRACK_STORAGE_KEY)
id = typeof id === 'string' ? id.trim() : ''
if (id.length >= 12) return id
id = 'gt_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 14)
wx.setStorageSync(GUEST_TRACK_STORAGE_KEY, id)
return id
} catch (_) {
return 'gt_fallback_local'
}
}
function sendMiniprogramTrack(data) {
return app.request('/api/miniprogram/track', {
method: 'POST',
data,
silent: true
})
}
/**
* 全局按钮/标签点击埋点(未登录也上报,携带 guestId
* @param {string} module 模块home|chapters|read|my|vip|wallet|match|referral|search|settings|about
* @param {string} action 行为tab_click|btn_click|nav_click|card_click|link_click 等
* @param {string} target 目标标识按钮文案、章节ID、标签名等
* @param {object} [extra] 附加数据
*/
function trackClick(module, action, target, extra) {
const userId = app.globalData.userInfo?.id || ''
const payload = {
action,
target,
extraData: Object.assign({ module, page: module }, extra || {})
}
if (userId) {
payload.userId = userId
} else {
payload.guestId = getGuestTrackId()
}
sendMiniprogramTrack(payload).catch(() => {})
}
/**
* 章节 PV写入 user_tracks.action=view_chapter未登录携带 guestId
*/
function trackViewChapter(sectionId, extra) {
const id = String(sectionId || '').trim()
if (!id) return
const userId = app.globalData.userInfo?.id || ''
const payload = {
action: 'view_chapter',
target: id,
extraData: Object.assign({ page: 'read', module: 'read' }, extra || {})
}
if (userId) {
payload.userId = userId
} else {
payload.guestId = getGuestTrackId()
}
sendMiniprogramTrack(payload).catch(() => {})
}
module.exports = { trackClick, trackViewChapter, getGuestTrackId }