以下代码兼容H5、微信H5、支付宝H5、APP、微信小程序、支付宝小程序
下载js插件放在utils目录下面 /utils/qrcode.js、/utils/jweixin-1.6.0.js、/utils/jalipay-3.1.1.js
链接: https://pan.baidu.com/s/1wKE7DgejCcW5ZT7Sib_IVA?pwd=w8ju
1.在本地运行到H5浏览器是调用uni.chooseImage从本地相册选择图片
参考文档:uni-app官网
2.在App端和微信小程序、支付宝小程序是调用uni.scanCode
参考文档:uni.scanCode(OBJECT) | uni-app官网
3.在微信H5是调用微信JsApi的扫一扫接口
参考文档:概述 | 微信开放文档
4.在支付宝H5是调用支付宝JsApi的扫一扫接口
参考文档:支付宝H5开放文档
页面代码
<template>
<view class="" style="padding-top: 200px;">
<u-button type="success" @click="handleClickScan()">扫一扫</u-button>
</view>
</template>
<script>
// #ifdef H5
import qrcode from "@/utils/qrcode.js"
//引用微信扫一扫
import wechatJssdk from '@/utils/jweixin-1.6.0.js'
//引用支付宝jssdk
import alipayJssdk from '@/utils/jalipay-3.1.1.js'
// #endif
export default {
data() {
return {
}
},
onLoad(options) {
},
mounted() {
if (this.isWechat()) { // 在微信浏览器才加载
this.getCode()
}
},
methods: {
// 判断是否在微信浏览器内
isWechat() {
// #ifdef H5
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/micromessenger/i) == 'micromessenger') {
return true;
} else {
return false;
}
// #endif
},
// 判断是否在支付宝浏览器内
isAlipay() {
// #ifdef H5
var ua = window.navigator.userAgent.toLowerCase();
if (ua.indexOf('alipay') > -1) {
return true;
} else {
return false;
}
// #endif
},
handleClickScan() {
if (this.isWechat()) {
this.wechatScan()
} else if (this.isAlipay()) {
this.aliScan()
} else {
this.uniScan()
}
},
wechatScan() {
console.log("微信扫一扫");
wechatJssdk.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: (res) => {
console.log("code=", res.resultStr);
},
fail: (error) => {}
});
},
aliScan() {
alipayJssdk.scan({
type: 'qr', // 扫描目标类型,支持 qr / bar,相应扫码选框会不同,默认 qr
}, (res) => {
if (res.code) {
console.log("res.code--", res.code);
}
});
},
uniScan() {
// #ifdef APP-PLUS
console.log("APP");
// #endif
// #ifdef MP-WEIXIN
console.log("微信小程序");
// #endif
// #ifdef APP-PLUS || MP-WEIXIN || MP-ALIPAY
uni.scanCode({
onlyFromCamera: true,
success: (res) => {
console.log("code=", res.result);
}
})
// #endif
// #ifdef H5
console.log("H5");
uni.chooseImage({
sizeType: ['original'],
count: 1,
success: (res) => {
const tempFilePaths = res.tempFilePaths
qrcode.decode(tempFilePaths[0]);
qrcode.callback = (code) => {
if (code == "error decoding QR Code") {
this.toast("识别二维码失败,请重新上传!")
} else {
console.log("code=", code);
}
}
}
});
// #endif
},
//获取微信公众号权限信息
getCode() {
if (location?.href) {
let url = location.href.split('#')[0];
this.$http('/api/sendmq/getwxsign', {
url: url,
})
.then(res => {
if (res.code === 200) {
wechatJssdk.config({
debug: false,
appId: res.data.appId,
timestamp: res.data.timestamp,
nonceStr: res.data.nonceStr,
signature: res.data.signature,
jsApiList: ['scanQRCode', 'chooseWXPay', 'chooseImage',
'previewImage'
],
})
wechatJssdk.ready((re) => {})
wechatJssdk.error((error) => {})
} else {
uni.showToast({
title: res.message,
icon: "none"
})
}
})
}
},
},
}
</script>
<style scoped lang="scss">
</style>