- 下载微信JSSDK https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#1
- 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
备注:登录后可在“开发者中心”查看对应的接口权限。 - 我这边新建一个wechat.js用于调用扫一扫
var jweixin = require('@/components/app/jweixin'); // 我将下载的插件重命名为jweixin.js放在components/app/目录下
export default {
//判断是否在微信中
isWechat:function(){
var ua = window.navigator.userAgent.toLowerCase();
if(ua.match(/micromessenger/i) == 'micromessenger'){
return true;
}else{
return false;
}
},
//初始化sdk配置
scanQRJssdk:async function(){
let url = window.location.href.split('#')[0]
let resData = await $http.POST('后台接口', {url:url}); // 根据接口返回appId,timestamp等数据
if(resData.code==200){
jweixin.config({
beta: true,
debug: false,
appId: resData.data.appId,
timestamp:resData.data.timestamp,
nonceStr: resData.data.nonceStr,
signature:resData.data.signature,
jsApiList: ['checkJsApi','scanQRCode']
});
jweixin.ready(function () {
jweixin.checkJsApi({
jsApiList:['scanQRCode'],
success:function(res){
console.log(res)
}
})
});
}
},
- 页面中调用方法
<template>
<view>
<button @click="OnQRcode()" class="sm cu-btn block bg-blue margin-top margin-lr-xs">扫码</button>
</view>
</template>
<script>
// 应用jweixin跟wechat插件
import jweixin from '@/components/app/jweixin-module'
import wechat from '@/components/app/wechat'
export default {
data() {
return {
}
},
onLoad() {
wechat.scanQRJssdk() // 页面打开时自动获取scanQRJssdk
},
methods: {
OnQRcode:function(){ // 点击的时候调起扫一扫功能呢
let self = this
jweixin.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
let resultStrArr = res.resultStr.split(",") // 转为数组时为了避免扫描一维码是返回CODE_128,20180528前面会添加一个CODE_128所以转为数组获取最后一条就行了
console.log(resultStrArr[resultStrArr.length-1]) // 输出扫码信息
}
});
},
}
</script>
ps:如果想支持苹果手机的话不要使用navigateTo跳转请使用window.location.href跳转到要扫码的页面。
locationUrl:function(url){ // window.location.href链接跳转
// getApp().globalData.apiUrlA 默认H5端页面链接,url拼接的地址
window.location.href=getApp().globalData.apiUrlA+url
},
urlLink:function(url,jsonData){ // 正常路由跳转
this.router.push({route: this.routerUrl[url],query:jsonData});
},