Sign in micro-letters, including access unionid, no authentication

1, to the WeChat open platform registered account, then associate applet
Associated applet example
2, the applet access to relevant parameters, submit to your own server backstage
after the following operations that require user authorization:

wx.login({
  success (res) {  
    if (res.code) {
      //获取到code(用户登录凭证)
       wx.getUserInfo({
         success: function(resp) {
           //获取到encryptedData(加密数据)和iv(偏移量)
           //发起网络请求,将code、encryptedData和iv都提交到自己服务器后台
           wx.request({
            url: 'https://test.com/onLogin',
            data: {
              code: res.code,
              encryptedData: resp.encryptedData,
              iv: resp.iv
            }
          })
         }
       })      
    } else {
      console.log('登录失败!' + res.errMsg)
    }
  }
})

3, obtained by code SessionKey (do your own server-side)
take parameters provided by the applet code to request the following links for the access_token:
https://api.weixin.qq.com/sns/oauth2/jscode2session?appid=APPID&secret=SECRET&js_code = CODE & grant_type = authorization_code
parameter Description

parameter Do you have to Explanation
appid Yes After applying unique identification, submission of application for approval in the WeChat open platform to obtain
secret Yes    Application key AppSecret, submit applications through the audit in WeChat open platform
code Yes   Fill in code parameters acquired first step
grant_type Yes   填authorization_code
@Override
public String getSessionKey(String appid, String appSecret, String code) {
    try {
        String pattern = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&grant_type=authorization_code&js_code=%s";
        String url = String.format(Locale.ENGLISH, pattern, appid, appSecret, code);
        ConvertedResponse<String> response = EasyHttp.executeGet(url, new StringResponseConverter());
        if (response.convertedResponse != null) {
            log.debug(response.convertedResponse);
            JSONObject jsonObject = JSON.parseObject(response.convertedResponse);
            return jsonObject.getString("session_key");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Correctly returns:

{
    "errcode":0,
    "errmsg":"",
    "openid":"OPEN_ID",
    "session_key":"SESSION_KEY",
    "uin":"",
    "unionid":"UNION_ID"
}

4, to decrypt the user information
on the step has been to get unionId, now provided by the previous step SessionKey and applets encryptedData and iv to decrypt, obtain user information, if correct decryption, the entire third-party registration is completed, the decryption fails the login fails.

@Override
public String decryptUserInfo(String encryptedData, String iv, String sessionKey) {
    try {
        byte[] data = Base64.decodeBase64(encryptedData);
        byte[] aseKey = Base64.decodeBase64(sessionKey);
        byte[] ivData = Base64.decodeBase64(iv);
        // 如果密钥不足16位,那么就补足
        int base = 16;
        if (aseKey.length % base != 0) {
            int groups = aseKey.length / base + 1;
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(aseKey, 0, temp, 0, aseKey.length);
            aseKey = temp;
        }
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        SecretKeySpec spec = new SecretKeySpec(aseKey, "AES");
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(ivData));
        cipher.init(Cipher.DECRYPT_MODE, spec, params);
        byte[] result = cipher.doFinal(data);
        String info = new String(result, StandardCharsets.UTF_8);
        log.debug(info);
        return info;
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        return null;
    }
}

Correct decryption result:

{
  "openId": "OPENID",
  "nickName": "NICKNAME",
  "gender": GENDER,
  "city": "CITY",
  "province": "PROVINCE",
  "country": "COUNTRY",
  "avatarUrl": "AVATARURL",
  "unionId": "UNIONID",
  "watermark": {
    "appid":"APPID",
    "timestamp":TIMESTAMP
  }
}

A micro-channel sweep the experience:

Experience a

Guess you like

Origin www.cnblogs.com/wandersnail/p/12356596.html