App.vue 9.9 KB

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