App.vue 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. <script>
  2. import config from '@/config.js'
  3. import Vue from 'vue'
  4. import { checkUserFamily, verifyToken, bindReferral } from './utils/api.js'
  5. Vue.prototype.$config = config
  6. export default {
  7. onLaunch: function(options) {
  8. console.log('App Launch', options)
  9. // 捕获分享/邀请参数(普通分享链接 ?inviteCode=xxx):未登录写入 storage 供注册登录后绑定推荐人,已登录直接绑定
  10. this.captureReferralParams(options)
  11. // 分享/深链冷启动(携带分享参数)放行到落地页,不套 splash,避免分享的文章/小程序页面打不开
  12. // inviteCode=推荐码(文章/活动/商品分享)| refCode=推广码 | token/familyInviteCode=家庭邀请令牌 | id=内容详情
  13. var hasDeepLink = options && options.query && (
  14. options.query.inviteCode || options.query.refCode || options.query.token ||
  15. options.query.familyInviteCode || options.query.id
  16. )
  17. // 冷启动:跳转到 splash 页展示过渡动画,2秒后自动进入首页
  18. if (options.scene !== 1047 && options.scene !== 1048 && options.scene !== 1049 && !hasDeepLink) {
  19. uni.setStorageSync('_isFirstLaunch', '1')
  20. uni.redirectTo({ url: '/pages/splash/index' })
  21. return
  22. }
  23. // 处理小程序码场景值(从 wxacode 扫码进入,跳过 splash)
  24. this.handleScene(options)
  25. // TabBar 始终显示 5 个底签,不因登录状态隐藏
  26. const token = uni.getStorageSync('token')
  27. if (token) {
  28. this.$store.commit('setToken', token)
  29. // 启动时校验 token 是否仍有效:过期则清理本地登录态并引导重新登录
  30. this.verifyStoredToken()
  31. // 冷启动恢复 familyId(登录时已持久化,hasFamily getter 依赖)
  32. var storedFamilyId = uni.getStorageSync('familyId')
  33. if (storedFamilyId) {
  34. this.$store.commit('setFamilyId', storedFamilyId)
  35. } else {
  36. // 历史用户(8ddc5b55 后未重新登录):本地无 familyId,从接口恢复
  37. this.restoreFamilyIdFromApi()
  38. }
  39. } else {
  40. // 无token时尝试自动登录
  41. this.tryAutoLogin()
  42. }
  43. },
  44. onShow: function(options) {
  45. console.log('App Show', options)
  46. // 热启动(含从分享卡重新进入):同样捕获分享参数
  47. this.captureReferralParams(options)
  48. // 每次 app 展示时也检查场景值(小程序码可能从冷启动后的 onShow 传入)
  49. this.handleScene(options)
  50. // 同步 storage → Vuex(防止 reLaunch/navigateTo 后 Vuex 未更新的问题)
  51. var token = uni.getStorageSync('token')
  52. if (token && token !== this.$store.state.token) {
  53. this.$store.commit('setToken', token)
  54. this.$store.commit('setFamilyId', uni.getStorageSync('familyId'))
  55. }
  56. },
  57. onHide: function() {
  58. console.log('App Hide')
  59. },
  60. methods: {
  61. // 捕获分享/邀请参数:普通分享链接 /pages/xxx?inviteCode=yyy 冷/热启动进入时,
  62. // 新用户(未登录)写入 storage,登录注册后由 login / user-edit 消费绑定推荐人;
  63. // 已登录用户直接绑定(boundInviteCode 防重,避免重复请求)
  64. captureReferralParams(options) {
  65. if (!options || !options.query) return
  66. var code = options.query.inviteCode
  67. if (!code) return
  68. if (uni.getStorageSync('token')) {
  69. var bound = uni.getStorageSync('boundInviteCode')
  70. if (bound === code) return
  71. bindReferral(code).then(function(res) {
  72. if (res && res.code === 200) {
  73. uni.setStorageSync('boundInviteCode', code)
  74. console.log('分享参数推荐人绑定成功', code)
  75. }
  76. }).catch(function(e) {
  77. // 后端已绑定(code=500 message=已绑定推荐人)→ 记录防重,避免每次冷/热启动重复请求/重复提示
  78. if (e && e.code !== undefined && e.code !== 401) {
  79. uni.setStorageSync('boundInviteCode', code)
  80. console.log('分享参数推荐人绑定失败(业务拒绝,已防重)', code, e.message || '')
  81. } else {
  82. console.log('分享参数推荐人绑定失败(网络/登录态)', e)
  83. }
  84. })
  85. return
  86. }
  87. uni.setStorageSync('inviteCode', code)
  88. if (options.query.inviteType) {
  89. uni.setStorageSync('inviteType', options.query.inviteType)
  90. }
  91. },
  92. // 校验本地 token 是否有效(开发环境跳过,避免无后端时误报)
  93. verifyStoredToken() {
  94. try {
  95. var envInfo = uni.getAccountInfoSync()
  96. if (envInfo && envInfo.miniProgram && envInfo.miniProgram.envVersion === 'develop') {
  97. return
  98. }
  99. } catch (e) { /* 非小程序环境 */ }
  100. var self = this
  101. verifyToken().then(function() {
  102. // token 有效,无需处理
  103. }).catch(function(e) {
  104. // 401 已由 request 封装触发 _clearAuthAndRedirect(清理 + 跳登录);
  105. // 其它错误(如网络失败)静默忽略,不打扰用户
  106. console.log('[App] token 校验未通过:', e && e.code)
  107. })
  108. },
  109. // 从接口恢复 familyId(历史用户冷启动,本地无 familyId 缓存)
  110. restoreFamilyIdFromApi() {
  111. var self = this
  112. checkUserFamily().then(function(res) {
  113. if (res && res.data && res.data.inFamily && res.data.familyId) {
  114. self.$store.commit('setFamilyId', res.data.familyId)
  115. console.log('[App] familyId 已从接口恢复:', res.data.familyId)
  116. }
  117. }).catch(function(e) {
  118. console.log('[App] familyId 接口恢复失败(页面按无家庭态渲染)', e)
  119. })
  120. },
  121. async tryAutoLogin() {
  122. // 开发环境下跳过自动登录,避免无后端时 10s 超时阻塞
  123. try {
  124. var envInfo = uni.getAccountInfoSync()
  125. if (envInfo && envInfo.miniProgram && envInfo.miniProgram.envVersion === 'develop') {
  126. return
  127. }
  128. } catch (e) { /* 非小程序环境 */ }
  129. try {
  130. // 1. 先尝试用缓存的openid自动登录
  131. const cachedOpenid = uni.getStorageSync('openid')
  132. if (cachedOpenid) {
  133. const res = await this.request('/api/auth/auto-login', 'POST', { openid: cachedOpenid })
  134. if (res && res.data) {
  135. this.saveLoginInfo(res.data)
  136. console.log('openid自动登录成功')
  137. // 刷新页面到登录态
  138. uni.switchTab({ url: '/pages/index-home/index' })
  139. return
  140. }
  141. }
  142. // 2. openid自动登录失败,不自动调用uni.login(避免DevTools环境超时阻塞渲染层)
  143. // 用户会看到登录页,手动选择登录方式
  144. } catch (e) {
  145. console.log('自动登录失败,需要手动登录', e)
  146. }
  147. },
  148. saveLoginInfo(data) {
  149. uni.setStorageSync('token', data.token)
  150. uni.setStorageSync('userId', data.userId)
  151. uni.setStorageSync('role', data.role)
  152. // 自动登录后重置到真实登录角色,避免残留切换状态
  153. uni.setStorageSync('currentRole', data.role)
  154. uni.setStorageSync('isSwitchedChild', false)
  155. uni.setStorageSync('isSwitchedTeacher', false)
  156. if (data.openid) {
  157. uni.setStorageSync('openid', data.openid)
  158. }
  159. // familyId 必须持久化:家庭在注册时已由后端创建,缺失会导致页面误判无家庭而重复创建
  160. uni.setStorageSync('userInfo', {
  161. nickname: data.nickname,
  162. userId: data.userId,
  163. familyId: data.familyId
  164. })
  165. this.$store.commit('setToken', data.token)
  166. // 同步 familyId 到 store(hasFamily getter 依赖;auto-login 路径)
  167. this.$store.commit('setFamilyId', data.familyId)
  168. },
  169. request(url, method, data) {
  170. return new Promise((resolve, reject) => {
  171. uni.request({
  172. url: config.api(url),
  173. method: method,
  174. data: data,
  175. timeout: 10000,
  176. header: { 'Content-Type': 'application/json' },
  177. success: (res) => {
  178. if (res.data.code === 200) {
  179. resolve(res.data)
  180. } else {
  181. reject(res.data)
  182. }
  183. },
  184. fail: reject
  185. })
  186. })
  187. },
  188. // 处理小程序码场景值,跳转到邀请页
  189. handleScene(options) {
  190. if (!options || !options.query) return
  191. var scene = options.query.scene
  192. if (!scene) return
  193. var sceneDecoded = decodeURIComponent(scene)
  194. if (sceneDecoded.indexOf('invite=') === 0) {
  195. var token = sceneDecoded.substring(7)
  196. uni.navigateTo({
  197. url: '/pages/invite/join?token=' + token
  198. })
  199. } else if (sceneDecoded.indexOf('ref=') === 0) {
  200. var refCode = sceneDecoded.substring(4)
  201. if (!refCode) {
  202. console.warn('推广码场景缺少 refCode', sceneDecoded)
  203. return
  204. }
  205. uni.navigateTo({
  206. url: '/pages/invite/join?refCode=' + encodeURIComponent(refCode)
  207. })
  208. }
  209. }
  210. }
  211. }
  212. </script>
  213. <style>
  214. @import url('./common/uni.css');
  215. page {
  216. background-color: var(--bg, #F5F9FC);
  217. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI',
  218. 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
  219. 'Helvetica Neue', Helvetica, Arial, sans-serif;
  220. color: var(--text, #1E293B);
  221. font-size: 28rpx;
  222. line-height: 1.6;
  223. -webkit-font-smoothing: antialiased;
  224. }
  225. /* 页面容器 */
  226. .page {
  227. padding: 0 32rpx 32rpx;
  228. min-height: 100vh;
  229. }
  230. .page--no-padding {
  231. padding: 0;
  232. }
  233. /* 分段标题 */
  234. .section-header {
  235. font-weight: 700;
  236. font-size: 32rpx;
  237. margin: 32rpx 0 16rpx;
  238. color: var(--text, #1E293B);
  239. display: flex;
  240. align-items: center;
  241. justify-content: space-between;
  242. border-left: 8rpx solid #F08A7A;
  243. padding-left: 20rpx;
  244. }
  245. .section-header__more {
  246. font-size: 24rpx;
  247. color: var(--muted, #94A3B8);
  248. font-weight: 400;
  249. }
  250. /* 安全区底部 */
  251. .safe-area-bottom {
  252. padding-bottom: calc(constant(safe-area-inset-bottom) + 20rpx);
  253. padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  254. }
  255. </style>