小程序获取个人信息、和群信息,后台解密返回信息

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40670946/article/details/82843879

场景描述:

1.微信目前是需要点击按钮获取权限,然后个人信息(头像、昵称)
2.获取用户的openId更多信息
3.分享到群的时候,可以获得群的openGId,然后显示群的昵称

注意问题:app.js中通过后台获取用户更多的信息时,因为异步,很多时候将后台用户信息通过this.setDate(),this拿不到报错,解决方法:
1.回调函数callback(获取群openGid时,会用到)
2.下面的例子在,index中获取值然后设置值

1.个人信息获取的代码:

在这里插入图片描述
在这里插入图片描述

index.wxml

<view class="container">
  <view class="userinfo">
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
</view>

index.wxss

.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}

index.js

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
      app.globalData.isRefresh = true;
      console.log("getUserInfo()==>>是否成功:" + app.globalData.isRefresh);
      //微信授权后调用请求后台用户信息
      this.AllUserInfo();
    } else {
      wx.showModal({
        title: '授权提示',
        content: '您点击了拒绝授权,将无法正常使用本小程序的功能体验。如想使用本小程序,请再次点击。',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
    }
  },
  AllUserInfo: function () {
    var that = this;
    // 获取后台的用户信息
    wx.login({
      success: function (res) {
        console.log("AllUserInfo()==>>res.code:" + res.code); //五分钟的code,发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.getUserInfo({
          withCredentials: true,
          success: function (res_user) {
            wx.request({
              url: 'http://xxx',//自己的后台域名
              method: "GET",
              data: {
                code: res.code, //上面wx.login()成功获取到的code
                encryptedData: res_user.encryptedData,
                iv: res_user.iv
              },
              header: {
                'content-type': 'application/json' //默认值
              },
              success: function (res) {
                console.log("index.js>>AllUserInfo()返回信息");
                console.log(res);
                if (res.data.status == 1) {
                  var userInfo_ = res.data.userInfo;
                  app.globalData.userInfo = res.data.userInfo;
                  //这里将用户的信息存储在本地中,方便其他页面调用
                  that.setData({
                    userInfo: userInfo_,
                  })
                  console.log('解密成功');
                } else {
                  console.log('解密失败');
                }
              }
            })
          }
        })
      }
    })
  },
})

app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null
  }
})

授权之后,后台解密信息返回
在这里插入图片描述

java+ssm后台解密:https://blog.csdn.net/abgglive/article/details/80666807
php:https://www.cnblogs.com/haifengliang/p/7998868.html

2.openGId获取群信息代码:

因为写了篇分享的文章:这里就不累赘了:先看分享文章:https://blog.csdn.net/qq_40670946/article/details/82843061
也可以自己去找AES解密包

添加1:
app.js中“分享成功”处插入代码:
//调用获取群id方法
  wx.login({
     success: function(result) {
        var s = vm;
        wx.request({
          url: 'http://xxx',//自己的后台域名
          method: "GET",
          data: {
            code: result.code,
            encryptedData: res.encryptedData,
            iv: res.iv
          },
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function(res) {
            console.log("后台接口返回信息:");
            console.log(res);
            if (res.data.status == 1) {
              console.log('解密成功');
              if (app.openGIdCallback) {
                app.openGIdCallback(res);
              }
            } else {
              console.log('解密失败');
            }
          }
        })
      }
    })


java后台接口修改为:
@ResponseBody
    @RequestMapping(value = "/getOpenGid", method = RequestMethod.GET)
    public Map getOpenGid(String encryptedData, String iv, String code) {
        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "xxx";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "xxx";
        //授权(必填)
        String grant_type = "authorization_code";

        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容(转换成json对象)
        JSONObject json = JSONObject.fromObject(sr);
        //获取会话密钥(session_key)
        String session_key = json.get("session_key").toString();
        //用户的唯一标识(openid)
        String openid = (String) json.get("openid");

        //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
        try {
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");
                JSONObject resultInfo = JSONObject.fromObject(result);
               map.put("resData",resultInfo);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        return map;
    }

注意:wxspAppid 和创建微信小程序的appid相同解密成功,如果要其他小伙伴测试解密的话,
1.需要将小伙伴添加为“体验者”,
2.小伙伴下拉项目时创建的项目appid为你的appid即可

添加2:
app.js中setInfo方法获得app实例(因为在wx.login下app.openGIdCallback换成this.openGIdCallback),会找不到this,导致报错

在这里插入图片描述

添加3:
index.wxml中增加代码:

<open-data id="groupName" type="groupName" open-gid="{{openGId}}"></open-data>
添加4:
index.js中:
     1.data数据增加代码:
         openGId: 0, //群id
     2.onLoad方法增加:
       //分享群信息回调函数
	    app.openGIdCallback = res => {
	      console.log("群信息出来了吗?");
	      console.log(res);
	      this.setData({
	        openGId: res.data.resData.openGId,
	      });
	    }

群的昵称信息会显示在open-data组件中;并不会和openGid一起返回!!

到这里就结束了,希望对你有用,能力有限,不对的地方请小伙伴们指正!

猜你喜欢

转载自blog.csdn.net/qq_40670946/article/details/82843879
今日推荐