vue H5 调用微信扫描二维码 识别
项目中需要调用H5的扫码,识别设备二维码的序列号,填入输入框中。一起来看看怎么实现滴。
1,微信公众号设置
(1)配置js接口安全域名(就是H5部署到线上的域名)
(2)配置Ip 白名单(将服务器的IP配置进去)
2,项目依赖安装
(1)jweixin-module
jweixin-module 安装依赖 package.json "dependencies" 对象中 新增:
"jweixin-module": "^1.6.0"
然后 npm install
(2)main.js
const app = createApp(App)
let jweixin = require('jweixin-module')
app.config.globalProperties.$wx = jweixin
vue2 的使用 Vue.prototype.$wx = jweixin
3,封装微信配置公共方法
import { Toast} from 'vant';
import axios from "axios"
export function wxConfig(wxRef, cb) {
let data = {
url: window.location.href.split('#')[0]
}
axios.post('请求地址',data).then((resp) => {
if (resp.data.code === "000000") {
wxRef.config({
// debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: resp.data.data.appId, // 必填,公众号的唯一标识
timestamp: Number(resp.data.data.timestamp), // 必填,生成签名的时间戳
nonceStr: resp.data.data.nonceStr, // 必填,生成签名的随机串
signature: resp.data.data.signature, // 必填,签名
jsApiList: ["checkJsApi","scanQRCode"] // 必填,需要使用的JS接口列表
})
wxRef.ready( () => {
cb && cb()
})
}else{
Toast('获取微信接口失败')
}
});
}
4,页面中调用方法实现(vue3)
// 扫码按钮
<van-button
size="small"
icon="scan"
@click="onScanQrCode"
></van-button>
//引用
import {getCurrentInstance } from "vue";
import { wxConfig } from "@/utils/wx.js"; //公共方法
//方法执行
setup() {
// main.js的微信常量
const { proxy } = getCurrentInstance();
//点击事件
const onScanQrCode = () => {
// vue2 直接使用 this.$wx
wxConfig(proxy.$wx, () => {
proxy.$wx.scanQRCode({
needResult: 1,
scanType: ["qrCode"],
success: function (res) {
// url 就是识别的结果
const url = res.resultStr;
//下面属于我们二维码规则的字符串匹配,可以根据你们自己项目规则进行修改
let b = url.split("?");
let c = b[1].split("=");
let d = c[1].split("$$");
deviceSn.value = d[0];
},
});
});
}
}
就可以了,大家试试,有问题评论区交流。