一、网页授权流程?
网页授权流程分为四步:
1.引导用户进入授权页面同意授权,获取code
2.通过 code 换取网页授权access_token(与基础支持中的access_token不同)
3.如果需要,开发者可以刷新网页授权access_token,避免过期
4.通过网页授权access_token和 openid 获取用户基本信息(支持 UnionID 机制)
二、点击授权案例
1.APPID,重定向
(原谅无法透露,大家按需写就ok)
2.读入数据
- HTML部分 /pages/tabbar/mine
- JS部分
//不要忘记引入
import {APPID,redirect_uri} from "@/public/env.js"
methods:{
info() {
// 微信登陆
let wx =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
window.location.href = wx
},
}
- JS部分 /pages/tabbar/index
//不要忘记引入
import {
IMG_URL,
PARAMS
} from '@/public/env';
// 注意:按项目需求截取,此处只截取了code
onLoad(options) {
console.log(window.location.href);
console.log('1112233', window.location.href?.split('=')[1]?.split('&')[0]);
try {
// 微信授权后执行
let token1 = uni.getStorageSync('token')
if (window.location.href?.split('?')[1]?.split('=')[0] == 'code' && !token1)
{
this.getOpenId(window.location.href?.split('=')[1]?.split('&')[0])
}
} catch (e) {
//TODO handle the exception
console.log('22222222', e);
}
},
methods:{
// 获取openid 并绑定
getOpenId(code) {
let that = this;
let sendData = {
code: code
};
that.apifun.unirequest(that.apifun.getOpenId, 'post', sendData, (res) =>
{
console.log('000', res)
if (res.code === 1) {
let datas = res.data;
this.getLogin(res.data)
} else {
that.apifun.toast(res.msg)
}
})
},
getLogin(box) {
let that = this;
let sendData = {
openid: box.openid,
avatar: box.headimgurl,
nickname: box.nickname
};
that.apifun.unirequest(that.apifun.login, 'post', sendData, (res) => {
console.log('121212', res)
if (res.code === 1) {
let datas = res.data;
//存token,个人信息
uni.setStorageSync("usermessage", res.data.userinfo)
uni.setStorageSync("token", res.data.userinfo.token)
} else {
that.apifun.toast(res.msg)
}
})
}
}
更多请参考文档: