声明:此处为博主,真实开发过程的记录,直奔主题,没有测试环节,请见谅。
一、前期准备工作
- 微信公众平台的注册好的appid、密钥,点我去注册了解
- 微信公众平台中需要设置授权域名,遵循微信的规则
二、登录获取openid
- 获取code
获取state、appid、scope,这里重定向的地址redirect_uri我写死了,便于自己控制,根据重定向后的参数确认是否回来code,其它参数都放到数据库,后台管理即可。
getCode(){
let methodName = "/你的后台接口地址";
this.$http
.post(methodName)
.then(res => {
let state = res.data.state;
let appid = res.data.appId;
this.$store.commit("set_appid", appid);
let redirect_uri = "获取到code后你的回调地址";
// let scope = "snsapi_userinfo";
let scope = res.data.scope;
let path =
"https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" +
appid +
"&redirect_uri=" +
redirect_uri +
"&response_type=code&scope=" +
scope +
"&state=" +
state +
"#wechat_redirect";
location.replace(path);
})
.catch(error => {
console.log(error);
this.loading = false;
this.$toast.error("获取code失败");
});
}
回调后vuex存储code
// 此处我是封装为一个方法,在每次created调用。
let code = this.getQueryString("code");
if (code) {
this.$store.commit("set_code", code);
//第二步:获取用户基本信息
this.getUserBaseInfo();
}
getUserBaseInfo(){
this.$http
.post(methodName, params)
.then(res => {
//存储token
this.$store.commit("set_token", res.data.token);
//存储用户基本信息
this.$store.commit("set_openid", res.data.userBaseInfo.openid);
})
.catch(error => {
console.log(error);
this.loading = false;
this.$toast.error("获取用户基本信息失败");
});
}
以上后台的代码具体的,参照下代码应该可以写好,这里就不详细说了,博主是专业前端开发,哪里有写的不妥的或者不对的,还请多多指教,大家互相学习。或者哪位有更好的方式方法请不吝赐教。