Files
consumer-front/src/utils/env.js
T

85 lines
1.7 KiB
JavaScript

/**
* 环境检测工具
* 检测当前运行平台(微信/支付宝/普通浏览器),映射到对应的 app_no
*/
// app_no 编码表:platform + terminalType → app_no
const APP_NO_MAP = {
'wechat_h5': '60000001102001',
'wechat_mp': '600102101',
'alipay_h5': '600112001',
'alipay_mp': '600112101',
};
/**
* 检测当前运行环境
* @returns {'wechat' | 'alipay' | 'browser'}
*/
export function detectPlatform() {
// #ifdef H5
const ua = navigator.userAgent;
if (/MicroMessenger/i.test(ua)) {
return 'wechat';
}
if (/AlipayClient/i.test(ua)) {
return 'alipay';
}
// #endif
// #ifdef MP-WEIXIN
return 'wechat';
// #endif
// #ifdef MP-ALIPAY
return 'alipay';
// #endif
return 'browser';
}
/**
* 检测当前终端类型
* @returns {'h5' | 'mp'}
*/
export function detectTerminalType() {
// #ifdef H5
return 'h5';
// #endif
// #ifdef MP-WEIXIN || MP-ALIPAY
return 'mp';
// #endif
return 'h5';
}
/**
* 根据平台和终端类型获取 app_no
* @param {string} platform - 'wechat' | 'alipay' | 'browser'
* @param {string} terminalType - 'h5' | 'mp'
* @returns {string} app_no
*/
export function getAppNo(platform, terminalType = 'h5') {
if (platform === 'browser') return '';
return APP_NO_MAP[`${platform}_${terminalType}`] || '';
}
/**
* 初始化环境检测并缓存到 storage
* 应在 App.vue onLaunch 中调用
*/
export function initEnv() {
const platform = detectPlatform();
const terminalType = detectTerminalType();
const appNo = getAppNo(platform, terminalType);
uni.setStorageSync('platform', platform);
uni.setStorageSync('terminal_type', terminalType);
if (appNo) {
uni.setStorageSync('app_no', appNo);
}
return { platform, terminalType, appNo };
}