注意:
1)路由:mode: 'history'
2)保证h5页面域名和公众号后台js安全域名一致
前端配置文件 wxConfig.js
import Vue from 'vue';
import wx from 'weixin-js-sdk';
Vue.use(wx);
export default {
data() {
return {
appId: 'wx485*********e74',
responseType: 'code',
scope: 'snsapi_userinfo',
baseURI: 'https://open.weixin.qq.com/connect/oauth2/authorize',
};
},
async created() {
},
methods: {
/**
* 获取code
* @param locationSearch
* @return {*}
*/
getCode(locationSearch) {
let url = decodeURIComponent(locationSearch);
let theRequest = {};
if (url.indexOf('?') !== -1) {
let str = url.substr(1);
let strs = str.split('&');
for (let i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
}
let urlParams = Object.assign(theRequest, this.$route.query);
return urlParams;
}
}
}
};
获取code和公众号用户信息
/**
* 获取code
* @return {Object}
*/
getRequest() {
let urlParams = this.getCode(location.search);
if (urlParams.code) {
this.getWxUserInfo(urlParams.code);
} else {
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx48******de74&redirect_uri=配置的重定向地址&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
}
},
/**
* 获取公众号用户信息
* @param code
* @return {Promise<void>}
*/
async getWxUserInfo (code) {
let params = {
code,
state: '123'
};
let token = await this.$http.get(`/wechat/userInfo`, params);
this.setToken(token);
const account = await this.$http.get('/wechat/accounts');
this.setAccount(account);
window.location.href = '/';
}