微信小程序分享群获取群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');
}
});
},