微信小程序分享群獲取群id時后端接口返回“微信AES解密失敗”,后來定位到原因是服務端用于解密的session_key失效。用戶獲取到openID存在緩存后,就不會每次login獲取登錄態了,這樣會導致登錄態失效,即后端維護的session_key失效。分享群后獲取的加密信息是老的session_key+openId構成,服務端解密時的session_key要和分享前一致。
在需要獲取openGid的頁面:
app.getOpenId(this.route, this.data.pageOptions).then((res) => { wx.login({ success(res) { // 刷新服務端session_key api.ajax('GET', api.config_url.refreshWxUserSessionKey, { appId: api.appId, code: res.code, }).then(res => { const { status, message } = res.data; if (status) { console.log('登錄態刷新成功'); } }, res => { }); } }) // 其他業務邏輯
app.js
//獲取openGid getOpenGid(shareTicket, status, callback) { var self = this; wx.getShareInfo({ shareTicket: shareTicket, complete(res) { var param = { "iv": res.iv, "encryptedData": res.encryptedData, "appId": self.appId, "openId": wx.getStorageSync("openId") }; self.getAesDecryptData(callback, param); } }); }, getAesDecryptData(callback, param) { const self = this; this.ajax('POST', this.config_url.aesDecryptData, param).then(res => { console.log(res); if (res.data.entry && res.data.entry.openGId) { wx.setStorageSync("openGId", res.data.entry.openGId); callback() && callback(); } else { console.log('獲取群id失敗'); wx.login({ success(res) { self.ajax('GET', self.config_url.refreshWxUserSessionKey, { appId: self.appId, code: res.code, }).then(res => { const { status, message } = res.data; if (status) { console.log('登錄態刷新成功'); } }, res => { }); } }); wx.removeStorageSync('openGId'); } }); },