微信小程序分享群获取群 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');
- }
- });
- },
来源: https://www.cnblogs.com/jikaiyang/p/9049918.html