微信小程序Java登录流程(ssm实现具体功能和问题解决方案)
一、登錄流程圖
二、小程序客戶端
doLogin:function(callback = () =>{}){ let that = this; wx.login({success:function(loginRes){if(loginRes){//獲取用戶信息wx.getUserInfo({withCredentials:true,//非必填 默認為truesuccess:function(infoRes){console.log(infoRes,'>>>');//請求服務端的登錄接口wx.request({url: api.loginUrl,data:{code:loginRes.code,//臨時登錄憑證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){//調用服務端登錄接口失敗// that.showInfo('調用接口失敗');console.log(error);}});}});}else{}} }); }微信小程序端發起登錄請求,攜帶的參數主要有:
code:loginRes.code,//臨時登錄憑證rawData:infoRes.rawData,//用戶非敏感信息signature:infoRes.signature,//簽名encrypteData:infoRes.encryptedData,//用戶敏感信息iv:infoRes.iv//解密算法的向量參數解釋:
code:loginRes.code,//臨時登錄憑證:必傳,通過code來換取后臺的sessionKey和openId
rawData:infoRes.rawData,//用戶非敏感信息
signature:infoRes.signature,//簽名
encrypteData:infoRes.encryptedData,//用戶敏感信息
iv:infoRes.iv//解密算法的向量
signature,//簽名、encryptedData,//用戶敏感信息、iv//解密算法的向量:
這三個參數是用來解碼用戶敏感信息的,比如電話號碼等信息。
需要的數據主要有:skey,用于標志用戶的唯一性。
三、Java后臺
/*** 登陸接口*/@RequestMapping("/login")@ApiResponses({@ApiResponse(code = 404, message = "服務器未找到資源"),@ApiResponse(code = 200, message = "請求成功"),@ApiResponse(code = 500, message = "服務器錯誤"),@ApiResponse(code = 401, message = "沒有訪問權限"),@ApiResponse(code = 403, message = "服務器拒絕訪問"),})@ApiOperation(value = "小程序登錄", httpMethod = "POST", notes = "小程序登錄")public ResponseEntity<LoginDataResult> login(@ApiParam(required = true, value = "臨時登錄憑證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、獲取用戶手機號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、向數據庫插入用戶信息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 小程序用戶唯一標志* @param sessionKey 小程序會話標志* @param skey 后臺生成的用戶唯一標志,會話管理*/private void redisCache(String openid, String sessionKey, String skey) {//根據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);//設置5天過期jedisClient.hset("WEIXIN_USER_SKEY_OPENID", skey, openid);jedisClient.expire("WEIXIN_USER_SKEY_OPENID",432000);//設置5天過期jedisClient.hset("WEIXIN_USER_SKEY_SESSIONKEY", skey, sessionKey);jedisClient.expire("WEIXIN_USER_SKEY_SESSIONKEY",432000);//設置5天過期}/*** 將用戶信息插入到數據庫* @param data 用戶信息* @param openid* @param phoneNumber 手機號* @return*/private String insertUser(RawData data, String openid, String phoneNumber) {//判斷用戶數據庫是否存在,不存在,入庫。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);//插入到數據庫userService.insertUser(user);} else {//已存在logger.info("用戶openid已存在,不需要插入");return user.getId();//返回用戶唯一標志skey}return skey;}/*** 獲取用戶板綁定的手機號* @param sessionKey 小程序session* @param signature 簽名* @param rawData 用戶信息* @param encryptedData 小程序加密數據* @param iv 小程序向量* @return*/@ApiOperation(value = "用戶手機號獲取", httpMethod = "GET", notes = "用戶手機號獲取")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.1獲取openid和sessionKey
session = this.wxService.getUserService().getSessionInfo(code);//獲取到openid和sessionkey openid = session.getOpenid(); sessionKey = session.getSessionKey();這段代碼是不是十分的簡潔,這里用到了一個第三方的sdk(weixin-java-tools),通過這個sdk可以非常簡便的獲取到openid和sessionKey,具體的demo。
當然,如果你不想用第三方的sdk,也可以自己實現,實現代碼如下:
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" );//默認參數//發送post請求讀取調用微信接口獲取openid用戶唯一標識JSONObject jsonObject = JSON.parseObject( UrlUtil.sendPost( requestUrl,requestUrlParam ));return jsonObject; }3.2解密用戶敏感數據獲取用戶信息
3.2.1controller
這個部分自己遇到了好多的坑,由于需要獲取用戶的手機號碼,需要解密用戶的信息。
/*** 獲取用戶板綁定的手機號* @param sessionKey 小程序session* @param signature 簽名* @param rawData 用戶信息* @param encryptedData 小程序加密數據* @param iv 小程序向量* @return*/@ApiOperation(value = "用戶手機號獲取", httpMethod = "GET", notes = "用戶手機號獲取")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工具類
這里調用了WxMiniappUtils.decrypt這個工具類,工具類如下:
/*** 解密用戶手機號算法* @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問題
但是這里使用這個decrypt工具類的時候,遇到了好多的問題。
第一:AES解密是報錯javax.crypto.BadPaddingException: pad block corrupted
這個問題是由于,工具類使用了Cipher.getInstance("AES/CBC/PKCS5Padding")。
解決:Cipher cipher = Cipher.getInstance(“AES/ECB/ZeroBytePadding”);。
第二:java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16
這個問題是由于,解碼出來的iv不是16位,好像是15位,這個為什么我也不太清楚。
解決:這個怎么解決,自己也沒有找到方法,如果有大神解決,望告知!
我的解決方法:其實我發現這個問題并不是這個工具類的問題,我折騰了一天發現,這個工具類并不是不能夠解碼手機號,有的是可以的,有的解析不到手機號,只有普通的信息,所以我覺得,這個可能是微信用戶注冊的時候,是不是用手機號注冊的,所以會出現有些能夠解析,有的不能解析。如果有大神有其他方法,望告知!
3.2.4解析成功數據
{"phoneNumber":"13880684012","purePhoneNumber":"13880684012","countryCode":"86","watermark":{"timestamp":1519460296,"appid":"wx6ede2086ee29a89f"}}如果解析到了這樣的json數據,說明是成功了的。
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;} }這個也會有上面的問題,有時候會解析失敗!具體方法,還在摸索中,有大神知道方法和原有,望告知!
3.2.6第三方sdk方法
WxMaPhoneNumberInfo phoneNoInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);phoneNumber = phoneNoInfo.getPurePhoneNumber();這個也會有上面的問題出現,有時候會解析失敗!
四、總結
1.小程序端發起請求并攜帶主要參數
2.java后臺接到/login請求后,根據code去調用微信接口獲取用戶唯一標識openid和sessionKey
3.根據openid查詢mysql數據庫,判斷該用戶是否存在,如果不存在將用戶非敏感信息和其他初始化數據存入到數據庫中,如果已存在,不操作
4.根據openid查詢redis數據庫,判斷openid對應的skey是否存在,如果存在則刪除原來老的skey以及對應的openid和sessionKey
5.通過uuid生成唯一的skey,用openid做鍵,skey做值,存入到redis中
6.然后把skey做鍵,openid和sessionKey的json串做值也重新存入到redis中
7.根據解密算法,參數有encryptedData、sessionKey和iv,獲取用戶信息userInfo,如果userInfo字段不滿足需要,可通過userInfo.put( “balance”,user.getUbalance() );添加所需要的字段和值
8.將微信小程序需要的數據封裝到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
總結
以上是生活随笔為你收集整理的微信小程序Java登录流程(ssm实现具体功能和问题解决方案)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql:Column id cann
- 下一篇: 微信小程序Java登录流程(ssm实现具