You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
126 lines
3.6 KiB
126 lines
3.6 KiB
<template>
|
|
<!-- 跳转到微信授权地址 -->
|
|
</template>
|
|
|
|
<script>
|
|
import queryStringify from '@/utils/queryStringify'
|
|
import store from '@/store'
|
|
import { isEmpty, urlEncode } from '@/utils/util'
|
|
import Api from '@/api/wxofficial'
|
|
|
|
export default {
|
|
|
|
data() {
|
|
return {
|
|
// 页面来源是否为微信回调
|
|
isCallback: false
|
|
}
|
|
},
|
|
|
|
created() {
|
|
// 处理微信回调
|
|
this.onCallback()
|
|
// 跳转到微信授权
|
|
this.redirectUrl()
|
|
},
|
|
|
|
methods: {
|
|
|
|
// 处理微信回调
|
|
onCallback() {
|
|
// 接收微信传来的参数
|
|
const wxParam = queryStringify.parse(window.location.search)
|
|
if (!isEmpty(wxParam)) {
|
|
const url = window.location.href.replace(window.location.search, '')
|
|
window.location.href = url + '?' + urlEncode(wxParam)
|
|
return
|
|
}
|
|
// 获取code参数
|
|
const query = this.$route.query
|
|
if (isEmpty(query) || !query.code) {
|
|
return
|
|
}
|
|
// 请求后端获取微信用户信息
|
|
this.isCallback = true
|
|
Api.oauthUserInfo(query.code)
|
|
.then(({ data }) => {
|
|
console.log('用户同意了授权')
|
|
console.log('userInfo:', data)
|
|
// 授权成功事件
|
|
this.onAuthSuccess(data)
|
|
})
|
|
},
|
|
|
|
// 授权成功事件
|
|
// 这里分为两个逻辑:
|
|
// 1.将openid和userInfo提交到后端,如果存在该用户 则实现自动登录,无需再填写手机号
|
|
// 2.如果不存在该用户, 则显示注册页面, 需填写手机号
|
|
// 3.如果后端报错了, 则显示错误信息
|
|
async onAuthSuccess({ userInfo, encryptedData, iv }) {
|
|
const app = this
|
|
// 提交到后端
|
|
store.dispatch('LoginWxOfficial', {
|
|
partyData: { oauth: 'WXOFFICIAL', userInfo, encryptedData, iv },
|
|
refereeId: store.getters.refereeId
|
|
})
|
|
.then(result => {
|
|
// 一键登录成功
|
|
app.$toast(result.message)
|
|
// 相应全局事件订阅: 刷新上级页面数据
|
|
uni.$emit('syncRefresh', true)
|
|
// 跳转回原页面
|
|
setTimeout(() => app.onNavigateBack(), 2000)
|
|
})
|
|
.catch(err => {
|
|
const resultData = err.result.data
|
|
// 显示错误信息
|
|
if (isEmpty(resultData)) {
|
|
app.$toast(err.result.message)
|
|
}
|
|
// 判断还需绑定手机号
|
|
if (resultData.isBindMobile) {
|
|
app.onEmitSuccess({ userInfo, encryptedData, iv })
|
|
}
|
|
})
|
|
},
|
|
|
|
// 跳转到微信授权
|
|
redirectUrl() {
|
|
if (this.isCallback) {
|
|
return
|
|
}
|
|
const callbackUrl = window.location.href
|
|
Api.oauthUrl(callbackUrl)
|
|
.then(result => {
|
|
const url = result.data.redirectUrl
|
|
window.location.href = url
|
|
})
|
|
},
|
|
|
|
// 将oauth提交给父级
|
|
async onEmitSuccess({ userInfo, encryptedData, iv }) {
|
|
this.$emit('success', {
|
|
oauth: 'WXOFFICIAL', // 第三方登录类型: WXOFFICIAL
|
|
userInfo,
|
|
encryptedData,
|
|
iv
|
|
})
|
|
},
|
|
|
|
/**
|
|
* 登录成功-跳转回原页面
|
|
*/
|
|
onNavigateBack(delta = 1) {
|
|
const pages = getCurrentPages()
|
|
if (pages.length > 1) {
|
|
uni.navigateBack({
|
|
delta: Number(delta || 1)
|
|
})
|
|
} else {
|
|
this.$navTo('pages/index/index')
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
</script>
|
|
|