背景:将前端h5页面放入企业微信应用或者从企业微信打开浏览器页面
前提:登录
怎么获取登录token 呢 通过获取获取地址栏的code去请求接口获取token
两种方案的区别是:
方案一在已经登录的情况下每次点击进入页面都需要去拿code
方案二则是当已经登录检测到code已经存在就不需要再去拿code 顾推荐方案二
方案一:在企业微信工作台配置应用并将需要打开的界面及redirecturl给后端配置 (前端也可以配置)即可在浏览器获取到token
方案二:前端页面写入代码
const autoLogin = () => {
const appId = 'ww1a2245553f8da44f'
const redirectUrl = encodeURIComponent(
`${window.location.origin}${window.location.pathname}${window.location.hash}`,
)
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=#wechat_redirect`
window.location.replace(url)
}
const getQuery = (key) => {
let val = ''
const url = window.location.toString()
const re = new RegExp(`${key}=([^?&#/]*)`, 'i')
if (re.test(url)) {
val = url.match(re)[1].toString()
}
return val
}
if (code === '') {
autoLogin()
} else {
//走登录流程
const nextUrl = (route.query.next || '/') as string
try {
const d = await ApiLogin.wxLogin(code)
userStore.token = d.data.accessToken
await userStore.getUserInfo()
await userStore.getRole()
if (userStore.userInfo.user && userStore.userInfo.user.userId) {
const hour = new Date().getHours()
const thisTime =
hour < 8
? '早上好'
: hour <= 11
? '上午好'
: hour <= 13
? '中午好'
: hour < 18
? '下午好'
: '晚上好'
ElNotification({
title: thisTime,
message: `欢迎登录${import.meta.env.VITE_APP_TITLE}!`,
type: 'success',
duration: 3000,
})
nextTick(() => {
router.push(nextUrl)
})
} else {
fullscreenLoading.value = false
ElMessageBox.alert('没有权限', '系统提醒').then(() => {
try {
userStore.token = ''
userStore.userInfo = {}
} catch (e) {
return e
}
})
}
} catch (ex: any) {
console.log('fail', ex)
router.push({
path: '/error',
query: {
message: '登录失败!',
},
})
}
}
拓展:无论是哪一种登录方式 目的都是获取token 获取tokern的前提就是通过第三方唯一值去获取
前端单点登录是通过获取ticket去置换token及其用户信息