按照微信官方要准备一个链接:
注意链接中的几个参数:
在methods中写上这两个方法:
getCode() {
const code = this.getUrlParam('code') // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
const local = window.location.href
let redirect_uri = encodeURIComponent(local) //回调的地址要编码
if (code == null || code === '') {
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
} else {
uni.setStorageSync('code', code)
this.code = code
let that = this
shop({
url: "/api/user/code",
method: "POST",
data: {
code: that.code
}
}).then((res) => {
res = JSON.parse(res)
uni.setStorageSync('user_id', res.data.userinfo.user_id) //存储用户id
console.log(res)
})
}
},
getUrlParam(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
var r = window.location.search.substr(1).match(reg)
if (r != null) return unescape(r[2])
return null
},
这样就可以在回调的地址里拿到code了