Files
code-bang/frontend/miniapp/utils/promoter.js
T
2026-10-14 14:44:01 +08:00

76 lines
2.3 KiB
JavaScript

import { bindPromoter } from '../services/promoter/fetchPromoter';
// 待绑定的推广人ID(登录前进入时先缓存,登录/绑定成功后清除)
const PENDING_KEY = 'pendingPromoterId';
// 分享链接参数:/pages/xxx?promoter_id=1,同时作为登录/绑定接口的参数名
export const QUERY_KEY = 'promoter_id';
// 小程序码 scene 参数:scene=pid%3D1,与后端 PromotionService::QRCODE_SCENE_KEY 一致
const SCENE_KEY = 'pid';
/** 当前登录用户ID */
export function getCurrentUserId() {
return Number((wx.getStorageSync('userInfo') || {}).id) || 0;
}
/** 从页面启动参数中解析推广人ID */
export function parsePromoterId(query = {}) {
if (query[QUERY_KEY]) {
return Number(query[QUERY_KEY]) || 0;
}
if (query.scene) {
const pair = decodeURIComponent(query.scene)
.split('&')
.map((item) => item.split('='))
.find(([key]) => key === SCENE_KEY);
return pair ? Number(pair[1]) || 0 : 0;
}
return 0;
}
/** 启动参数中带推广人时缓存,等待登录后绑定 */
export function savePendingPromoter(query) {
const promoterId = parsePromoterId(query || {});
if (promoterId && promoterId !== getCurrentUserId()) {
wx.setStorageSync(PENDING_KEY, promoterId);
}
}
export function getPendingPromoter() {
return Number(wx.getStorageSync(PENDING_KEY)) || 0;
}
export function clearPendingPromoter() {
wx.removeStorageSync(PENDING_KEY);
}
/** 已登录状态下绑定缓存的推广人(热启动从分享进入时使用) */
export async function bindPendingPromoter() {
const promoterId = getPendingPromoter();
if (!promoterId || !wx.getStorageSync('token')) {
return;
}
try {
const res = await bindPromoter({ [QUERY_KEY]: promoterId });
if (res.code === 1) {
clearPendingPromoter();
}
} catch (err) {
console.error('bindPromoter failed:', err);
}
}
/** 分享参数:promoter_id=当前用户ID,未登录时为空 */
export function promoterQuery() {
const userId = getCurrentUserId();
return userId ? `${QUERY_KEY}=${userId}` : '';
}
/** 给分享路径追加推广人参数 */
export function withPromoter(path) {
const query = promoterQuery();
if (!query) {
return path;
}
return `${path}${path.indexOf('?') > -1 ? '&' : '?'}${query}`;
}