微信小程式Java登入流程(ssm實現具體功能和加解密隱私資訊問題解決方案)

程式設計師歐陽思海發表於2019-03-04

文章有不當之處,歡迎指正,如果喜歡微信閱讀,你也可以關注我的微信公眾號:好好學java,獲取優質學習資源。

一、登入流程圖

20180510145856113.png

二、小程式客戶端

doLogin:function(callback = () =>{}){
let that = this;
wx.login({
  success:function(loginRes){
    if(loginRes){
      //獲取使用者資訊
      wx.getUserInfo({
        withCredentials:true,//非必填  預設為true
        success: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來換取後臺的sessionKeyopenId 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和sessionkey
            openid = 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到redis
        redisCache(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生成唯一key
        String 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){
    //微信端登入code
    String wxCode = code;
    String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
    Map<String,String> requestUrlParam = new HashMap<String, String>(  );
    requestUrlParam.put( "appid","你的小程式appId" );//小程式appId
    requestUrlParam.put( "secret","你的小程式appSecret" );
    requestUrlParam.put( "js_code",wxCode );//小程式端返回的code
    requestUrlParam.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 block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void initialize(){
        if (initialized) return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    //生成iv
    public 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

相關文章