自动化立体仓库 - WMS系统
#
zjj
2025-09-02 598c9d63f68a8c92b264328c88c1cb4ef25af044
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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<String, String> querys) {
        try {
            if (CommontUtil.isEmpty(querys)) {
                return "";
            } else {
                List<String> list = new ArrayList(querys.size());
                Iterator var3 = querys.entrySet().iterator();
 
                while (var3.hasNext()) {
                    Map.Entry<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> map = new LinkedHashMap<>();
        map.put("client_id", clientId);
        map.put("client_secret",clientSecret);
        String pathParamStr = getMapStr(map);
        //body
        HashMap<String, Object> 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<String, String> map = new LinkedHashMap<>();
        map.put("access_token", TokenRes.getAccessToken());
        String pathParamStr = getMapStr(map);
        //body
        HashMap<String, Object> 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<String, String> map = new LinkedHashMap<>();
        map.put("access_token", TokenRes.getAccessToken());
        String pathParamStr = getMapStr(map);
        //body
        HashMap<String, Object> 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<String, String> map = new LinkedHashMap<>();
        map.put("access_token", TokenRes.getAccessToken());
        String pathParamStr = getMapStr(map);
        //body
        HashMap<String, Object> 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<String, String> 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;
//    }
}