vue + 微信獲取用戶信息
本次項目作到一個點贊功能,即分享出去一個頁面給微信好友,微信好友點開並點贊,須要將點贊用戶的微信暱稱,微信頭像以及微信openid,微信unionid(這個須要關注公衆號纔會有該字段)傳給後端,記錄點贊人的相關信息vue
微信網頁受權nginx
分享頁面的實際連接:
⚠️ 當前頁面的連接須要 encodeURIComponent( url ) 編碼json
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect // APPID: 公衆號的appid // REDIRECT_URI:當前頁面的連接,須要編碼 // scope: snsapi_base / snsapi_userinfo // 其餘值均不用改動
代碼以下segmentfault
// created 週期 if(this.$route.query.from) { // 判斷連接中是否有from參數,下面的studentId,activityId項目須要 let _nowUrl = window.location.href.split('?')[0] + `?resource=1&studentId=${this.$route.query.studentId}&activityId=${this.$route.query.activityId}` let _shareUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(_nowUrl)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect` window.location.href = _shareUrl return }
// 處理微信用戶信息 handleWechatMsg(code) { // 調取 獲取微信用戶信息的接口(後端參考微信官方文檔進行封裝) code--參數 api.getWechatInfo(code).then((res)=>{ if(res.data.code == 200) { // 返回的是json字符串 let _data = res.data.content let _personMsg = JSON.parse(_data) this.wechatMsg = _personMsg // 本地存儲微信用戶信息,防止頁面被刷新,code失效 window.localStorage.setItem('wechatMesssage', _data) } else if (res.data.code == 400) { // 400-code失效,400是後端返回,具體看後端返回哪一個碼 let msgs = window.localStorage.getItem('wechatMesssage') this.wechatMsg = JSON.parse(msgs) } else { this.$Message.message(res.data.message); } }) },
⚠️--------------------後端