业务需求:前端获取url地址上的code,传递给后端,将code作为接口参数,调用接口返回token,expires,userInfo
data() {
return {
code: ''
}
},
appid:微信公众平台开发设置里可以找到
redirect_url:获取到code后重定向回来访问的页面,
scope分为两种类型:
1. snsapi_base:静默授权,只获取用户的openID,优点:不弹出用户的授权页面,直接跳转,缺点:获取不到用户的其他信息。
2. snsapi_userinfo:非静默授权,需用户授权,除了获取到用户的openID之外,还可以获取到用户的昵称、性别、所在地等,优点:可以获取到用户更多信息,即使在用户不关注的情况下也可以获取到,缺点:必须要用户手动授权
3.获取code,getUrlCode()截取url中的code方法,
获取到的回调地址 /future/?code=031nGIml2UknCb4sCIkl2Vcixc0nGImV&state=STATE,可以发布到线上看是否获取到code,然后用fiddler抓包工具查看是否获取到code
methods: {
getCode() { // 非静默授权,第一次有弹框
var local = 'https://ck.kml169.com/future' //当前页面的地址
// const local = window.location.href;
var appid = 'wxdf495b6476b487a2' //公众号里有自己查,不会找的查一下百度
this.code = this.getUrlCode().code // 截取code
// 判断地址栏参数有无code,如果没有code,页面地址就跳转到微信提供的获取code的链接
if (this.code == null || this.code == '') {
console.log(1116666)
location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid +
"&redirect_uri=" +
encodeURIComponent(local) + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
} else {
// 获取code后自己的业务逻辑
console.log(222)
request.get('/community_api/Login/login', {
code: this.code
}).then(res => {
if (res.code == 0) {
// alert(res.data+'111111')
uni.setStorage({
key: "token",
data: res.data.token
})
uni.setStorage({
key: "expires",
data: res.data.expires
})
uni.setStorage({
key: "userInfo",
data: res.data.userInfo
})
uni.navigateTo({
url: '/pagesA/village/villageList'
})
}
})
}
},
// 截取url中的code方法
getUrlCode() {
var url = location.search
var theRequest = new Object()
if (url.indexOf("?") != -1) {
var str = url.substr(1)
var strs = str.split("&")
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
}
}
console.log(theRequest,'111')
return theRequest
},
},
onLoad() {
this.getCode()
},