问题描述
微信内h5页面微信授权登录,获取code换取登录token
解决方案:
1.用户在微信内授权登录,这里用的是vue开发,登录之后code在回调的url中,然后拿着code向后端换取token即可.
wxgetMobileCode() {
const appid = “wxxxxxxx”;
const redirect_uri = encodeURIComponent(window.location.href);
const scope = “snsapi_userinfo”
const urls =
https://open./connect/oauth2/authorize?appid=${appid} &redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect
window.location.href = urls
},
2.在回调的url中获取code
created() {
if(this.$route.query.code
) {
this.getWeixin(this.$route.query.code
); //执行换取token
} else {
//因为code返回的时候不能直接通过参数拿到,所以要对code进行截取处理
let href = window.location.href
let origin = window.location.origin
let hash = window.location.hash
if(href.includes(“code”)) {
this.code = href.split(‘?’)[1].split(‘=’)[1].split(‘&’)[0];
window.location.href =${origin}/${hash}&code=${this.code}
}
}
},