/*** 初始化微信 JS-SDK* @see https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html*/ import { getWxSignature } from '@/services/index'; //获取签名的接口,服务端提供export const APPID = 'xxxx'; 微信小程序的appid/*** 获取随机字符串* @param length - 随机字符串长度,默认为 32*/ export function getRandomStr (length = 32): string {const tmp = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';let str = '';for (let i = 0; i < length; i += 1) {str += tmp.charAt(Math.floor(Math.random() * tmp.length));}return str; }async function getWxConfig (jsApiList: string[] = ['openLocation']) {const nonceStr = getRandomStr(6);const timestamp = Math.floor(new Date().getTime() / 1000);const res = await getWxSignature({appId: APPID,type: 'jsapi',paramMap: JSON.stringify({noncestr: nonceStr,timestamp: Math.floor(new Date().getTime() / 1000),url: location.href,}),});const { model = '' } = res || {}; //获取到的签名return {appId: APPID,debug: false,jsApiList,timestamp,nonceStr,signature: model,}; }/** @see https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html */ export async function initWxJsSdk () {
const isWeixin = /MicroMessenger/i.test(navigator.userAgent);
if (!isWeixin) return;const configData = await getWxConfig();return new Promise((resolve, reject) => {const handleWxReady = () => {window.wx?.config(configData);window.wx?.ready(resolve);window.wx?.error(reject);};if (!window.WeixinJSBridge || !window.WeixinJSBridge.invoke) {document.addEventListener('WeixinJSBridgeReady', handleWxReady, false);} else {handleWxReady();}}); }