第一步是微信公众平台申请测试账号
第二部在网页授权(修改)填写回调域名,测试可以使用自己本地的端口,注意:这里不可以添加http:// 只准添加例如:baidu.com
第三部按照里面的只是即可
代码如下
1,// 获取code
getCode() {
this.code = ''
let origin = 'http://192.168.1.115:8082/mycenter/mycenter' //网页授权的回调域名,这里设置的是本地端口
let urlNow = encodeURIComponent(origin); //处理域名
let scope = "snsapi_userinfo"; //弹框显示授权
let appid = "公众平台申请的id";
this.code = this.codeurl
// 截取code
if (this.code == null || this.code === '') {
//未授权qu授权
let url =
`https://open.weixin.qq.com/connect/oauth2/authorize?
appid=${
appid}&redirect_uri=${
urlNow}&
response_type=code&scope=${
scope}&
state=123#wechat_redirect`;
window.location.href = url;
}
},
getUrlCode() {
// 截取url中的code方法
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])
}
}
return theRequest
},
2.// 拿code换取accessToken和openid最后获取用户信息
async saveOpenID() {
let data = {
code: this.codeurl,
initiationID: this.rankvalue(32)
}
if (this.codeurl) {
const res = await this.myrequest.post('/dlt/user/access_token', data)
if (res.result) {
this.accessToken = res.result.accessToken
this.openid = res.result.openid
this.login() //获取用户登录信息
}
}
},
// 获取登录用户信息
async login() {
let loginData = {
loginCode: this.openid,
initiationID: this.rankvalue(32),
accessToken: this.accessToken
}
const userInfo = await this.myrequest.post("/dlt/user/login", loginData)
this.headImage =userInfo.result.headImage
this.userName = userInfo.result.userName
},
created() {
this.codeurl = this.getUrlCode().code //获取code
this.getCode()
},