share.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * 分享工具:小程序分享(onShareAppMessage / onShareTimeline)共用逻辑。
  3. *
  4. * 邀请码(转介绍跟踪):仅登录用户有,复用 train_user.invite_code,
  5. * 经 /api/invite/myposter 惰性加载一次,按 userId 缓存(模块级 + storage)。
  6. * 未登录 / 加载失败时不带邀请码,分享仍可用。
  7. */
  8. import { getMyPoster } from '@/utils/api.js'
  9. let cached = { userId: '', code: '' }
  10. function currentUserId() {
  11. return uni.getStorageSync('userId') || ''
  12. }
  13. function readInviteCode() {
  14. var userId = currentUserId()
  15. if (!userId) return ''
  16. if (cached.userId === userId && cached.code) return cached.code
  17. var code = uni.getStorageSync('invite_' + userId)
  18. if (code) {
  19. cached = { userId: userId, code: code }
  20. }
  21. return cached.userId === userId ? cached.code : ''
  22. }
  23. /** 后台预载当前用户邀请码(页面 onLoad/onShow 调用,不阻塞 UI、不弹登录框) */
  24. export function loadInviteCode() {
  25. var userId = currentUserId()
  26. if (!userId || readInviteCode()) return
  27. getMyPoster().then(function(resp) {
  28. var data = resp.data || {}
  29. var code = data.inviteCode || ''
  30. if (code) {
  31. cached = { userId: userId, code: code }
  32. uni.setStorageSync('invite_' + userId, code)
  33. }
  34. }).catch(function() {
  35. // 静默失败:分享路径不带邀请码
  36. })
  37. }
  38. /** 同步读取已缓存的邀请码(onShareAppMessage / onShareTimeline 回调内使用) */
  39. export function getInviteCode() {
  40. return readInviteCode()
  41. }
  42. /** 拼分享路径:path(如 /pages/course/detail?courseId=1)末尾追加 inviteCode 参数 */
  43. export function buildSharePath(path) {
  44. var code = readInviteCode()
  45. if (!code) return path
  46. return path + (path.indexOf('?') > -1 ? '&' : '?') + 'inviteCode=' + code
  47. }