思路,使用web-view内嵌一个网页,在网页上实现扫码成功重定向时,判断是否携带code和state,携带则使用uni.postMessage传递个webview的message事件,然后将code等参数传递给后台进行登录
h5页面
// html
// 因为网站也要进行扫码登录,所以设置了一个stateFlag用来区分
<div v-if="state.stateFlag==='APP'" class="appWXCode">
<div v-loading="state.wxLoading" class="login-area ">
<div id="login_container"></div>
</div>
</div>
//js
<script setup>
import { useRouter, useRoute } from 'vue-router'
import { reactive,onMounted} from 'vue';
const router = useRouter()
const const state = reactive({
stateFlag:'H5',
wxLoading:false
})
onMounted(async () => {
let stateFlag = await route.query.stateFlag
if(stateFlag) state.stateFlag = stateFlag || 'H5'
if(queryLocalURLStr('state')) state.stateFlag = queryLocalURLStr('state').split('-')[1]
if(state.stateFlag==='APP') getWXLoginAboutInfo()
})
// 查询微信扫码登录相关信息
const getWXLoginAboutInfo = async() => {
state.wxLoading = true
const { data } = await queryWXLoginAboutInfo() //请求后台获取二维码等信息
state.wxLoading = false
var obj = new WxLogin
({
id:"login_container",//div的id
appid: data.app_id,
scope: "snsapi_login",//写死
redirect_uri:encodeURI(data.url), //扫码登录后的重定向地址,我用和这个页面一样的地址
state: data.state+'-' + state.stateFlag,
style: "black",//二维码黑白风格
});
}
router.isReady().then(async() => {
// 判断是否是重定向跳转的页面
if (queryLocalURLStr('code') && queryLocalURLStr('state')) {
let state = queryLocalURLStr('state').split('-')[0]
let stateFlag = queryLocalURLStr('state').split('-')[1]
// app扫码
if(stateFlag==='APP') {
console.log('传递信息')
uni.postMessage({
data:{
code:queryLocalURLStr('code'),
state:state
}
})
return false
}
//h5扫码
// 请求后台接口执行登录 3微信登录
await userPinia.login({
type: 3,
code: queryLocalURLStr('code'),
state: state
})
}
})
</script>
// 其中queryLocalURLStr是获取网址上的参数
function queryLocalURLStr(queryStr) {
let reg = new RegExp(`(^|&)${queryStr}=([^&]*)(&|$)`)
let queryStrs = window.location.search.substr(1).match(reg)
if (queryStrs != null) return unescape(queryStrs[2])
else return ''
}
// 需要在index.html中导入web-view.js 和wxLogin.js
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
app页面
<template>
<view class="page-root">
<web-view :src="state.url" @message="handleMessage" class="web-view"></web-view>
</view>
</template>
<script setup>
import { reactive } from 'vue';
import {
onLoad,
onUnload
} from '@dcloudio/uni-app'
import { useUserStore } from '../../store/user';
const userStore = useUserStore()
import api from '@/request/api.js'
const state = reactive({
url:''
})
const handleMessage = async (data)=>{
let dataObj = data.detail.data[0]
let param = {
code:dataObj.code,
state:dataObj.state,
type:3
}
await userStore['loginToMatchmaker'](param) //请求接口登录
uni.navigateBack({
delta:2
})
}
onLoad((options) => {
getWXLoginAboutInfo()
})
// 查询微信扫码登录相关信息
const getWXLoginAboutInfo = async() => {
const { data } = await api.queryWXLoginAboutInfo()
state.url = data.url+`/#/?stateFlag=APP`
}
</script>