uniapp app端实现微信扫码登录

思路,使用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>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值