当前位置: 首页 > 工具软件 > go-wechat-sdk > 使用案例 >

企业微信JS-SDK使用权限签名算法附实现源码

齐才艺
2023-12-01

最近做了一个企业微信接入的项目,JS-SDK使用权限签名算法附源码,觉得有用记得点赞转发,感谢!

  /*---生成验签规则开始------*/
    @Autowired
    EnterWeChatView enterWeChatView;//自定义类获取properties里面的参数

    public Map<String, String> makeWXTicket(String url) {
        String jsApiTicket = null;
        try {
            jsApiTicket = this.ewJsSdk();
            Map<String, String> ret = new HashMap<String, String>();
            String timestamp = createTimestamp();
            /*-----------------------*/
            Map<String, String> params = new HashMap<String, String>();
            params.put("jsapi_ticket", jsApiTicket);
            params.put("noncestr", getSign());
            params.put("timestamp", timestamp);
            params.put("url", url);
            //1.1 对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)
            Map<String, String> sortParams = sortAsc(params);
            //1.2 使用URL键值对的格式拼接成字符串
            String str = mapJoin(sortParams, false);

            // 获取指定摘要算法的messageDigest对象
            MessageDigest messageDigest = null; // 此处的sha代表sha1
            try {
                messageDigest = MessageDigest.getInstance("SHA");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }

            // 调用digest方法,进行加密操作
            byte[] cipherBytes = messageDigest.digest(str.getBytes());

            String cipherStr = Hex.encodeHexString(cipherBytes);
            System.out.println(cipherStr);
            ret.put("appId", enterWeChatView.getCorpid());
            ret.put("timestamp", timestamp);
            ret.put("noncestr", getSign());
            ret.put("signature", cipherStr);
            /*-----------------------*/
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private HashMap<String, String> sortAsc(Map<String, String> map) {
        HashMap<String, String> tempMap = new LinkedHashMap<String, String>();
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        //排序
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });

        for (int i = 0; i < infoIds.size(); i++) {
            Map.Entry<String, String> item = infoIds.get(i);
            tempMap.put(item.getKey(), item.getValue());
        }
        return tempMap;
    }


    public static String mapJoin(Map<String, String> map, boolean valueUrlEncode) {
        StringBuilder sb = new StringBuilder();
        for (String key : map.keySet()) {
            if (map.get(key) != null && !"".equals(map.get(key))) {
                try {
                    String temp = (key.endsWith("_") && key.length() > 1) ? key.substring(0, key.length() - 1) : key;
                    sb.append(temp);
                    sb.append("=");
                    //获取到map的值
                    String value = map.get(key);
                    //判断是否需要url编码
                    if (valueUrlEncode) {
                        value = URLEncoder.encode(map.get(key), "utf-8").replace("+", "%20");
                    }
                    sb.append(value);
                    sb.append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
 //生成时间戳
    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

 private String getSign() {
        StringBuffer str = new StringBuffer();
        str.append(Constant.CXXJW);
        str.append(String.valueOf(System.currentTimeMillis() / 1000));
        String sourceStr = Base64.getEncoder().encodeToString(str.toString().getBytes(Charset.forName("UTF-8")));
        try {
            String noncestr = DigestUtils.md5DigestAsHex(sourceStr.getBytes("UTF-8"));
            return noncestr;
        } catch (UnsupportedEncodingException e) {
            logger.error("getSign:" + e);
        }
        return null;
    }
public String ewJsSdk() throws Exception {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            String access_token = null;
            RestTemplate template = new RestTemplate();
            String url = MessageFormat.format(enterWeChatView.getUrl(), enterWeChatView.getCorpid(), enterWeChatView.getCorpsecret());
            String result = template.getForObject(url, String.class);
            if (null != result) {
                Map<String, Object> resMap = JSON.parseObject(result, Map.class);
                if (resMap.get("errcode").toString().equals("0")) {
                    System.out.println(resMap.get("access_token").toString());
                    redis.setEx(Constant.ENTER_WECHAT.join("_", "token"), resMap.get("access_token").toString(), 72000L, TimeUnit.SECONDS);
                    access_token = resMap.get("access_token").toString();
                }
            }
            return access_token;
        });
        future.join();
        System.out.println(future.get());
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            Map<String, Object> resMap = null;
            RestTemplate template = new RestTemplate();
            try {
                String url = MessageFormat.format(enterWeChatView.getEnterJsapiTicket(), future.get().toString());
                String result = template.getForObject(url, String.class);
                if (null != result) {
                    resMap = JSON.parseObject(result, Map.class);
                    if (resMap.get("errcode").toString().equals("0")) {
                        System.out.println(resMap.get("ticket").toString());
                        redis.setEx(Constant.ENTER_WECHAT.join("_", "ticket"), resMap.get("ticket").toString(), 72000L, TimeUnit.SECONDS);
                        return resMap.get("ticket").toString();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        });
        future1.join();
        System.out.println("[" + future1.get() + "]");
        return future1.get().toString();
    }


   public Map<String, Object> ewAccessToken() throws Exception {
        Map<String, Object> resMap = null;
        RestTemplate template = new RestTemplate();
        String url = MessageFormat.format(enterWeChatView.getUrl(), enterWeChatView.getCorpid(), enterWeChatView.getCorpsecret());
        String result = template.getForObject(url, String.class);
        if (null != result) {
            resMap = JSON.parseObject(result, Map.class);
            if (resMap.get("errcode").toString().equals(Constant.SUCCCODE)) {
                ridis.setEx(Constant.ENTER_WECHAT.join("_", "token"), resMap.get("access_token").toString(), 71000L, TimeUnit.SECONDS);
                return resMap;
            }
        }
        return resMap;
    }
   @Data
	@Component
	@ConfigurationProperties(prefix = "enterprise")
	public class EnterWeChatView {
	    public String corpid;
	    public String corpsecret;
	    public String url;
	    public String enterJsapiTicket;
	    public String appJsapiTicket;
XXX.properties
#企业ID
enterprise.corpid=XXXXXXX
#根据应用不同有所更改-应用的凭证密钥
enterprise.corpsecret=XXXXXXX
#获取access_token
enterprise.url=https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}
#获取企业的jsapi_ticket
enterprise.enter_jsapi_ticket=https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={0}
#获取应用的jsapi_ticket
enterprise.app_jsapi_ticket=https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token={0}&type={1}
enterprise.wechat=XXXXXXX

以上代码可以直接复制使用

 类似资料: