当前位置:   article > 正文

微信小程序获取openid、sessionKey及授权获取手机号码等信息_微信登录前后端根据openid 手机号

微信登录前后端根据openid 手机号

1.最近在开发小程序的项目中,服务端需要配合前端获取当前用户与微信绑定的手机号;需要以下两步:
1.1根据前端所传的code通过服务端调微信接口获取openId,sessionkey;
1.2根据前端所传的encrypdata,ivdata,sessionKey服务端进行解密后得到手机号

2.登录根绝凭证appId和appSecret校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程,然后后端通过code值调用微信的API地址   获取openId和sessionkey信息     然后前端页面通过点击授权按钮触(encrypdata、ivdata,sessionKey)调用后端接口进行解密获取授权用户信息

3.开发流程如下   首先在配置文件里面配置appId和appSecret   如下图:

4.获取微信openId sessionKey工具类   代码如下:

  1. package com.longjin.wechat.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.impl.client.HttpClientBuilder;
  9. import org.apache.http.util.EntityUtils;
  10. /**
  11. * 请求微信小程序 api
  12. */
  13. public class WeChatMiniClient {
  14. /**
  15. * 请求微信小程序api 获取 openId,session_key
  16. *
  17. * @param code wx.login返回 code值
  18. * @param appId 小程序 appId
  19. * @param appSecret 小程序 appSecret
  20. * @return
  21. */
  22. public static JSONObject feighMini(String code, String appId, String appSecret) {
  23. //拼接url
  24. StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
  25. url.append("appid=");//appId设置
  26. url.append(appId);
  27. url.append("&secret=");//secret设置
  28. url.append(appSecret);
  29. url.append("&js_code=");//code设置
  30. url.append(code);
  31. url.append("&grant_type=authorization_code"); //值固定
  32. JSONObject jsonObject = new JSONObject();
  33. try {
  34. HttpClient client = HttpClientBuilder.create().build();//构建一个Client
  35. HttpGet get = new HttpGet(url.toString()); //构建一个GET请求
  36. HttpResponse response = client.execute(get);//提交GET请求
  37. HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
  38. String content = EntityUtils.toString(result);
  39. jsonObject = JSON.parseObject(content);
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. return jsonObject;
  44. }
  45. }

 

5.调用工具类获取到sessionkey和openid放入redis中   等前端点用户授权之后和encrypdata、ivdata一起传过来,注意这里不要直接把sessionkey直接放到sessionkey放到接口中返到前端,sessionkey属于私密信息  我这里是保存到redis中  代码如下:

  1. public Map<String, Object> loginAuto(String code) throws Exception {
  2. Map<String, Object> map = new HashMap<>();
  3. //请求小程序api
  4. JSONObject jsonObject = WeChatMiniClient.feighMini(code, caseAppId, caseAppSecret);
  5. Map<String, Object> tempMap = AllJsonUtils.convertJson2Object(jsonObject, Map.class);
  6. //包含错误码
  7. if (tempMap.containsKey("errcode")) {
  8. String errCode = tempMap.get("errcode").toString();
  9. //错误 非法请求
  10. //系统返回msg,携带英文
  11. String sysMsg = tempMap.get("errmsg").toString();
  12. map.put("errorCode", errCode);
  13. map.put("errorMsg", MiniConstants.getMsg(errCode, sysMsg));
  14. } else if (tempMap.containsKey("session_key")) {
  15. //获取用户唯一标识
  16. String openId = tempMap.get("openid").toString();
  17. map.put("openId",openId);
  18. //将openId与sessionKey关联 放入缓存中
  19. redisUtil.setex(openId, tempMap.get("session_key").toString(), Contents.appRedisLoginTimeOut, Contents.userIndexdb);
  20. }
  21. return map;
  22. }

 

6.点击授权获取手机号码  代码如下:

/**
     *  <desc>
     *      解密与微信绑定的手机号
     *  </desc>
     *
     * @param encrypdata 微信参数
     * @param ivdata 微信参数
     * @param sessionKey 会话密钥
     * @return
     * @createDate 2018/11/24
     */
    @RequestMapping(path = "/getPhoneNum",method = RequestMethod.POST)
    @ResponseBody
    public MessageVO getPhoneNum(String encrypdata,String ivdata,String sessionKey){
        try {
            if(StringUtils.isEmpty(encrypdata) || StringUtils.isEmpty(ivdata) || StringUtils.isEmpty(sessionKey)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            byte[] encrypData = Base64.decode(encrypdata);
            byte[] ivData = Base64.decode(ivdata);
            byte[] sessionKeyByte = Base64.decode(sessionKey);
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            //解析解密后的字符串 
            String phoneNum = new String(cipher.doFinal(encrypData),"UTF-8");

           JSONObject jsonObjects = JSONObject.parseObject(json); 

         String phoneNumber = jsonObjects.getString("phoneNumber");//用户手机号

            return  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),phoneNum);
        }catch (Exception e){
            throw new DataAccessException("【小程序_注册登录版块】解密与微信绑定的手机号失败",e);
        }
    }

