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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
| // utils/analytics.js
const analytics = {
// 页面访问统计
trackPageView(pageName, properties = {}) {
const data = {
event: 'page_view',
page: pageName,
timestamp: Date.now(),
properties: {
...properties,
userId: wx.getStorageSync('userId'),
sessionId: this.getSessionId()
}
}
this.report(data)
},
// 自定义事件追踪
trackEvent(eventName, properties = {}) {
const data = {
event: eventName,
timestamp: Date.now(),
properties: {
...properties,
userId: wx.getStorageSync('userId'),
sessionId: this.getSessionId()
}
}
this.report(data)
},
// 获取会话ID
getSessionId() {
let sessionId = wx.getStorageSync('sessionId')
if (!sessionId) {
sessionId = Date.now().toString(36) + Math.random().toString(36).substr(2)
wx.setStorageSync('sessionId', sessionId)
}
return sessionId
},
// 数据上报
report(data) {
// 批量上报
const events = wx.getStorageSync('pendingEvents') || []
events.push(data)
// 限制缓存大小
if (events.length > 50) {
events.shift()
}
wx.setStorageSync('pendingEvents', events)
// 立即上报或延迟上报
if (data.event === 'page_view') {
this.flushEvents()
} else {
this.scheduleFlush()
}
},
// 立即上报
async flushEvents() {
const events = wx.getStorageSync('pendingEvents') || []
if (events.length === 0) return
try {
await wx.request({
url: '/api/analytics/events',
method: 'POST',
data: { events }
})
wx.removeStorageSync('pendingEvents')
} catch (error) {
console.error('数据上报失败:', error)
}
},
// 定时上报
scheduleFlush() {
if (this.flushTimer) return
this.flushTimer = setTimeout(() => {
this.flushEvents()
this.flushTimer = null
}, 5000)
}
}
// 页面中使用
// pages/index/index.js
Page({
onLoad() {
analytics.trackPageView('index')
},
onButtonClick() {
analytics.trackEvent('button_click', {
buttonId: 'main_button',
location: 'homepage'
})
}
})
|