package com.zy.kingdee.utils; import cn.hutool.http.HttpRequest; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.core.common.Cools; import com.smecloud.apigw.client.ApigwClient; import com.smecloud.apigw.codec.GwURLEncoder; import com.smecloud.apigw.constant.HttpMethod; import com.smecloud.apigw.exception.ApiException; import com.smecloud.apigw.model.ApiRequest; import com.smecloud.apigw.model.ApigwConfig; import com.smecloud.apigw.util.CommontUtil; import com.smecloud.apigw.util.SHAUtil; import com.zy.kingdee.entity.*; import lombok.SneakyThrows; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.*; import java.util.stream.Collectors; public class K3ApiUtil { private static final String clientId = "320285"; private static final String clientSecret = "bd29825057688ef40b1154057961a13b"; private static final String HOST = "api.kingdee.com"; private static final String instanceId = "436582290097836032"; private static final String appKey = "KidEvrK8"; private static final String[] DEFAULT_SIGNHEADERS = new String[]{"X-Api-Nonce", "X-Api-TimeStamp"}; public static ResParam TokenRes = null; public static ResParam userRes = null; public static String authCode = null; public static String sessionId = null; public static AcctDto acctDto = null; public static GatewayDto gatewayDto = null; /** * 获取Nonce * * @param len * @return */ public static String getNonce(int len) { StringBuilder rs = new StringBuilder(); for (int i = 0; i < len; ++i) { rs.append(new SecureRandom().nextInt(10)); } return rs.toString(); } /** * 获取url转码格式 * * @param path * @return */ private static String getPathEncode(String path) { try { return GwURLEncoder.encode(path, StandardCharsets.UTF_8.toString()); } catch (Exception var3) { Exception e = var3; throw new ApiException(e); } } /** * 获取拼接参数转码格式 * * @param querys * @return */ private static String getQueryEncode(Map querys) { try { if (CommontUtil.isEmpty(querys)) { return ""; } else { List list = new ArrayList(querys.size()); Iterator var3 = querys.entrySet().iterator(); while (var3.hasNext()) { Map.Entry entry = (Map.Entry) var3.next(); String key = GwURLEncoder.encode((String) entry.getKey(), StandardCharsets.UTF_8.toString()); String value = URLEncoder.encode((String) entry.getValue(), StandardCharsets.UTF_8.toString()); list.add(key + "=" + value); } Collections.sort(list); String rawQueryString = String.join("&", list); String[] queryStrings = rawQueryString.split("&"); list.clear(); String[] var16 = queryStrings; int var17 = queryStrings.length; for (int var7 = 0; var7 < var17; ++var7) { String param = var16[var7]; int index = param.indexOf("="); if (index >= 1) { String key = GwURLEncoder.encode(param.substring(0, index), StandardCharsets.UTF_8.toString()); String value = GwURLEncoder.encode(param.substring(index + 1), StandardCharsets.UTF_8.toString()); list.add(key + "=" + value); } } return String.join("&", list); } } catch (Exception var12) { Exception e = var12; throw new ApiException(e); } } /** * 获取加密签名 * * @param method * @param path * @param query * @param signatureHeaders * @param headers * @return */ private static String getSign(String method, String path, String query, String[] signatureHeaders, Map headers) { StringBuilder b = new StringBuilder(); b.append(method); b.append("\n"); b.append(path); b.append("\n"); b.append(query); b.append("\n"); String[] var7 = signatureHeaders; int var8 = signatureHeaders.length; for (int var9 = 0; var9 < var8; ++var9) { String x = var7[var9]; b.append(x.toLowerCase()); b.append(":"); b.append((String) headers.get(x)); b.append("\n"); } String s = SHAUtil.SHA256HMAC(b.toString(), clientSecret); return s != null ? Base64.getEncoder().encodeToString(s.getBytes()) : ""; } /** * 获取加密后结果 * * @return */ public static String getSecretStr(String key, String secret) { String s = SHAUtil.SHA256HMAC(key, secret); return s != null ? Base64.getEncoder().encodeToString(s.getBytes()) : ""; } public static String getMapStr(Map map) { if (map == null) { return ""; } StringBuilder b = new StringBuilder("?"); String str = map.keySet().stream().map(key -> { try { return GwURLEncoder.encode(key, StandardCharsets.UTF_8.toString()) + "=" + GwURLEncoder.encode(map.get(key), StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }).collect(Collectors.joining("&")); b.append(str); return b.toString(); } /** * 初始化网关 * * @return */ private static ApigwConfig initConfig() { ApigwConfig config = new ApigwConfig(); //设置client_id config.setClientID(clientId); //设置client_secret config.setClientSecret(clientSecret); ApigwClient apigwClient = ApigwClient.getInstance(); //初始化API网关客户端 apigwClient.init(config); return config; } /** * 获取签名 * * @param method * @param url * @param querys * @return */ public static ReqParam getSignature(HttpMethod method, String url, Map querys) { //初始化API网关客户端 ApigwConfig config = initConfig(); ApiRequest request = new ApiRequest(method, HOST, url); request.setQuerys(querys); request.setBodyJson(JSONObject.toJSONString("").getBytes()); //初始回参 ReqParam res = ReqParam.init(Long.toString(System.currentTimeMillis()), getNonce(10)); request.addHeader("X-Api-ClientID", config.getClientID()); request.addHeader("X-Api-Auth-Version", "2.0"); request.addHeader("X-Api-TimeStamp", res.getTimeStamp()); request.addHeader("X-Api-Nonce", res.getNonce()); request.addHeader("X-Api-SignHeaders", String.join(",", DEFAULT_SIGNHEADERS)); String sign = getSign(request.getMethod().getValue(), getPathEncode(request.getPath()), getQueryEncode(request.getQuerys()), DEFAULT_SIGNHEADERS, request.getHeaders()); request.setSignature(sign); request.addHeader("X-Api-Signature", sign); res.setSign(sign); return res; } /** * 获取验证 * * @return */ @SneakyThrows public static ResParam getAuthorize() { String url = "/jdyconnector/app_management/push_app_authorize"; //URL ?拼接字段 Map map = new LinkedHashMap<>(); map.put("outerInstanceId", instanceId); String pathParamStr = getMapStr(map); //获取接口参数 ReqParam req = K3ApiUtil.getSignature(HttpMethod.POST_BODY, url, map); String resStr = HttpRequest.post(HOST + url + pathParamStr) .header("X-Api-ClientID", clientId) .header("X-Api-Auth-Version", "2.0") .header("X-Api-TimeStamp", req.getTimeStamp()) .header("X-Api-Nonce", req.getNonce()) .header("X-Api-SignHeaders", "X-Api-TimeStamp,X-Api-Nonce") .header("X-Api-Signature", req.getSign()) .execute() .body(); ResDto res = JSONObject.parseObject(resStr, ResDto.class); if (res.getCode() != 200) { throw new RuntimeException(res.getMsg()); } // System.out.println("testGetAuth():" + resStr); userRes = res.getData().get(0); return res.getData().get(0); } /** * 获取验证 * * @return */ @SneakyThrows public static ResParam getToken() { //获取授权 ResParam authorizeRes = getAuthorize(); String url = "/jdyconnector/app_management/kingdee_auth_token"; //URL ?拼接字段 Map map = new LinkedHashMap<>(); map.put("app_key", authorizeRes.getAppKey()); String secretStr = getSecretStr(authorizeRes.getAppKey(), authorizeRes.getAppSecret()); map.put("app_signature", secretStr); String pathParamStr = getMapStr(map); //获取接口参数 ReqParam req = K3ApiUtil.getSignature(HttpMethod.GET, url, map); String resStr = HttpRequest.get(HOST + url + pathParamStr) .header("X-Api-ClientID", clientId) .header("X-Api-Auth-Version", "2.0") .header("X-Api-TimeStamp", req.getTimeStamp()) .header("X-Api-Nonce", req.getNonce()) .header("X-Api-SignHeaders", "X-Api-TimeStamp,X-Api-Nonce") .header("X-Api-Signature", req.getSign()) .execute() .body(); ResDto res = JSONObject.parseObject(resStr, ResDto.class); if (res.getErrcode() != 0) { throw new RuntimeException(res.getDescription()); } ResParam resParam = res.getData().get(0); resParam.setDomain(authorizeRes.getDomain()); // System.out.println("testGetToken():" + resStr); TokenRes = resParam; return resParam; } @SneakyThrows public static String getAuthCode() { String url = "/koas/user/auth_code"; //URL ?拼接字段 Map map = new LinkedHashMap<>(); map.put("access_token", TokenRes.getAccessToken()); String pathParamStr = getMapStr(map); //body //请求 String resStr = HttpRequest.post(HOST + url + pathParamStr) .header("KIS-Timestamp", Long.toString(System.currentTimeMillis() / 1000L)) .header("KIS-State", "vfun" + getNonce(12)) .header("KIS-TraceID", "vfun10086") .header("KIS-Ver", "1.0") .contentType("application/json") .execute() .body(); ResDto res = JSONObject.parseObject(resStr, ResDto.class); if (res.getErrcode() != 0) { throw new RuntimeException(res.getDescription()); } // System.out.println("testSendMsg():" + resStr); authCode = res.getData().get(0).getAuthCode(); return res.getData().get(0).getAuthCode(); } @SneakyThrows public static String getSessionId() { String url = "/koas/user/auth_code_login_access_token"; //URL ?拼接字段 Map map = new LinkedHashMap<>(); map.put("client_id", clientId); map.put("client_secret",clientSecret); String pathParamStr = getMapStr(map); //body HashMap bodyMap = new HashMap<>(); bodyMap.put("auth_code",authCode); //请求 String resStr = HttpRequest.post(HOST + url + pathParamStr) .header("KIS-Timestamp", Long.toString(System.currentTimeMillis() / 1000L)) .header("KIS-State", "WMS" + getNonce(12)) .header("KIS-TraceID", "WMS") .header("KIS-Ver", "1.0") .contentType("application/json") .body(JSON.toJSONString(bodyMap)) .execute() .body(); ResDto res = JSONObject.parseObject(resStr, ResDto.class); if (res.getErrcode() != 0) { throw new RuntimeException(res.getDescription()); } sessionId = res.getData().get(0).getSessionId(); return res.getData().get(0).getSessionId(); } @SneakyThrows public static AcctDto getAcctNumber() { String url = "/koas/user/account"; //URL ?拼接字段 Map map = new LinkedHashMap<>(); map.put("access_token", TokenRes.getAccessToken()); String pathParamStr = getMapStr(map); //body HashMap bodyMap = new HashMap<>(); bodyMap.put("session_id",sessionId); //请求 String resStr = HttpRequest.post(HOST + url + pathParamStr) .header("KIS-Timestamp", Long.toString(System.currentTimeMillis() / 1000L)) .header("KIS-State", "WMS" + getNonce(12)) .header("KIS-TraceID", "WMS") .header("KIS-Ver", "1.0") .contentType("application/json") .body(JSON.toJSONString(bodyMap)) .execute() .body(); AcctDto res = JSONObject.parseObject(resStr, AcctDto.class); if (res.getErrcode() != 0) { throw new RuntimeException(res.getDescription()); } acctDto = res; return res; } @SneakyThrows public static String getIcrmId() { String url = "/koas/user/account_applist"; //URL ?拼接字段 Map map = new LinkedHashMap<>(); map.put("access_token", TokenRes.getAccessToken()); String pathParamStr = getMapStr(map); //body HashMap bodyMap = new HashMap<>(); bodyMap.put("session_id",sessionId); bodyMap.put("client_id", clientId); bodyMap.put("acctnumber",acctDto.getData().getOrglist().get(0).getProdinstlist().get(0).getAccountlist().get(0).getAcctnumber()); //请求 String resStr = HttpRequest.post(HOST + url + pathParamStr) .header("KIS-Timestamp", Long.toString(System.currentTimeMillis() / 1000L)) .header("KIS-State", "wmss" + getNonce(12)) .header("KIS-TraceID", "wmss") .header("KIS-Ver", "1.0") .contentType("application/json") .body(JSON.toJSONString(bodyMap)) .execute() .body(); ResDto res = JSONObject.parseObject(resStr, ResDto.class); if (res.getErrcode() != 0) { throw new RuntimeException(res.getDescription()); } return ""; } @SneakyThrows public static String getServiceGateway() { String url = "/koas/user/get_service_gateway"; //URL ?拼接字段 Map map = new LinkedHashMap<>(); map.put("access_token", TokenRes.getAccessToken()); String pathParamStr = getMapStr(map); //body HashMap bodyMap = new HashMap<>(); bodyMap.put("session_id",sessionId); bodyMap.put("pid", acctDto.getData().getOrglist().get(0).getProdinstlist().get(0).getPid()); bodyMap.put("acctnumber",acctDto.getData().getOrglist().get(0).getProdinstlist().get(0).getAccountlist().get(0).getAcctnumber()); bodyMap.put("icrmid","2c9223b083cc0f130183e4c32be01544"); //请求 String resStr = HttpRequest.post(HOST + url + pathParamStr) .header("KIS-Timestamp", Long.toString(System.currentTimeMillis() / 1000L)) .header("KIS-State", "wmss" + getNonce(12)) .header("KIS-TraceID", "wmss") .header("KIS-Ver", "1.0") .contentType("application/json") .body(JSON.toJSONString(bodyMap)) .execute() .body(); GatewayDto res = JSONObject.parseObject(resStr, GatewayDto.class); if (res.getErrcode() != 0) { throw new RuntimeException(res.getDescription()); } gatewayDto = res; return "SUCCESS"; } public static void init(){ getToken(); getAuthCode(); getSessionId(); getAcctNumber(); getServiceGateway(); } public static void main(String[] args) { getToken(); getAuthCode(); getSessionId(); getAcctNumber(); getServiceGateway(); // getIcrmId(); } /** * 单据审核接口 * @param FClassTypeID 外购入库(1001), 销售出库(1021),采购申请(1070) ,销售订单(1081),产品入库(1002),调拨单(1041) ,生产领料单(1024),采购订单 (1071) * @param FInterID 单据ID * @return */ // @SneakyThrows // @Deprecated // public static ResDto checkK3Vouch(Integer FClassTypeID, Integer FInterID) { // ResParam tokenRes = getToken(); // String url = "/koas/APP007720/api/approve/submit"; // //URL ?拼接字段 // Map map = new LinkedHashMap<>(); // map.put("access_token", tokenRes.getAccessToken()); // String pathParamStr = getMapStr(map); // //body // String bodyJson = VouchCheckDto.convertToQueryJson(FClassTypeID, FInterID); // //请求 // String resStr = HttpRequest.post(HOST + url + pathParamStr) // .header("KIS-Timestamp", Long.toString(System.currentTimeMillis() / 1000L)) // .header("KIS-State", "vfun" + getNonce(12)) // .header("KIS-TraceID", "vfun10086") // .header("KIS-Ver", "1.0") // .header("KIS-AuthData", tokenRes.getAppToken()) // .header("X-Api-SignHeaders", "X-Api-TimeStamp,X-Api-Nonce") // .header("X-GW-Router-Addr", tokenRes.getDomain()) // .body(bodyJson) // .execute() // .body(); // ResDto res = ObjUtil.parseObject(resStr, ResDto.class); // if (res.getErrcode() != 0) { // throw new RuntimeException(res.getDescription()); // } //// System.out.println("testSendMsg():" + resStr); // return res; // } }