微信小程序与Java后台的通信

登录,在微信小程序上面称为当一个用户使用该小程序,进入到小程序中,我们拿到该用户的信息,进行一系列的操作,并记录下来。

基本思路
1.微信小程序端通过调用对应的api,将对应的变量传入后台(code、iv、encryptedData)。
2. 后台首先使用code,按照微信服务器端的传参规定,拿到对应的值,sessionKey 以及 openid 。
3. 调用成功之后,拿到openId 判断该用户是否为第一次进入小程序,如果是,不入库,相反,需要将用户的基本信息入库,基本信息从何来,就需要使用到微信小程序传入到后台的另二个变量,通过解密用户敏感信息得到,将其信息入库。
4. 入库成功后,将对应的信息放入到缓存中,我选择的缓存为redis,设置对应的过期时间,最后将生成的uuid 放入到map中,将其返回小程序中。

调用微信服务器端得到返回值:

String code = reqMap.get("code");
String url = MapUtils.getString(configProperties, "url");//请求的地址
String appId = MapUtils.getString(configProperties, "appId");//开发者对应的AppID
String appSecret = MapUtils.getString(configProperties, "appSecret");//开发者对应的AppSecret
String grant_type = MapUtils.getString(configProperties, "grant_type");
Map<String, Object> map = new HashMap<>();
map.put("appid",appId);
map.put("secret",appSecret);
map.put("js_code",code);
map.put("grant_type",grant_type);
//调用微信接口获取openId用户唯一标识
String wxReturnValue = UrlUtil.sendPost(url, map);

将其转化map,进行入库操作:

Map<String,Object> tempMap = JsonUtils.convertJson2Object(post, Map.class);
if(tempMap.containsKey("errcode")){
        String errcode = tempMap.get("errcode").toString();
        log.info("微信返回的错误码",errcode);
}
else if(tempMap.containsKey("session_key")){
         log.info("调用微信成功");
         //开始处理userInfo
         String openid = tempMap.get("openid").toString();
         WxUser wxuser = new WxUser();
         wxuser.setWopenId(openid);
         //先查询openId存在不存在,存在不入库,不存在就入库
         List<WxUser> wxUserList = wxUserMapper.selectOpenIdNum(wxuser);
         String session_key = "";
         if(wxUserList != null && wxUserList.size() > 0){
            log.info("openId已经存在,不需要插入");
         }
         else{
            log.info("openId不存在,插入数据库");
            //对encryptedData用户数据加解密
            String encryptedData = reqMap.get("encryptedData");
            String iv = reqMap.get("iv");
            session_key = tempMap.get("session_key").toString();
            Map<String,String> userMap = getUserInfo(encryptedData, session_key, iv);
            String nickName = userMap.get("nickName");
            String avatarUrl = userMap.get("avatarUrl");
            String gender = String.valueOf(userMap.get("gender"));
            String province = userMap.get("province");
            String city = userMap.get("city");
            String country = userMap.get("country");
            //创建对象,将数据插入数据库中
            WxUser newUser = new WxUser();
            String wxUserId = UUID.randomUUID().toString().replaceAll("-", "");//用户id
            newUser.setWid(wxUserId);
            newUser.setWopenId(openid);
            newUser.setWnickName(nickName);
            newUser.setWavatarUrl(avatarUrl);
            newUser.setWgender(gender);
            newUser.setWprovince(province);
            newUser.setWcity(city);
            newUser.setWcountry(country);
            Integer count1 =  wxUserMapper.insertWxUser(newUser);
        }
}
//判断缓存信息,如果存在去除掉旧的缓存信息,缓存新的对应的数据。
//生成对应的uuid 将其建立起关系,返回即可。

补全上面提到的工具类:

/*
* 解密用户敏感数据获取用户信息
*
* @param sessionKey    数据进行加密签名的密钥
* @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
* @param iv            加密算法的初始向量
* @return
*/
public static Map<String,String> getUserInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                Map<String, String> userMap = JsonUtils.convertJson2Object(result, Map.class);
                return userMap;
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidParameterSpecException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalBlockSizeException e) {
            log.error(e.getMessage(), e);
        } catch (BadPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
}

UrlUtils工具类:

/*
* 向指定 URL 发送POST方法的请求
* @param url   发送请求的 URL
* @param paramMap 请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        String param = "";
        Iterator<String> it = paramMap.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key) + "&";
        }
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {

        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
}

JsonUtils工具类:

/*
* Json转对象
* @param json
* @param type
* @param <T>
* @return
*/
public static <T> T convertJson2Object(String json, Class<T> type) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    return mapper.readValue(json, type);
}

以上便可实现登录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值