微信小程序分享群獲取群id時(shí)后端接口返回“微信AES解密失敗”,后來定位到原因是服務(wù)端用于解密的session_key失效。用戶獲取到openID存在緩存后,就不會每次login獲取登錄態(tài)了,這樣會導(dǎo)致登錄態(tài)失效,即后端維護(hù)的session_key失效。分享群后獲取的加密信息是老的session_key+openId構(gòu)成,服務(wù)端解密時(shí)的session_key要和分享前一致。
在需要獲取openGid的頁面:
app.getOpenId(this.route, this.data.pageOptions).then((res) => {
wx.login({
success(res) {
// 刷新服務(wù)端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('登錄態(tài)刷新成功');
}
}, res => { });
}
})
// 其他業(yè)務(wù)邏輯
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('登錄態(tài)刷新成功');
}
}, res => { });
}
});
wx.removeStorageSync('openGId');
}
});
},