Files
device-voice-h5/utils/wxsdk.js
sexygoat 39773341bd
All checks were successful
构建并部署前端到生产环境 / build-and-deploy (push) Successful in 46s
fix: 修复扫一扫登录
2026-04-17 10:56:46 +08:00

96 lines
2.6 KiB
JavaScript

import { wechatApi } from '@/api/index.js';
// 动态加载微信 JSSDK
const loadWxJSSDK = () => {
return new Promise((resolve, reject) => {
// 如果已经加载,直接返回
if (window.wx && typeof window.wx.config === 'function') {
console.log('微信JSSDK已存在');
resolve();
return;
}
// 检查是否已经有 script 标签在加载
const existingScript = document.querySelector('script[src*="jweixin"]');
if (existingScript) {
console.log('检测到JSSDK脚本标签,等待加载完成...');
// 等待已有的脚本加载完成
let count = 0;
const maxCount = 50;
const timer = setInterval(() => {
count++;
if (window.wx && typeof window.wx.config === 'function') {
clearInterval(timer);
console.log('微信JSSDK加载成功');
resolve();
} else if (count >= maxCount) {
clearInterval(timer);
reject(new Error('微信JSSDK加载超时'));
}
}, 100);
return;
}
console.log('开始动态加载微信JSSDK...');
// 动态创建 script 标签
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
script.onload = () => {
console.log('微信JSSDK脚本加载完成');
if (window.wx && typeof window.wx.config === 'function') {
resolve();
} else {
reject(new Error('微信JSSDK脚本加载失败'));
}
};
script.onerror = () => {
console.error('微信JSSDK脚本加载失败');
reject(new Error('微信JSSDK脚本加载失败,请检查网络'));
};
document.head.appendChild(script);
});
};
export const initWxSdk = async () => {
// #ifdef H5
try {
// 动态加载微信 JSSDK
await loadWxJSSDK();
const currentUrl = window.location.href.split('#')[0];
console.log('JSSDK URL:', currentUrl);
const data = await wechatApi.getJssdkConfig(currentUrl);
console.log('JSSDK Config:', data);
window.wx.config({
debug: true,
appId: data.app_id,
timestamp: data.timestamp,
nonceStr: data.nonce_str,
signature: data.signature,
jsApiList: ['scanQRCode']
});
return new Promise((resolve) => {
window.wx.ready(() => {
console.log('微信SDK配置成功');
resolve({ success: true });
});
window.wx.error((err) => {
console.error('wx.config error:', err);
resolve({ success: false, error: err.errMsg || '微信配置失败' });
});
});
} catch (e) {
console.error('WX SDK init failed', e);
return { success: false, error: e.message || '微信JSSDK未加载,请在微信中打开' };
}
// #endif
// #ifndef H5
return { success: false, error: '请在H5环境中使用' };
// #endif
};