很多时候我们产品大大会提出用户想要在微信公众号中嵌入小程序或者H5端的需求,本小白也是第一次去做这个,有些心得体会分享给大家。
首先 我们在npm上下载微信的jssdk"weixin-js-sdk": "^1.6.0"
在app.vue中引入后,调用方法
mounted() {
this.setJdk()
},
async setJdk() {
let link = /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.localStorage.getItem('scanUrl');
// console.log(link)
const {data: res} = await this.$http.post(this.api.zpURL+'/获取授权签名的接口',{jsUrl:link});
if (res.status == 1) {
localStorage.setItem('appid', res.data.wxConfig02.appid);
wx.config({
debug: false, // TODO: 测试阶段使用
appId: res.data.wxConfig02.appid,
timestamp: res.data.wxConfig02.timestamp,
nonceStr: res.data.wxConfig02.nonceStr,
signature: res.data.wxConfig02.signature,
jsApiList: [ //微信jssdk自带的方法 获取用户信息 扫码等功能
'getLocation',
'updateAppMessageShareData',
'updateTimelineShareData',
'onMenuShareAppMessage',
'onMenuShareTimeline',
'scanQRCode',
'checkJsApi',
'hideAllNonBaseMenuItem',
'hideMenuItems'
]
})
this.city()
if (!this.common.token) {
//token 为空授权
// 这样每次你进来的时候就会判断token的存在,如果近期登陆过就直接跳到界面里,不需要再去进行授权
this.wxAuthorize();
} else {
const {data: res} = await this.$http.post(this.api.tokenApi+'/请求token的接口',);
if (res.status == 1) {
this.common.userInfo = res.data
sessionStorage.setItem('user_info', JSON.stringify(res.data))
this.getInfoByopenid()
}else{
this.wxAuthorize();
}
}
}
},
// async getBytoken(obj){
// const {data: res} = await this.$http.post(this.api.tokenApi+'/byhealthOfficialAccount/getWeChatUserByToken',obj);
// console.log(res.data)
// if (res.status == 1) {
// this.common.userInfo = res.data
// sessionStorage.setItem('user_info', JSON.stringify(res.data))
// this.getInfoByopenid()
// }
// },
// 授权
async wxAuthorize() {
let code = this.getQueryString('code'); // 地址解析
// console.log(code, 'code')
if (code) {
const {data: res} = await this.$http.post(this.api.commonURL+'请求用户信息的接口',{code:code});
// console.log(res.data)
if (res.status == 1) {
this.common.token = res.data.access_token
this.common.userInfo = res.data
// console.log(this.common.token);
localStorage.setItem('token', res.data.access_token)
sessionStorage.setItem('user_info', JSON.stringify(res.data))
this.getInfoByopenid()
}
} else {
let appid = localStorage.getItem('appid') || null
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid +
'&redirect_uri=http://打包后你自己的线上地址' + '&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect';
}
},