Files
device-voice-h5/utils/wxsdk.js
luo 4dc86889c5
All checks were successful
构建并部署前端到生产环境 / build-and-deploy (push) Successful in 55s
fix:bug scan
2026-06-26 14:59:15 +08:00

111 lines
2.2 KiB
JavaScript

// utils/wxsdk.js —— 封装微信扫一扫 不用旧的了
import { wechatApi } from '@/api/index.js'
const getWx = () => window.jWeixin || window.wx
const entryUrl = window.__WX_ENTRY_URL__ || window.location.href.split('#')[0]
let configPromise = null
let configUrl = ''
let configReady = false
const isIOS = () => /iphone|ipad|ipod/i.test(navigator.userAgent)
const getConfigUrl = () => {
// iOS 微信 WebView 的 JS-SDK 签名 URL 需要使用 SPA 首次进入的地址。
if (isIOS()) {
return entryUrl
}
return window.location.href.split('#')[0]
}
/**
* 初始化微信 JS-SDK
*/
export async function initWxConfig() {
const wx = getWx()
if (!wx) {
throw new Error('微信 SDK 未加载')
}
const url = getConfigUrl()
console.log(url);
if (configReady && configUrl === url) {
return
}
if (configPromise && configUrl === url) {
return configPromise
}
configUrl = url
configReady = false
configPromise = wechatApi.getJssdkConfig(url).then((data) => {
const { app_id, timestamp, nonce_str, signature } = data
return new Promise((resolve, reject) => {
wx.config({
debug: false,
appId: app_id,
timestamp: timestamp,
nonceStr: nonce_str,
signature: signature,
jsApiList: ['scanQRCode']
})
wx.ready(() => {
console.log('微信 SDK 就绪')
configReady = true
resolve()
})
wx.error((err) => {
console.error('wx.config 失败', err)
configReady = false
configPromise = null
reject(err)
})
})
}).catch((e) => {
console.error('获取微信签名失败', e)
configPromise = null
configReady = false
throw e
})
return configPromise
}
/**
* 调起微信扫一扫
* @returns {Promise<string>} 扫码结果字符串
*/
export async function wxScan() {
await initWxConfig()
const wx = getWx()
if (!wx) {
throw new Error('微信 SDK 未加载')
}
return new Promise((resolve, reject) => {
wx.scanQRCode({
needResult: 1,
scanType: ['qrCode', 'barCode'],
success(res) {
console.log('扫码成功:', res)
resolve(res.resultStr)
},
fail(err) {
console.error('扫码失败:', err)
reject(err)
}
})
})
}
/**
* 检查是否在微信环境中
*/
export function isInWechat() {
return /micromessenger/i.test(navigator.userAgent)
}