微信小程序:java后台获取openId

openId是某个微信账户对应某个小程序或者公众号的唯一标识,但openId必须经过后台解密才能获取(之前实现过前台解密,可是由于微信小程序的种种限制,前台解密无法在小程序发布后使用)

二、实现流程

1. 获取微信用户的登录信息;

2. 将encryptedData中的数据作为参数传给java后台

微信小程序:java后台获取openId

3. java后台进行解密

微信小程序:java后台获取openId

三、代码实现

1. 后台的解密代码

1 /** 2 * decoding encrypted data to get openid 3 * 4 * @param iv 5 * @param encryptedData 6 * @param code 7 * @return 8 */ 9 @RequestMapping(value = "/decodeUserInfo", method = RequestMethod.GET) 10 private Map decodeUserInfo(String iv, String encryptedData, String code) { 11 Map map = new HashMap(); 12 // login code can not be null 13 if (code == null || code.length() == 0) { 14 map.put("status", 0); 15 map.put("msg", "code 不能为空"); 16 return map; 17 } 18 // mini-Program\'s AppID 19 String wechatAppId = "你的小程序的AppID"; 20 21 // mini-Program\'s session-key 22 String wechatSecretKey = "你的小程序的session-key"; 23 24 String grantType = "authorization_code"; 25 26 // using login code to get sessionId and openId 27 String params = "appid=" + wechatAppId + "&secret=" + wechatSecretKey + "&js_code=" + code + "&grant_type=" + grantType; 28 29 // sending request 30 String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params); 31 32 // analysis request content 33 JSONObject json = JSONObject.fromObject(sr); 34 35 // getting session_key 36 String sessionKey = json.get("session_key").toString(); 37 38 // getting open_id 39 String openId = json.get("openid").toString(); 40 41 // decoding encrypted info with AES 42 try { 43 String result = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8"); 44 if (null != result && result.length() > 0) { 45 map.put("status", 1); 46 map.put("msg", "解密成功"); 47 48 JSONObject userInfoJSON = JSONObject.fromObject(result); 49 Map userInfo = new HashMap(); 50 userInfo.put("openId", userInfoJSON.get("openId")); 51 userInfo.put("nickName", userInfoJSON.get("nickName")); 52 userInfo.put("gender", userInfoJSON.get("gender")); 53 userInfo.put("city", userInfoJSON.get("city")); 54 userInfo.put("province", userInfoJSON.get("province")); 55 userInfo.put("country", userInfoJSON.get("country")); 56 userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl")); 57 userInfo.put("unionId", userInfoJSON.get("unionId")); 58 map.put("userInfo", userInfo); 59 return map; 60 } 61 62 63 } catch (Exception e) { 64 e.printStackTrace(); 65 } 66 map.put("status", 0); 67 map.put("msg", "解密失败"); 68 return map; 69 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgydxw.html