// utils/wxsdk.js —— 封装微信扫一扫 import jweixin from 'jweixin-module' import { wechatApi } from '@/api/index.js' /** * 初始化微信 JS-SDK */ export async function initWxConfig() { // iOS 微信 SPA 需用首次进入的 URL 签名 const url = window.location.href.split('#')[0] try { // 调用后端接口获取签名 const data = await wechatApi.getJssdkConfig(url) const { app_id, timestamp, nonce_str, signature } = data return new Promise((resolve, reject) => { jweixin.config({ debug: true, appId: app_id, timestamp: timestamp, nonceStr: nonce_str, signature: signature, jsApiList: ['scanQRCode'] }) jweixin.ready(() => { console.log('微信 SDK 就绪') resolve() }) jweixin.error((err) => { console.error('wx.config 失败', err) reject(err) }) }) } catch (e) { console.error('获取微信签名失败', e) throw e } } /** * 调起微信扫一扫 * @returns {Promise} 扫码结果字符串 */ export function wxScan() { return new Promise((resolve, reject) => { jweixin.scanQRCode({ needResult: 1, // 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) }