/** * 支付环境检测:PC / H5 / 微信浏览器 * 用于 ZPAY 等聚合支付,需区分环境以选择正确的支付通道 * 参考:https://juejin.cn/post/7122720360683798542 */ export type PayEnv = "pc" | "h5" | "wechat"; export type PayChannel = "alipay" | "wxpay"; /** 是否在微信内置浏览器 */ export function isWeChat(): boolean { if (typeof navigator === "undefined") return false; return /MicroMessenger/i.test(navigator.userAgent); } /** 是否在支付宝内置浏览器 */ export function isAlipay(): boolean { if (typeof navigator === "undefined") return false; return /AlipayClient|Alipay/i.test(navigator.userAgent); } /** 是否移动设备(含平板) */ export function isMobile(): boolean { if (typeof navigator === "undefined") return false; return /AppleWebKit.*Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ); } /** 当前支付环境 */ export function getPayEnv(): PayEnv { if (isWeChat()) return "wechat"; if (isMobile()) return "h5"; return "pc"; } /** * 根据环境推荐/强制支付通道 * - 微信浏览器:只能用 wxpay(支付宝在微信内无法唤起) * - 支付宝浏览器:优先 alipay * - PC/H5:用户可选 */ export function getRecommendedChannel(env: PayEnv): PayChannel { if (env === "wechat") return "wxpay"; if (env === "pc" || env === "h5") return "alipay"; // 默认支付宝 return "alipay"; } /** 微信内是否只能选微信支付 */ export function mustUseWxPay(env: PayEnv): boolean { return env === "wechat"; }