7.以上就是获取授权之后的用户手机号码    令附上项目中实际应用  代码如下:
 

  1. @Override
  2. public ResultsCode saveUserInfo(GlobalUser globalUser){
  3. try {
  4. String sessionKey = "";
  5. sessionKey = redisUtil.get(globalUser.getOpenId(), Contents.userIndexdb);
  6. //sessionKey查询不到查数据库
  7. if(StringUtils.isBlank(sessionKey)){
  8. VipThirdAccountUser vipThirdAccountUser = vipThirdAccountUserDao.findByAccountId(globalUser.getOpenId());
  9. sessionKey = vipThirdAccountUser.getAccountKey();
  10. }
  11. byte[] encrypData = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(globalUser.getEncryptedData());
  12. byte[] ivData = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(globalUser.getIv());
  13. byte[] sessionKeyByte = Base64.decode(sessionKey);
  14. AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
  15. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  16. SecretKeySpec keySpec = new SecretKeySpec(sessionKeyByte, "AES");
  17. cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
  18. //解析解密后的字符串
  19. String json = new String(cipher.doFinal(encrypData),"UTF-8");
  20. JSONObject jsonObjects = JSONObject.parseObject(json);
  21. String phoneNumber = jsonObjects.getString("phoneNumber");
  22. //通过openId查询
  23. VipThirdAccountUser vipThirdAccountUser = vipThirdAccountUserDao.findByAccountId(globalUser.getOpenId());
  24. Map<String,Object> map = new HashMap<>();
  25. //没有对应数据 加入用户数据
  26. if (null == vipThirdAccountUser) {//新用户
  27. globalUser.setAccountId(globalUser.getOpenId());
  28. globalUser.setPhone(phoneNumber);
  29. globalUser.setAccountKey(sessionKey);
  30. addUserInfo(globalUser);
  31. } else {//老用户
  32. String username = vipThirdAccountUser.getUsername();
  33. GlobalUser byUserName = globalUserDao.findByUserName(username);
  34. if (null != byUserName) {
  35. doCommon(map, byUserName, globalUser.getOpenId());
  36. return ResultsCode.success(map);
  37. }
  38. }
  39. }catch (Exception e){
  40. return ResultsCode.Fail();
  41. }
  42. return ResultsCode.success();
  43. }
  44. /**
  45. * 设置公共部分
  46. */
  47. public void doCommon(Map<String, Object> map, GlobalUser globalUser, String openId) {
  48. //判断是否存在对应key
  49. boolean loginExist = redisUtil.exists(SysStringUtils.md5(globalUser.getUsername() + "mini"), Contents.userIndexdb);
  50. if (loginExist) {
  51. String oldToken = redisUtil.get(SysStringUtils.md5(globalUser.getUsername() + "mini"), Contents.userIndexdb);
  52. redisUtil.del(Contents.userIndexdb, oldToken);
  53. }
  54. GlobalUserExt globalUserExt = globalUserExtDao.findByUserId(globalUser.getUserId().toString());
  55. globalUser.setNickname(globalUserExt.getNickname());
  56. globalUser.setImagePath(globalUserExt.getImagePath());
  57. globalUser.setWeixinId(globalUserExt.getWeixinId());
  58. map.put("globalUser", globalUser);
  59. String token = TokenUtils.getToken(globalUser.getUserId().toString(), globalUser.getUsername(), SysStringUtils.md5(globalUser.getUsername() + "caseMini"), globalUser.getUserId().toString());
  60. map.put("token", token);
  61. map.put("openId", openId);
  62. //将生成的token存入Redis中
  63. redisUtil.setex(token, token, Contents.appRedisLoginTimeOut, Contents.userIndexdb);
  64. redisUtil.setex(SysStringUtils.md5(globalUser.getUsername() + "mini"), token, Contents.appRedisLoginTimeOut, Contents.userIndexdb);
  65. AdminRole role = new AdminRole();
  66. role.setUserId(globalUser.getUserId());
  67. List<AdminRole> roleList = roleManageService.getRoleList(role);
  68. map.put("roleList", roleList);
  69. //获取角色全部菜单资源列表
  70. List<AdminMenu> adminMenuList = new ArrayList<>();
  71. if (null != roleList && roleList.size() != 0) {
  72. for (AdminRole r : roleList) {
  73. List<AdminMenu> roleMenuList = roleManageService.getRoleMenuList(r.getRoleId());
  74. adminMenuList.addAll(roleMenuList);
  75. }
  76. }
  77. map.put("adminMenuList",adminMenuList);
  78. String uid = globalUser.getUserId().toString();
  79. new Thread() {
  80. @Override
  81. public void run() {
  82. if (StringUtils.isNotBlank(uid)) {
  83. globalUserDao.updateStatus(uid);
  84. }
  85. }
  86. }.start();
  87. }
  88. /**
  89. * 添加用户信息
  90. *
  91. * @param globalUser
  92. */
  93. public void addUserInfo(GlobalUser globalUser){
  94. //用户统一信息添加
  95. String userId = StringStrUtils.getUUID();
  96. globalUser.setSource(NumberEnum.FIRST.code());
  97. globalUser.setMobile(globalUser.getPhone());
  98. globalUser.setUsername(globalUser.getPhone());
  99. globalUser.setCreateType(NumberEnum.SECOND.code());
  100. globalUser.setUserId(userId);
  101. globalUserDao.save(globalUser);
  102. //会员用户添加
  103. VipMemberUser vipMemberUser = new VipMemberUser();
  104. vipMemberUser.setUserId(userId);
  105. Integer memberId = vipMemberUserDao.save(vipMemberUser);
  106. //三方授权登录添加
  107. VipThirdAccountUser vipThirdAccountUser = new VipThirdAccountUser();
  108. vipThirdAccountUser.setMemberId(memberId);
  109. vipThirdAccountUser.setSource(globalUser.getThirdAccountSource());
  110. vipThirdAccountUser.setAccountId(globalUser.getAccountId());
  111. vipThirdAccountUser.setAccountKey(globalUser.getAccountKey());
  112. vipThirdAccountUser.setUserId(userId);
  113. vipThirdAccountUser.setUsername(globalUser.getPhone());
  114. vipThirdAccountUserDao.save(vipThirdAccountUser);
  115. AdminRole role = new AdminRole();
  116. role.setAppId("PA-PLATFORM-XH");
  117. role.setRoletypeId("R32");
  118. role.setName("市民");
  119. role.setCode("CITIZEN");
  120. role.setPriority(NumberEnum.FIVE.code());
  121. role.setIsRegular(NumberEnum.FIRST.code());
  122. role.setIsSuper(NumberEnum.ZERO.code());
  123. role.setIsPublic(NumberEnum.ZERO.code());
  124. role.setStatus(NumberEnum.FIRST.code());
  125. role.setDescription("市民");
  126. role.setUserId(userId);
  127. Integer roleId = roleManageService.add(role);
  128. //会员用户组
  129. SasMemberGroup sasMemberGroup = new SasMemberGroup();
  130. sasMemberGroup.setRoleId(roleId);
  131. sasMemberGroup.setName("市民");
  132. sasMemberGroup.setCode("CITIZEN");
  133. sasMemberGroup.setIsCommonGroup(NumberEnum.FIRST.code());
  134. sasMemberGroup.setIsLeaderGroup(NumberEnum.ZERO.code());
  135. sasMemberGroup.setIsGridGroup(NumberEnum.ZERO.code());
  136. sasMemberGroup.setIsPartyGroup(NumberEnum.ZERO.code());
  137. sasMemberGroup.setIsWorkGroup(NumberEnum.ZERO.code());
  138. sasMemberGroup.setIsVillageGroup(NumberEnum.ZERO.code());
  139. sasMemberGroup.setIsDisabled(NumberEnum.ZERO.code());
  140. sasMemberGroup.setPriority(NumberEnum.FIRST.code());
  141. sasMemberGroup.setDescription("市民");
  142. Integer groupId = sasMemberGroupDao.add(sasMemberGroup);
  143. //添加用户组关联
  144. SasMemberGroupUser sasMemberGroupUser = new SasMemberGroupUser();
  145. sasMemberGroupUser.setGroupId(groupId);
  146. sasMemberGroupUser.setMemberId(memberId);
  147. sasMemberGroupUserDao.add(sasMemberGroupUser);
  148. //添加用户基本信息
  149. GlobalUserExt globalUserExt = new GlobalUserExt();
  150. globalUserExt.setUserId(userId);
  151. globalUserExt.setNickname(globalUser.getNickname());
  152. globalUserExt.setWeixinId(globalUser.getWeixinId());
  153. globalUserExt.setImagePath(globalUser.getImagePath());
  154. globalUserExtDao.save(globalUserExt);
  155. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/284682?site
推荐阅读
相关标签
  

闽ICP备14008679号