716 lines
23 KiB
JavaScript
716 lines
23 KiB
JavaScript
/**
|
|
* 微信JS-SDK工具类
|
|
* 基于官方文档:https://developers.weixin.qq.com/doc/service/guide/h5/jssdk.html
|
|
* 支持:分享、扫码、支付、地理位置、图片选择等常用功能
|
|
* 优化:双CDN备份机制,精简版 (2025-01-03)
|
|
*/
|
|
|
|
import { request } from '@/common/request.js';
|
|
|
|
class WeChatSDK {
|
|
constructor() {
|
|
this.isInitialized = false;
|
|
this.configInfo = null;
|
|
this.debug = process.env.NODE_ENV === 'development';
|
|
|
|
// 常用API列表
|
|
this.jsApiList = [
|
|
// 基础接口
|
|
'checkJsApi',
|
|
'updateAppMessageShareData',
|
|
'updateTimelineShareData',
|
|
'onMenuShareTimeline',
|
|
'onMenuShareAppMessage',
|
|
'onMenuShareQQ',
|
|
'onMenuShareWeibo',
|
|
'onMenuShareQZone',
|
|
|
|
// 图像接口
|
|
'chooseImage',
|
|
'previewImage',
|
|
'uploadImage',
|
|
'downloadImage',
|
|
|
|
// 音频接口
|
|
'startRecord',
|
|
'stopRecord',
|
|
'onVoiceRecordEnd',
|
|
'playVoice',
|
|
'pauseVoice',
|
|
'stopVoice',
|
|
'onVoicePlayEnd',
|
|
'uploadVoice',
|
|
'downloadVoice',
|
|
|
|
// 智能接口
|
|
'translateVoice',
|
|
|
|
// 设备信息
|
|
'getNetworkType',
|
|
'openLocation',
|
|
'getLocation',
|
|
|
|
// 界面操作
|
|
'closeWindow',
|
|
'hideMenuItems',
|
|
'showMenuItems',
|
|
'hideAllNonBaseMenuItem',
|
|
'showAllNonBaseMenuItem',
|
|
|
|
// 微信扫一扫
|
|
'scanQRCode',
|
|
|
|
// 微信支付
|
|
'chooseWXPay',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 等待wx对象就绪 - 简化版
|
|
* @param {Number} timeout 超时时间(毫秒)
|
|
* @returns {Promise}
|
|
*/
|
|
waitForWx(timeout = 10000) {
|
|
return new Promise((resolve, reject) => {
|
|
const isWxReady = () => {
|
|
return (
|
|
typeof wx !== 'undefined' &&
|
|
wx.config &&
|
|
typeof wx.config === 'function' &&
|
|
wx.ready &&
|
|
typeof wx.ready === 'function'
|
|
);
|
|
};
|
|
|
|
if (isWxReady()) {
|
|
console.log('✅ wx对象已就绪');
|
|
resolve(true);
|
|
return;
|
|
}
|
|
|
|
console.log('⏳ 等待wx对象就绪...');
|
|
let startTime = Date.now();
|
|
|
|
const checkInterval = setInterval(() => {
|
|
const elapsed = Date.now() - startTime;
|
|
|
|
if (isWxReady()) {
|
|
clearInterval(checkInterval);
|
|
console.log(`✅ wx对象已就绪 (耗时: ${Math.floor(elapsed / 1000)}s)`);
|
|
resolve(true);
|
|
} else if (elapsed > timeout) {
|
|
clearInterval(checkInterval);
|
|
reject(new Error(`等待wx对象超时 (${timeout / 1000}s)`));
|
|
}
|
|
}, 200);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 初始化微信JS-SDK配置 - 简化版
|
|
* @param {Object} options 配置选项
|
|
* @returns {Promise}
|
|
*/
|
|
async init(options = {}) {
|
|
try {
|
|
console.log('🔧 开始初始化微信JS-SDK...');
|
|
|
|
// 检查微信环境
|
|
if (!this.isWeChatBrowser()) {
|
|
const error = new Error('当前不在微信浏览器环境中');
|
|
console.warn('⚠️ ' + error.message);
|
|
return Promise.reject(error);
|
|
}
|
|
|
|
// 确保SDK已加载
|
|
try {
|
|
await this.waitForWx();
|
|
console.log('✅ 使用预加载的微信JS-SDK脚本');
|
|
} catch (waitError) {
|
|
console.log('⚠️ 预加载脚本未就绪,尝试动态加载...');
|
|
await WeChatSDK.loadWeChatSDK();
|
|
await this.waitForWx(5000);
|
|
}
|
|
|
|
// 获取当前页面URL
|
|
const currentUrl = options.url || this.getCurrentUrl();
|
|
console.log('📍 当前页面URL:', currentUrl);
|
|
|
|
// 获取微信配置
|
|
const configData = await this.getWeChatConfig(currentUrl);
|
|
this.configInfo = configData;
|
|
|
|
// 配置参数
|
|
const configOptions = {
|
|
debug: options.debug !== undefined ? options.debug : this.debug,
|
|
appId: configData.appId,
|
|
timestamp: configData.timestamp,
|
|
nonceStr: configData.nonceStr,
|
|
signature: configData.signature,
|
|
jsApiList: options.jsApiList || this.jsApiList,
|
|
};
|
|
|
|
console.log('⚙️ 微信配置参数:', {
|
|
...configOptions,
|
|
signature: configData.signature.substring(0, 10) + '...',
|
|
});
|
|
|
|
// 返回Promise
|
|
return new Promise((resolve, reject) => {
|
|
wx.config(configOptions);
|
|
|
|
wx.ready(() => {
|
|
console.log('✅ 微信JS-SDK初始化成功');
|
|
this.isInitialized = true;
|
|
resolve(configData);
|
|
});
|
|
|
|
wx.error((res) => {
|
|
console.error('❌ 微信JS-SDK初始化失败:', res);
|
|
this.isInitialized = false;
|
|
let errorMsg = '微信JS-SDK初始化失败';
|
|
if (res.errMsg) {
|
|
errorMsg += ': ' + res.errMsg;
|
|
if (res.errMsg.includes('invalid signature')) {
|
|
errorMsg += '(签名无效,请检查域名配置)';
|
|
} else if (res.errMsg.includes('invalid url domain')) {
|
|
errorMsg += '(域名未在微信公众平台配置)';
|
|
}
|
|
}
|
|
reject(new Error(errorMsg));
|
|
});
|
|
});
|
|
} catch (error) {
|
|
console.error('❌ 初始化微信JS-SDK异常:', error);
|
|
return Promise.reject(error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 检查是否在微信浏览器中
|
|
* @returns {Boolean}
|
|
*/
|
|
isWeChatBrowser() {
|
|
const ua = navigator.userAgent.toLowerCase();
|
|
return ua.includes('micromessenger');
|
|
}
|
|
|
|
/**
|
|
* 获取当前页面URL(去除hash部分)
|
|
* @returns {String}
|
|
*/
|
|
getCurrentUrl() {
|
|
const url = location.href.split('#')[0];
|
|
return encodeURIComponent(url);
|
|
}
|
|
|
|
/**
|
|
* 获取微信配置信息
|
|
* @param {String} url 页面URL
|
|
* @returns {Promise}
|
|
*/
|
|
async getWeChatConfig(url) {
|
|
try {
|
|
console.log('🔄 获取微信配置信息...');
|
|
|
|
const response = await request({
|
|
url: '/system/wechat/config',
|
|
method: 'POST',
|
|
data: { url: decodeURIComponent(url) },
|
|
});
|
|
|
|
if (response.code === 200) {
|
|
console.log('✅ 获取微信配置成功');
|
|
return response.data;
|
|
} else {
|
|
throw new Error(response.msg || '获取微信配置失败');
|
|
}
|
|
} catch (error) {
|
|
console.error('❌ 获取微信配置失败:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 检查当前客户端版本是否支持指定JS接口
|
|
* @param {Array} jsApiList 需要检查的接口列表
|
|
* @returns {Promise}
|
|
*/
|
|
checkJsApi(jsApiList) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.checkJsApi({
|
|
jsApiList: jsApiList,
|
|
success: (res) => {
|
|
console.log('✅ 接口支持检查结果:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 接口支持检查失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 分享到朋友圈
|
|
* @param {Object} shareData 分享数据
|
|
* @param {String} shareData.title 分享标题
|
|
* @param {String} shareData.link 分享链接
|
|
* @param {String} shareData.imgUrl 分享图标
|
|
* @returns {Promise}
|
|
*/
|
|
shareTimeline(shareData) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.updateTimelineShareData({
|
|
title: shareData.title,
|
|
link: shareData.link,
|
|
imgUrl: shareData.imgUrl,
|
|
success: (res) => {
|
|
console.log('✅ 朋友圈分享配置成功:', res);
|
|
resolve(res);
|
|
},
|
|
cancel: (res) => {
|
|
console.log('👤 用户取消分享:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 朋友圈分享配置失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 分享给朋友
|
|
* @param {Object} shareData 分享数据
|
|
* @param {String} shareData.title 分享标题
|
|
* @param {String} shareData.desc 分享描述
|
|
* @param {String} shareData.link 分享链接
|
|
* @param {String} shareData.imgUrl 分享图标
|
|
* @returns {Promise}
|
|
*/
|
|
shareAppMessage(shareData) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.updateAppMessageShareData({
|
|
title: shareData.title,
|
|
desc: shareData.desc,
|
|
link: shareData.link,
|
|
imgUrl: shareData.imgUrl,
|
|
success: (res) => {
|
|
console.log('✅ 朋友分享配置成功:', res);
|
|
resolve(res);
|
|
},
|
|
cancel: (res) => {
|
|
console.log('👤 用户取消分享:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 朋友分享配置失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 微信扫一扫
|
|
* @param {Object} options 扫码选项
|
|
* @param {Number} options.needResult 是否返回扫描结果,0不返回,1返回
|
|
* @param {Array} options.scanType 扫码类型,qrCode二维码,barCode条形码
|
|
* @returns {Promise}
|
|
*/
|
|
scanQRCode(options = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.scanQRCode({
|
|
needResult: options.needResult || 1,
|
|
scanType: options.scanType || ['qrCode', 'barCode'],
|
|
success: (res) => {
|
|
console.log('✅ 扫码成功:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 扫码失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 选择图片
|
|
* @param {Object} options 选择选项
|
|
* @param {Number} options.count 图片数量,默认9
|
|
* @param {Array} options.sizeType 图片尺寸,original原图,compressed压缩图
|
|
* @param {Array} options.sourceType 图片来源,album相册,camera相机
|
|
* @returns {Promise}
|
|
*/
|
|
chooseImage(options = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.chooseImage({
|
|
count: options.count || 1,
|
|
sizeType: options.sizeType || ['original', 'compressed'],
|
|
sourceType: options.sourceType || ['album', 'camera'],
|
|
success: (res) => {
|
|
console.log('✅ 选择图片成功:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 选择图片失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 预览图片
|
|
* @param {Object} options 预览选项
|
|
* @param {String} options.current 当前显示图片的http链接
|
|
* @param {Array} options.urls 需要预览的图片http链接列表
|
|
* @returns {Promise}
|
|
*/
|
|
previewImage(options) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.previewImage({
|
|
current: options.current,
|
|
urls: options.urls,
|
|
success: (res) => {
|
|
console.log('✅ 预览图片成功:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 预览图片失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 获取地理位置
|
|
* @param {Object} options 定位选项
|
|
* @param {String} options.type 坐标类型,wgs84或gcj02
|
|
* @returns {Promise}
|
|
*/
|
|
getLocation(options = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.getLocation({
|
|
type: options.type || 'gcj02',
|
|
success: (res) => {
|
|
console.log('✅ 获取地理位置成功:', res);
|
|
resolve(res);
|
|
},
|
|
cancel: (res) => {
|
|
console.log('👤 用户取消定位:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 获取地理位置失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 打开地图
|
|
* @param {Object} location 位置信息
|
|
* @param {Number} location.latitude 纬度
|
|
* @param {Number} location.longitude 经度
|
|
* @param {String} location.name 位置名称
|
|
* @param {String} location.address 地址详情
|
|
* @param {Number} location.scale 地图缩放级别
|
|
* @returns {Promise}
|
|
*/
|
|
openLocation(location) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.openLocation({
|
|
latitude: location.latitude,
|
|
longitude: location.longitude,
|
|
name: location.name || '',
|
|
address: location.address || '',
|
|
scale: location.scale || 14,
|
|
success: (res) => {
|
|
console.log('✅ 打开地图成功:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 打开地图失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 微信支付
|
|
* @param {Object} payInfo 支付信息
|
|
* @returns {Promise}
|
|
*/
|
|
chooseWXPay(payInfo) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.chooseWXPay({
|
|
timestamp: payInfo.timestamp,
|
|
nonceStr: payInfo.nonceStr,
|
|
package: payInfo.package,
|
|
signType: payInfo.signType || 'MD5',
|
|
paySign: payInfo.paySign,
|
|
success: (res) => {
|
|
console.log('✅ 微信支付成功:', res);
|
|
resolve(res);
|
|
},
|
|
cancel: (res) => {
|
|
console.log('👤 用户取消支付:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 微信支付失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 关闭当前网页窗口
|
|
*/
|
|
closeWindow() {
|
|
if (!this.isInitialized) {
|
|
console.error('❌ 微信JS-SDK未初始化');
|
|
return;
|
|
}
|
|
wx.closeWindow();
|
|
}
|
|
|
|
/**
|
|
* 获取网络状态
|
|
* @returns {Promise}
|
|
*/
|
|
getNetworkType() {
|
|
return new Promise((resolve, reject) => {
|
|
if (!this.isInitialized) {
|
|
reject(new Error('微信JS-SDK未初始化'));
|
|
return;
|
|
}
|
|
|
|
wx.getNetworkType({
|
|
success: (res) => {
|
|
console.log('✅ 获取网络状态成功:', res);
|
|
resolve(res);
|
|
},
|
|
fail: (error) => {
|
|
console.error('❌ 获取网络状态失败:', error);
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 获取微信JS-SDK版本信息
|
|
* @returns {String} 版本号
|
|
*/
|
|
getVersion() {
|
|
if (typeof wx !== 'undefined' && wx.getWxVersion && typeof wx.getWxVersion === 'function') {
|
|
try {
|
|
return wx.getWxVersion();
|
|
} catch (error) {
|
|
console.warn('获取微信版本失败:', error);
|
|
return '无法获取版本';
|
|
}
|
|
}
|
|
return typeof wx !== 'undefined' ? '1.6.0 (推测)' : '未加载';
|
|
}
|
|
|
|
/**
|
|
* 获取可用的API列表
|
|
* @returns {String} 可用API的描述
|
|
*/
|
|
getAvailableApis() {
|
|
if (!this.isInitialized) {
|
|
return '未初始化';
|
|
}
|
|
|
|
// 返回当前配置的API列表
|
|
const availableCount = this.jsApiList.length;
|
|
const mainApis = ['分享', '扫码', '图片选择', '地理位置', '网络状态'];
|
|
return `${availableCount}个API (${mainApis.join('、')}等)`;
|
|
}
|
|
|
|
/**
|
|
* 统一的SDK加载器 - 供其他页面直接使用(简化版)
|
|
* @returns {Promise<boolean>} 加载结果
|
|
*/
|
|
static loadWeChatSDK() {
|
|
return new Promise((resolve, reject) => {
|
|
// 检查是否已经加载过
|
|
if (typeof window !== 'undefined' && window.wx && window.wx.config && window.wx.ready) {
|
|
console.log('✅ 微信JS-SDK已加载');
|
|
return resolve(true);
|
|
}
|
|
|
|
if (typeof document === 'undefined') {
|
|
return reject(new Error('document not available'));
|
|
}
|
|
|
|
// 检查是否正在加载中
|
|
const existing = document.getElementById('wx-jssdk-dynamic');
|
|
if (existing) {
|
|
existing.addEventListener('load', () => resolve(true));
|
|
existing.addEventListener('error', (e) => reject(e));
|
|
return;
|
|
}
|
|
|
|
// 官方推荐的双CDN地址
|
|
const sdkUrls = [
|
|
'https://res.wx.qq.com/open/js/jweixin-1.6.0.js',
|
|
'https://res2.wx.qq.com/open/js/jweixin-1.6.0.js',
|
|
];
|
|
let currentUrlIndex = 0;
|
|
|
|
const tryLoadScript = () => {
|
|
if (currentUrlIndex >= sdkUrls.length) {
|
|
reject(new Error('所有微信JS-SDK资源加载失败'));
|
|
return;
|
|
}
|
|
|
|
const script = document.createElement('script');
|
|
script.id = 'wx-jssdk-dynamic';
|
|
script.type = 'text/javascript';
|
|
script.async = true;
|
|
script.src = sdkUrls[currentUrlIndex];
|
|
|
|
console.log(`🔄 [动态加载] CDN[${currentUrlIndex}]: ${script.src}`);
|
|
|
|
script.onload = () => {
|
|
if (typeof wx !== 'undefined' && wx.config && wx.ready) {
|
|
console.log('✅ [动态加载] 成功');
|
|
resolve(true);
|
|
} else {
|
|
console.log('❌ [动态加载] wx对象不完整');
|
|
currentUrlIndex++;
|
|
if (currentUrlIndex < sdkUrls.length) {
|
|
script.remove();
|
|
setTimeout(tryLoadScript, 1000);
|
|
} else {
|
|
reject(new Error('所有微信JS-SDK资源加载失败'));
|
|
}
|
|
}
|
|
};
|
|
|
|
script.onerror = () => {
|
|
console.log(`❌ [动态加载] CDN[${currentUrlIndex}] 失败`);
|
|
currentUrlIndex++;
|
|
if (currentUrlIndex < sdkUrls.length) {
|
|
script.remove();
|
|
setTimeout(tryLoadScript, 1000);
|
|
} else {
|
|
reject(new Error('所有微信JS-SDK资源加载失败'));
|
|
}
|
|
};
|
|
|
|
document.head.appendChild(script);
|
|
|
|
// 设置超时时间(10秒)
|
|
setTimeout(() => {
|
|
if (typeof wx === 'undefined' || !wx.config || !wx.ready) {
|
|
console.log(`❌ [动态加载] CDN[${currentUrlIndex}] 超时`);
|
|
script.remove();
|
|
currentUrlIndex++;
|
|
if (currentUrlIndex < sdkUrls.length) {
|
|
tryLoadScript();
|
|
} else {
|
|
reject(new Error('微信JS-SDK加载超时'));
|
|
}
|
|
}
|
|
}, 10000);
|
|
};
|
|
|
|
tryLoadScript();
|
|
});
|
|
}
|
|
}
|
|
|
|
// 创建单例实例
|
|
const weChatSDK = new WeChatSDK();
|
|
|
|
// 导出实例和类
|
|
export default weChatSDK;
|
|
export { WeChatSDK };
|
|
|
|
/**
|
|
* 使用示例:
|
|
*
|
|
* // 1. 初始化
|
|
* import weChatSDK from '@/utils/wechat.js';
|
|
*
|
|
* // 在页面加载时初始化
|
|
* weChatSDK.init().then(() => {
|
|
* console.log('微信JS-SDK初始化完成');
|
|
* });
|
|
*
|
|
* // 2. 配置分享
|
|
* weChatSDK.shareTimeline({
|
|
* title: '分享标题',
|
|
* link: 'https://example.com',
|
|
* imgUrl: 'https://example.com/icon.jpg'
|
|
* });
|
|
*
|
|
* // 3. 扫码
|
|
* weChatSDK.scanQRCode().then(result => {
|
|
* console.log('扫码结果:', result.resultStr);
|
|
* });
|
|
*
|
|
* // 4. 选择图片
|
|
* weChatSDK.chooseImage({ count: 3 }).then(result => {
|
|
* console.log('选中的图片:', result.localIds);
|
|
* });
|
|
*/
|