初始化微信JSAPI
/** * 初始化微信 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(); } }); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?