微信公众号H5授权登录
废话不多,直接上代码(这里只写代码的实现)
页面进来判断微信环境
onShow() {
//设置初始值为false,微信环境下才能打开
this.isWeixin = this.isWechat()
if (this.isWeixin) {
if (uni.getStorageSync('token') == '' || uni.getStorageSync('token') == null || uni.getStorageSync(
'token') == undefined) {
this.checkWeChatCode()
return false
} else {
}
} else {
uni.showToast({
title: '请在微信浏览器打开',
icon: 'none'
})
}
if (uni.getStorageSync('nickname')) {
this.nickname = uni.getStorageSync('nickname')
}
if (uni.getStorageSync('avatar')) {
this.avatar = uni.getStorageSync('avatar')
}
if (uni.getStorageSync('cardtype')) {
this.cardtype = uni.getStorageSync('cardtype')
}
},
方法里面部分代码
//方法:用来判断是否是微信内置的浏览器
isWechat() {
return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
},
//用来提取微信url的code
getUrlCode(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
[, ''
])[1]
.replace(/\+/g, '%20')) || null
},
//检查浏览器地址栏中微信接口返回的code
checkWeChatCode() {
let code = this.getUrlCode('code')
if (code) {
this.getOpenidAndUserinfo(code)
}
},
//请求微信接口,用来获取code (我这里直接写的点击事件绑定并判断token展示未登录或者登录状态)
getWeChatCode() {
let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
let appid = '你的公众号appid'
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
appid +
"&redirect_uri=" +
local +
"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
},
//把code传递给后台接口,实现登录
getOpenidAndUserinfo(code) {
let data = {
code: code
}
//这里的参数由于后端人员的要求,做了加密处理
http.post('登录接口', Base64.encode(JSON.stringify(data))).then(res => {
if (res.result.status == 2) {
//此时说明code已经失效或者toke过期,需重新获取code进行登录
this.getWeChatCode()
}
if (res.errorcode != 0) {
uni.showToast({
title: res.message,
icon: 'none'
})
} else {
this.afterLogin(res)
}
}).catch(err => {
console.log(err)
})
},
/*微信登录*/
afterLogin(res) {
let user = res.result
uni.setStorageSync('avatar', user.user_mes.wechat_avatar ? user.user_mes.wechat_avatar : '')
uni.setStorageSync('nickname', user.user_mes.name ? user.user_mes.name : '')
uni.setStorageSync('id', user.user_mes.user_id ? user.user_mes.user_id : '')
uni.setStorageSync('token', user.user_mes.user_token ? user.user_mes.user_token : '')
uni.setStorageSync('status', res.status)
//自定义跳转页可自行封装方法,这里不多做阐述
uni.reLaunch({
url: '/pages/mine/mine'
})
},
最后在调用其他接口时判断后端人员返回的token进行重定向登录或者进行其他逻辑