| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- /**
- * 分享工具:小程序分享(onShareAppMessage / onShareTimeline)共用逻辑。
- *
- * 邀请码(转介绍跟踪):仅登录用户有,复用 train_user.invite_code,
- * 经 /api/invite/myposter 惰性加载一次,按 userId 缓存(模块级 + storage)。
- * 未登录 / 加载失败时不带邀请码,分享仍可用。
- */
- import { getMyPoster } from '@/utils/api.js'
- import config from '@/config.js'
- let cached = { userId: '', code: '' }
- function currentUserId() {
- return uni.getStorageSync('userId') || ''
- }
- function readInviteCode() {
- var userId = currentUserId()
- if (!userId) return ''
- if (cached.userId === userId && cached.code) return cached.code
- var code = uni.getStorageSync('invite_' + userId)
- if (code) {
- cached = { userId: userId, code: code }
- }
- return cached.userId === userId ? cached.code : ''
- }
- /**
- * 预载当前用户邀请码(页面 onLoad/onShow 调用,不阻塞 UI、不弹登录框)。
- * 返回 Promise<string>:已有缓存/无登录用户时立即 resolve,供「生成海报」等
- * 需要邀请码才能继续的场景 await 后使用。
- */
- export function loadInviteCode() {
- var userId = currentUserId()
- if (!userId) return Promise.resolve('')
- var existing = readInviteCode()
- if (existing) return Promise.resolve(existing)
- return getMyPoster().then(function(resp) {
- var data = resp.data || {}
- var code = data.inviteCode || ''
- if (code) {
- cached = { userId: userId, code: code }
- uni.setStorageSync('invite_' + userId, code)
- }
- return code
- }).catch(function() {
- // 静默失败:分享路径不带邀请码
- return ''
- })
- }
- /** 同步读取已缓存的邀请码(onShareAppMessage / onShareTimeline 回调内使用) */
- export function getInviteCode() {
- return readInviteCode()
- }
- /** 拼分享路径:path(如 /pages/course/detail?courseId=1)末尾追加 inviteCode 参数 */
- export function buildSharePath(path) {
- var code = readInviteCode()
- if (!code) return path
- return path + (path.indexOf('?') > -1 ? '&' : '?') + 'inviteCode=' + code
- }
- /**
- * 后端返回的 /uploads/xxx 资源路径转绝对地址。
- * 小程序端 <image> / uni.getImageInfo 不能使用 / 开头的相对路径(会被当作包内本地文件),
- * H5 端 BASE_URL 为空时保持相对路径(由 nginx 同域提供)。
- */
- export function resolveAssetUrl(path) {
- if (!path) return ''
- if (path.indexOf('http://') === 0 || path.indexOf('https://') === 0) return path
- if (path.charAt(0) === '/') return config.api(path)
- return path
- }
|