1.点击按钮,掉获取授权的方法
// 微信登录
wxlogin () {
var url=encodeURIComponent("http://www.****.com.cn/#/bindTel")
var appid=this.appid;
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
},
2.获取code,在重定向页面初次加载的时候获取。
// 处理code
getCode () {
const code = location.href.split('?')[1]
if (!code) return {}
const obj = {}
code.split('&').forEach(item => {
const arr = item.split('=')
obj[arr[0]] = arr[1]
})
return obj
},
var code=this.getCode().code;//通过处理路由获取路由中的code
3.根据code获取openid,accesstoken
this.appid=response.appid
this.appsecret=response.appsecret
var appid= this.appid;
var code=this.getCode().code;
var appsecret= this.appsecret;
let getaccess=`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code`
//通过拿到的code和appID、app_serect获取access_token和open_id
this.$get(getaccess).then( resText => {
var open_id = resText.openid;
this.openids=open_id;//获取到的openid
this.accessToken=access_token;//获取到的access_token
})