前言
最近有一个需求是:盘点待审批状态,需要用微信公众号推送消息给审批人员,让其在微信中审批。因此就需要:通过微信的网页授权(即:微信公众号授权登录Vue H5项目并指定跳转到某一个页面进行操作)
前提准备
1、 官方文档地址
https://open.weixin.qq.com/connect/oauth2/authorize?appid=
自己公众号openid
&redirect_uri=授权后重定向的回调链接地址(即需要调跳转的H5页面)
&response_type=code&scope=snsapi_userinfo&state=123(url参数)
#wechat_redirect
注释:
注意
:跳转回调redirect_uri
,必须是https
开头
2、微信公众号需要配置以下:
具体步骤
逻辑思路
:
判断token是否存在(即判断是否已经登陆H5项目)1、如果已登陆,就直接跳转页面。
2、如果没有登陆,就要进行授权登录并重置token。
在H5项目新建一个wxh5页面(此页面是白名单
——即未登录也可以进入)
<template>
<div class="wx-h5">
<van-loading type="spinner" color="#1989fa" vertical>页面跳转中...</van-loading>
</div>
</template>
<script>
import { setToken } from '@/utils/auth'
export default {
name: 'WXh5',
data() {
return {
code: '',
id: '' // 盘点单id
}
},
mounted() {
console.log('获取url参数', this.getUrlCode())
this.code = this.getUrlCode().code
this.id = this.getUrlCode().state
this.checkLogin()
},
methods: {
// 审核页登录授权
async getWxLogin() {
const res = await this.$api.getWxLogin(this.code)
if (res.success) {
console.log('存储token', res.data)
setToken(res.data)
// 存储token
if (res.data) {
this.$router.push({
path: '跳转路由地址',
query: { addTitle: '盘点', id: this.id, type: 'wx' }
})
}
}
},
// 判断是否登录
async checkLogin() {
const res = await this.$api.checkLogin()
if (res.success) {
console.log('是否登录', res.data)
if (res.data) {
console.log('跳转审批')
this.$router.push({
path: '跳转路由地址',
query: { addTitle: '盘点', id: this.id, type: 'wx' }
})
} else {
this.getWxLogin()
}
}
},
// 获取url中的code方法
getUrlCode() {
// 截取url中的code方法
const url = location.search
// eslint-disable-next-line no-new-object
const theRequest = new Object()
if (url.indexOf('?') != -1) {
const str = url.substr(1)
const strs = str.split('&')
for (let i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
}
}
return theRequest
}
}
}
</script>
<style lang="scss">
.wx-h5 {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.1);
}
</style>