一、https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=snsapi_base#wechat_redirect
参数解析:
1.appid 微信公众号ID 去开发者平台获取
2.redirect_uri,重定向的页面地址,授权完成后再重新回到当前页面
3.scope:两种模式
snsapi_base静默授权,只获取oppenID
snsapi_userinfo非静默授权,需要手动确认,获取oppenId和微信头像等用户信息
成功返回跳转的页面后面会带有code
将code传给后台获取oppenId
<script>
import GetUrlParam from '@/assets/js/util/getUrlParam.js'
export default {
name: 'Index',
data () {
return {
}
},
created () {
this.getCode()
},
methods: {
getCode () { // 非静默授权,第一次有弹框
const code = GetUrlParam('code') // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
const local = window.location.href
if (code == null || code === '') {
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + window.APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
} else {
this.getOpenId(code) //把code传给后台获取用户信息
}
},
getOpenId (code) { // 通过code获取 openId等用户信息,/api/user/wechat/login 为后台接口
let _this = this
this.$http.post('/api/user/wechat/login', {code: code}).then((res) => {
let datas = res.data
if (datas.code === 0 ) {
console.log('成功')
}
}).catch((error) => {
console.log(error)
})
}
}
}
</script>