解密微信小程序Java登录流程(ssm实现具体功能)
點(diǎn)擊上方“好好學(xué)java”,選擇“置頂公眾號”
優(yōu)秀學(xué)習(xí)資源、干貨第一時(shí)間送達(dá)!
?精彩內(nèi)容?
java實(shí)戰(zhàn)練習(xí)項(xiàng)目教程
2018微服務(wù)資源springboot、springcloud、docker、dubbo實(shí)戰(zhàn)等傾心分享
2018年java架構(gòu)師全套學(xué)習(xí)教程
最新大數(shù)據(jù)培訓(xùn)完整視頻教程
2018年java最新全套培訓(xùn)學(xué)習(xí)教程
一、登錄流程圖
這里寫圖片描述二、小程序客戶端
doLogin:function(callback?=?()?=>{}){ let?that?=?this; wx.login({success:function(loginRes){if(loginRes){//獲取用戶信息wx.getUserInfo({withCredentials:true,//非必填??默認(rèn)為truesuccess:function(infoRes){console.log(infoRes,'>>>');//請求服務(wù)端的登錄接口wx.request({url:?api.loginUrl,data:{code:loginRes.code,//臨時(shí)登錄憑證rawData:infoRes.rawData,//用戶非敏感信息signature:infoRes.signature,//簽名encrypteData:infoRes.encryptedData,//用戶敏感信息iv:infoRes.iv//解密算法的向量},success:function(res){console.log('login?success');res?=?res.data;if(res.result==0){that.globalData.userInfo?=?res.userInfo;wx.setStorageSync('userInfo',JSON.stringify(res.userInfo));wx.setStorageSync('loginFlag',res.skey);console.log("skey="+res.skey);callback();}else{that.showInfo('res.errmsg');}},fail:function(error){//調(diào)用服務(wù)端登錄接口失敗//?that.showInfo('調(diào)用接口失敗');console.log(error);}});}});}else{}} }); }微信小程序端發(fā)起登錄請求,攜帶的參數(shù)主要有:
????code:loginRes.code,//臨時(shí)登錄憑證rawData:infoRes.rawData,//用戶非敏感信息signature:infoRes.signature,//簽名encrypteData:infoRes.encryptedData,//用戶敏感信息iv:infoRes.iv//解密算法的向量參數(shù)解釋:
code:loginRes.code,//臨時(shí)登錄憑證:必傳,通過code來換取后臺的sessionKey和openId
rawData:infoRes.rawData,//用戶非敏感信息
signature:infoRes.signature,//簽名
encrypteData:infoRes.encryptedData,//用戶敏感信息
iv:infoRes.iv//解密算法的向量
signature,//簽名、encryptedData,//用戶敏感信息、iv//解密算法的向量:
這三個(gè)參數(shù)是用來解碼用戶敏感信息的,比如電話號碼等信息。
需要的數(shù)據(jù)主要有:skey,用于標(biāo)志用戶的唯一性。
三、Java后臺
/***?登陸接口*/@RequestMapping("/login")@ApiResponses({@ApiResponse(code?=?404,?message?=?"服務(wù)器未找到資源"),@ApiResponse(code?=?200,?message?=?"請求成功"),@ApiResponse(code?=?500,?message?=?"服務(wù)器錯(cuò)誤"),@ApiResponse(code?=?401,?message?=?"沒有訪問權(quán)限"),@ApiResponse(code?=?403,?message?=?"服務(wù)器拒絕訪問"),})@ApiOperation(value?=?"小程序登錄",?httpMethod?=?"POST",?notes?=?"小程序登錄")public?ResponseEntity<LoginDataResult>?login(@ApiParam(required?=?true,?value?=?"臨時(shí)登錄憑證code",?name?=?"code")?String?code,@ApiParam(required?=?true,?value?=?"用戶非敏感信息",?name?=?"rawData")@RequestParam(value?=?"rawData",?required?=?true)?String?rawData,@ApiParam(required?=?true,?value?=?"簽名",?name?=?"signature")@RequestParam(value?=?"signature",?required?=?true)?String?signature,@ApiParam(required?=?true,?value?=?"用戶敏感信息",?name?=?"encrypteData")@RequestParam(value?=?"encrypteData",?required?=?true)?String?encrypteData,@ApiParam(required?=?true,?value?=?"解密算法的向量",?name?=?"iv")@RequestParam(value?=?"iv",?required?=?true)?String?iv)?{ObjectMapper?mapper?=?new?ObjectMapper();logger.info("signature============================================================="+signature);logger.info("encrypteData=========================================================="+encrypteData);logger.info("iv========================================================================"+iv);RawData?data?=?null;WxMaJscode2SessionResult?session?=?null;String?openid?=?null;String?sessionKey?=?null;String?phoneNumber?=?null;try?{if?(rawData?!=?null?&&?!"".equals(rawData))?{//1、獲取用戶非敏感信息data?=?mapper.readValue(rawData,?RawData.class);}session?=?this.wxService.getUserService().getSessionInfo(code);//獲取到openid和sessionkeyopenid?=?session.getOpenid();sessionKey?=?session.getSessionKey();logger.info("sessionkey========================================================="+sessionKey);/*??//2、獲取用戶手機(jī)號phoneNumber?=?phone(code,?signature,?rawData,?encrypteData,?iv);logger.info("phoneNumber========================================="+phoneNumber); */}?catch?(IOException?e)?{e.printStackTrace();logger.info("獲取用戶信息失敗");LoginDataResult?loginDataResult?=?new?LoginDataResult();loginDataResult.setCode("2");loginDataResult.setMsg("請求失敗");return?ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(loginDataResult);}?catch?(WxErrorException?e)?{e.printStackTrace();logger.info("獲取用戶信息失敗");}//3、向數(shù)據(jù)庫插入用戶信息String?skey?=?insertUser(data,?openid,?phoneNumber);//4、緩存openid,?sessionKey,?skey到redisredisCache(openid,?sessionKey,?skey);//5、把新的skey返回給小程序LoginDataResult?loginDataResult?=?new?LoginDataResult();loginDataResult.setSkey(skey);loginDataResult.setCode("1");loginDataResult.setMsg("請求成功");return?ResponseEntity.status(HttpStatus.OK).body(loginDataResult);}/***?緩存openid,sessionKey,skey等信息*?@param?openid?小程序用戶唯一標(biāo)志*?@param?sessionKey?小程序會(huì)話標(biāo)志*?@param?skey?后臺生成的用戶唯一標(biāo)志,會(huì)話管理*/private?void?redisCache(String?openid,?String?sessionKey,?String?skey)?{//根據(jù)openid查詢skey是否存在String?skey_redis?=?jedisClient.hget("WEXIN_USER_OPENID_SKEY",?openid);if?(StringUtils.isNotBlank(skey_redis))?{//存在?刪除?skey?重新生成skey?將skey返回jedisClient.hdel("WEXIN_USER_OPENID_SKEY",?openid);jedisClient.hdel("WEIXIN_USER_SKEY_OPENID",?skey_redis);jedisClient.hdel("WEIXIN_USER_SKEY_SESSIONKEY",?skey_redis);}//??緩存一份新的jedisClient.hset("WEXIN_USER_OPENID_SKEY",?openid,?skey);jedisClient.expire("WEXIN_USER_OPENID_SKEY",432000);//設(shè)置5天過期jedisClient.hset("WEIXIN_USER_SKEY_OPENID",?skey,?openid);jedisClient.expire("WEIXIN_USER_SKEY_OPENID",432000);//設(shè)置5天過期jedisClient.hset("WEIXIN_USER_SKEY_SESSIONKEY",?skey,?sessionKey);jedisClient.expire("WEIXIN_USER_SKEY_SESSIONKEY",432000);//設(shè)置5天過期}/***?將用戶信息插入到數(shù)據(jù)庫*?@param?data?用戶信息*?@param?openid*?@param?phoneNumber?手機(jī)號*?@return*/private?String?insertUser(RawData?data,?String?openid,?String?phoneNumber)?{//判斷用戶數(shù)據(jù)庫是否存在,不存在,入庫。Member?user?=?userService.selectUserByOpenid(openid);//uuid生成唯一keyString?skey?=?UUID.randomUUID().toString();if?(user?==?null)?{//入庫user?=?new?Member();user.setId(skey);user.setCountry(data.getCountry());user.setCreatedate(new?Date());user.setDf(1);user.setGender(data.getGender().equals("1")???1?:?2);//1為男,2為女user.setHeadimg(data.getAvatarUrl());user.setNickname(data.getNickName());user.setOpenid(openid);user.setCitycode(data.getCity());user.setProvincecode(data.getProvince());user.setMobileno(phoneNumber);//插入到數(shù)據(jù)庫userService.insertUser(user);}?else?{//已存在logger.info("用戶openid已存在,不需要插入");return?user.getId();//返回用戶唯一標(biāo)志skey}return?skey;}/***?獲取用戶板綁定的手機(jī)號*?@param?sessionKey?小程序session*?@param?signature?簽名*?@param?rawData?用戶信息*?@param?encryptedData?小程序加密數(shù)據(jù)*?@param?iv?小程序向量*?@return*/@ApiOperation(value?=?"用戶手機(jī)號獲取",?httpMethod?=?"GET",?notes?=?"用戶手機(jī)號獲取")public?String?phone(String?sessionKey,?String?signature,?String?rawData,?String?encryptedData,?String?iv)?{String?phoneNumber?=?null;try?{byte[]?bytes?=?WxMiniappUtils.decrypt(Base64.decodeBase64(sessionKey),?Base64.decodeBase64(iv),?Base64.decodeBase64(encryptedData));String?phone?=?new?String(bytes,?"UTF8");logger.info("phone====================================="+phone);}?catch?(NoSuchPaddingException?e)?{e.printStackTrace();}?catch?(NoSuchAlgorithmException?e)?{e.printStackTrace();}?catch?(InvalidAlgorithmParameterException?e)?{e.printStackTrace();}?catch?(InvalidKeyException?e)?{e.printStackTrace();}?catch?(BadPaddingException?e)?{e.printStackTrace();}?catch?(IllegalBlockSizeException?e)?{e.printStackTrace();}?catch?(UnsupportedEncodingException?e)?{e.printStackTrace();}return?null;}下面對上面代碼進(jìn)行分析:
3.1獲取openid和sessionKey
session?=?this.wxService.getUserService().getSessionInfo(code);//獲取到openid和sessionkey openid?=?session.getOpenid(); sessionKey?=?session.getSessionKey();這段代碼是不是十分的簡潔,這里用到了一個(gè)第三方的sdk(weixin-java-tools),通過這個(gè)sdk可以非常簡便的獲取到openid和sessionKey,具體的demo。
當(dāng)然,如果你不想用第三方的sdk,也可以自己實(shí)現(xiàn),實(shí)現(xiàn)代碼如下:
public?static?JSONObject?getSessionKeyOrOpenId(String?code){//微信端登錄codeString?wxCode?=?code;String?requestUrl?=?"https://api.weixin.qq.com/sns/jscode2session";Map<String,String>?requestUrlParam?=?new?HashMap<String,?String>(??);requestUrlParam.put(?"appid","你的小程序appId"?);//小程序appIdrequestUrlParam.put(?"secret","你的小程序appSecret"?);requestUrlParam.put(?"js_code",wxCode?);//小程序端返回的coderequestUrlParam.put(?"grant_type","authorization_code"?);//默認(rèn)參數(shù)//發(fā)送post請求讀取調(diào)用微信接口獲取openid用戶唯一標(biāo)識JSONObject?jsonObject?=?JSON.parseObject(?UrlUtil.sendPost(?requestUrl,requestUrlParam?));return?jsonObject; }3.2解密用戶敏感數(shù)據(jù)獲取用戶信息
3.2.1controller
這個(gè)部分自己遇到了好多的坑,由于需要獲取用戶的手機(jī)號碼,需要解密用戶的信息。
??/***?獲取用戶板綁定的手機(jī)號*?@param?sessionKey?小程序session*?@param?signature?簽名*?@param?rawData?用戶信息*?@param?encryptedData?小程序加密數(shù)據(jù)*?@param?iv?小程序向量*?@return*/@ApiOperation(value?=?"用戶手機(jī)號獲取",?httpMethod?=?"GET",?notes?=?"用戶手機(jī)號獲取")public?String?phone(String?sessionKey,?String?signature,?String?rawData,?String?encryptedData,?String?iv)?{String?phoneNumber?=?null;try?{byte[]?bytes?=?WxMiniappUtils.decrypt(Base64.decodeBase64(sessionKey),?Base64.decodeBase64(iv),?Base64.decodeBase64(encryptedData));String?phone?=?new?String(bytes,?"UTF8");logger.info("phone====================================="+phone);}?catch?(NoSuchPaddingException?e)?{e.printStackTrace();}?catch?(NoSuchAlgorithmException?e)?{e.printStackTrace();}?catch?(InvalidAlgorithmParameterException?e)?{e.printStackTrace();}?catch?(InvalidKeyException?e)?{e.printStackTrace();}?catch?(BadPaddingException?e)?{e.printStackTrace();}?catch?(IllegalBlockSizeException?e)?{e.printStackTrace();}?catch?(UnsupportedEncodingException?e)?{e.printStackTrace();}return?null;}3.2.2decrypt工具類
這里調(diào)用了WxMiniappUtils.decrypt這個(gè)工具類,工具類如下:
?/***?解密用戶手機(jī)號算法*?@param?sessionkey?小程序登錄sessionKey*?@param?iv?向量*?@param?encryptedData*?@return*?@throws?NoSuchPaddingException*?@throws?NoSuchAlgorithmException*?@throws?InvalidAlgorithmParameterException*?@throws?InvalidKeyException*?@throws?BadPaddingException*?@throws?IllegalBlockSizeException*/public?static?byte[]?decrypt(byte[]?sessionkey,?byte[]?iv,?byte[]?encryptedData)throws?NoSuchPaddingException,?NoSuchAlgorithmException,?InvalidAlgorithmParameterException,InvalidKeyException,?BadPaddingException,?IllegalBlockSizeException?{AlgorithmParameterSpec?ivSpec?=?new?IvParameterSpec(iv);Cipher?cipher?=?Cipher.getInstance("AES/CBC/PKCS5Padding");SecretKeySpec?keySpec?=?new?SecretKeySpec(sessionkey,?"AES");cipher.init(Cipher.DECRYPT_MODE,?keySpec,?ivSpec);return?cipher.doFinal(encryptedData);}這里用到的Cipher類是 javax.crypto的類。
3.2.3問題
但是這里使用這個(gè)decrypt工具類的時(shí)候,遇到了好多的問題。
第一:AES解密是報(bào)錯(cuò)javax.crypto.BadPaddingException: pad block corrupted
這個(gè)問題是由于,工具類使用了Cipher.getInstance("AES/CBC/PKCS5Padding")。
解決:Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding");。
第二:java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16
這個(gè)問題是由于,解碼出來的iv不是16位,好像是15位,這個(gè)為什么我也不太清楚。
解決:這個(gè)怎么解決,自己也沒有找到方法,如果有大神解決,望告知!
我的解決方法:其實(shí)我發(fā)現(xiàn)這個(gè)問題并不是這個(gè)工具類的問題,我折騰了一天發(fā)現(xiàn),這個(gè)工具類并不是不能夠解碼手機(jī)號,有的是可以的,有的解析不到手機(jī)號,只有普通的信息,所以我覺得,這個(gè)可能是微信用戶注冊的時(shí)候,是不是用手機(jī)號注冊的,所以會(huì)出現(xiàn)有些能夠解析,有的不能解析。如果有大神有其他方法,望告知!
3.2.4解析成功數(shù)據(jù)
{"phoneNumber":"13880684012","purePhoneNumber":"13880684012","countryCode":"86","watermark":{"timestamp":1519460296,"appid":"wx6ede2086ee29a89f"}}如果解析到了這樣的json數(shù)據(jù),說明是成功了的。
3.2.5 另外一種方案
public?class?AES?{public?static?final?AES?instance?=?new?AES();public?static?boolean?initialized?=?false;/***?AES解密*?@param?content?密文*?@return*?@throws?InvalidAlgorithmParameterException*?@throws?NoSuchProviderException*/public?byte[]?decrypt(byte[]?content,?byte[]?keyByte,?byte[]?ivByte)?throws?InvalidAlgorithmParameterException?{initialize();try?{Cipher?cipher?=?Cipher.getInstance("AES/CBC/PKCS7Padding");Key?sKeySpec?=?new?SecretKeySpec(keyByte,?"AES");cipher.init(Cipher.DECRYPT_MODE,?sKeySpec,?generateIV(ivByte));//?初始化byte[]?result?=?cipher.doFinal(content);return?result;}?catch?(NoSuchAlgorithmException?e)?{e.printStackTrace();}?catch?(NoSuchPaddingException?e)?{e.printStackTrace();}?catch?(InvalidKeyException?e)?{e.printStackTrace();}?catch?(IllegalBlockSizeException?e)?{e.printStackTrace();}?catch?(BadPaddingException?e)?{e.printStackTrace();}?catch?(NoSuchProviderException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}?catch?(Exception?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}return?null;}public?static?void?initialize(){if?(initialized)?return;Security.addProvider(new?BouncyCastleProvider());initialized?=?true;}//生成ivpublic?static?AlgorithmParameters?generateIV(byte[]?iv)?throws?Exception{AlgorithmParameters?params?=?AlgorithmParameters.getInstance("AES");params.init(new?IvParameterSpec(iv));return?params;} }這個(gè)也會(huì)有上面的問題,有時(shí)候會(huì)解析失敗!具體方法,還在摸索中,有大神知道方法和原有,望告知!
3.2.6第三方sdk方法
WxMaPhoneNumberInfo?phoneNoInfo?=?this.wxService.getUserService().getPhoneNoInfo(sessionKey,?encryptedData,?iv);phoneNumber?=?phoneNoInfo.getPurePhoneNumber();這個(gè)也會(huì)有上面的問題出現(xiàn),有時(shí)候會(huì)解析失敗!
四、總結(jié)
1.小程序端發(fā)起請求并攜帶主要參數(shù)
2.java后臺接到/login請求后,根據(jù)code去調(diào)用微信接口獲取用戶唯一標(biāo)識openid和sessionKey
3.根據(jù)openid查詢mysql數(shù)據(jù)庫,判斷該用戶是否存在,如果不存在將用戶非敏感信息和其他初始化數(shù)據(jù)存入到數(shù)據(jù)庫中,如果已存在,不操作
4.根據(jù)openid查詢r(jià)edis數(shù)據(jù)庫,判斷openid對應(yīng)的skey是否存在,如果存在則刪除原來老的skey以及對應(yīng)的openid和sessionKey
5.通過uuid生成唯一的skey,用openid做鍵,skey做值,存入到redis中
6.然后把skey做鍵,openid和sessionKey的json串做值也重新存入到redis中
7.根據(jù)解密算法,參數(shù)有encryptedData、sessionKey和iv,獲取用戶信息userInfo,如果userInfo字段不滿足需要,可通過userInfo.put( "balance",user.getUbalance() );添加所需要的字段和值
8.將微信小程序需要的數(shù)據(jù)封裝到map中,返回給小程序端。
參考資料(感謝)
https://blog.csdn.net/abcwanglinyong/article/details/80267901
https://github.com/binarywang/weixin-java-miniapp-demo
https://www.cnblogs.com/nosqlcoco/p/6105749.html
https://www.cnblogs.com/suxiaoqi/p/7874635.html
????覺得有用就轉(zhuǎn)發(fā)分享一下吧
推薦閱讀
1.?一文springmvc入門
2.?重溫javaweb過濾器
3.?servlet就是這么簡單
4.?tomcat基本使用,就是這么簡單
附上熱門QQ群,存放資源和歷史資料,2000容量(低門檻付費(fèi)群),長按二維碼入群
總結(jié)
以上是生活随笔為你收集整理的解密微信小程序Java登录流程(ssm实现具体功能)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 重温java web过滤器filter
- 下一篇: Java线程池原理及使用