微信开发unionId获取和企业微信接口调用配置签名问题总结

2020-04-09  本文已影响0人  逆水清寒

前言

一:微信的UnionID的获取问题

1:问题
2:原因
3:解决方案

二:部分用户拿不到unionId的问题

1:问题
{"phoneNumber":"15251***648","watermark":{"appid":"wx4b101b***1f6b108","timestamp":1586253485},"purePhoneNumber":"15251**648","countryCode":"86"}
2:原因:
3:解决方案:
public String getUnionId(String code,String iv,String encryptedData) {
        RestTemplate restTemplate = new RestTemplate();
        StringBuilder unionIdRequestUrl = new StringBuilder(URI_UNIONID);
        unionIdRequestUrl.append("?appid="+appid);
        unionIdRequestUrl.append("&secret="+secret);
        unionIdRequestUrl.append("&js_code="+code);
        unionIdRequestUrl.append("&grant_type=authorization_code");
        String response = restTemplate.getForObject(unionIdRequestUrl.toString(), String.class);
        Map<String, Object> result = new ObjectMapper().readValue(response, Map.class);
        String sessionKey = MapUtils.getString(result, "session_key");
        String unionId = MapUtils.getString(result, "unionId");
        // 如果没有获取到就解析前端的加密数据
        if (null != unionId) {
            String str = AES.wxDecrypt(encryptedData, sessionKey, iv);
            JSONObject obj = JSONObject.parseObject(str);
            unionId = null != obj?obj.getString("unionId"):null;
        }
        return unionId
    }

三:企业微信的签名机制和配置config获取问题

1:问题
2:原因
3:解决方案(java后端)
    //企业微信的jsapi_ticket地址
    private final static String GET_WX_TICKET = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=ACCESS_TOKEN";

    //应用tictet地址
    private final static String GET_APP_TICKET = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=ACCESS_TOKEN&type=agent_config";public Object getShareSign(@RequestBody ReqWeiXinShare req) Exception {
        // 微信唯一标识
        String appid = req.getAppid();
        // 微信调用接口凭证
        String appSecret = req.getAppSecret();
        // 分享url
        String locationUrl = req.getLocationUrl();
        if (!StringUtils.isEmpty(appid) && !StringUtils.isEmpty(appSecret)
                && !StringUtils.isEmpty(locationUrl)) {
            String accessToken = wxCpUserService.accessToken();
            Map<String,Object> resultMap = new HashMap<>();
            Map<String, String> jsApiMap = this.sign(GET_WX_TICKET, accessToken,req.getLocationUrl());
            if (null != jsApiMap) {
                resultMap.put("config_nonceStr",jsApiMap.get("nonceStr"));
                resultMap.put("config_ticket",jsApiMap.get("ticket"));
                resultMap.put("config_timestamp",jsApiMap.get("timestamp"));
                resultMap.put("config_signature",jsApiMap.get("signature"));
            }
            Map<String, String> ticketMap = this.sign(GET_APP_TICKET, accessToken,req.getLocationUrl());
            if (null != ticketMap) {
                resultMap.put("agent_nonceStr",ticketMap.get("nonceStr"));
                resultMap.put("agent_ticket",ticketMap.get("ticket"));
                resultMap.put("agent_timestamp",ticketMap.get("timestamp"));
                resultMap.put("agent_signature",ticketMap.get("signature"));
            }
            resultMap.put("appid", appid);
            resultMap.put("url", locationUrl);
            return resultMap;
        } else {
            return null;
        }
    } 
private Map<String, String> sign(String url, String accessToken,String redirectUrl) {
        String ticket = this.getTicket(url,accessToken);
        Map<String, String> ret = new HashMap<String, String>();
        String noncestr = getRandomString(16);
        String timestamp = Long.toString(System.currentTimeMillis()).substring(0,10);
        String signature = "";
        String params = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr
                + "&timestamp=" + timestamp + "&url=" + redirectUrl;
        log.info("签名返回内容:{}", params);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(params.getBytes("UTF-8"));
            signature = this.byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException var10) {
            var10.printStackTrace();
        } catch (UnsupportedEncodingException var11) {
            var11.printStackTrace();
        }
        ret.put("url", url);
        ret.put("ticket", ticket);
        ret.put("nonceStr", noncestr);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
    }
private String getTicket(String url,String accessToke) {
        String ticket = "";
        RestTemplate restTemplate = new RestTemplate();
        url = url.replace("ACCESS_TOKEN",accessToke);
        try {
            String response = restTemplate.getForObject(url, String.class);
            JSONObject demoJson = JSON.parseObject(response);
            if (demoJson.getString("errcode").equals("40001")) {
                return "error";
            }
            ticket = demoJson.getString("ticket");
            System.out.println(ticket);
        } catch (Exception var6) {
            var6.printStackTrace();
        }
        return ticket;
    }
 private static String getRandomString(int length){
        String keyString = "ergrfewfwdgggcvv;uihefujsncjdvngrjegeuirgverggvbergbvuigverug";
        int len = keyString.length();
        StringBuffer str = new StringBuffer();
        for(int i=0;i<length;i++){
            str.append(keyString.charAt((int) Math.round(Math.random() * (len - 1))));
        }
        return str.toString();
    }
private String byteToHex(byte[] hash) {
        Formatter formatter = new Formatter();
        byte[] var3 = hash;
        int var4 = hash.length;
        for (int var5 = 0; var5 < var4; ++var5) {
            byte b = var3[var5];
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

三:总结

上一篇 下一篇

猜你喜欢

热点阅读