zxl
2025-06-16 0fb6b9d8d414822668c401a2b507df1fe6d1fa2d
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
package cn.lili.modules.logistics.plugin.kdniao;
 
import cn.hutool.core.text.CharSequenceUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.modules.logistics.LogisticsPlugin;
import cn.lili.modules.logistics.entity.dto.LabelOrderDTO;
import cn.lili.modules.logistics.entity.enums.LogisticsEnum;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dos.OrderItem;
import cn.lili.modules.order.order.entity.vo.OrderDetailVO;
import cn.lili.modules.store.entity.dos.StoreLogistics;
import cn.lili.modules.store.entity.dto.StoreDeliverGoodsAddressDTO;
import cn.lili.modules.system.entity.dos.Logistics;
import cn.lili.modules.system.entity.dto.LogisticsSetting;
import cn.lili.modules.system.entity.vo.Traces;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 快递鸟插件
 *
 * @author Bulbasaur
 */
@Slf4j
public class KdniaoPlugin implements LogisticsPlugin {
 
    @Autowired
    private LogisticsSetting logisticsSetting;
 
    public KdniaoPlugin(LogisticsSetting logisticsSetting) {
        this.logisticsSetting = logisticsSetting;
    }
 
    @Override
    public LogisticsEnum pluginName() {
        return LogisticsEnum.KDNIAO;
    }
 
    @Override
    public Traces pollQuery(Logistics logistics, String expNo, String phone) {
        try {
            String requestData = "{'OrderCode':'','ShipperCode':'" + logistics.getCode() +
                    "','LogisticCode':'" + expNo + "'" +
                    ",'CustomerName':'" + phone.substring(phone.length() - 4) + "'" +
                    "}";
            //请求地址-测试地址
            String testReqURL = "http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json";
            //请求地址-正式地址
            String reqURL = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
            Map<String, String> params = new HashMap<>(8);
            params.put("RequestData", urlEncoder(requestData, "UTF-8"));
            params.put("EBusinessID", logisticsSetting.getKdniaoEbusinessID());
            params.put("RequestType", logisticsSetting.getRequestType());
            String dataSign = encrypt(requestData, logisticsSetting.getKdniaoAppKey(), "UTF-8");
            params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
            params.put("DataType", "2");
 
            String result = sendPost(reqURL, params);
            Map map = (Map) JSON.parse(result);
            return new Traces(logistics.getName(), expNo, (List<Map>) map.get("Traces"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    @Override
    public Traces pollMapTrack(Logistics logistics, String expNo, String phone, String from, String to) {
        try {
            //请求地址-测试地址
            String testReqURL = "http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json";
            //请求地址-正式地址
            String reqURL = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
            String RequestData = "{" +
                    "'OrderCode': ''," +
                    "'CustomerName': '" + phone.substring(phone.length() - 4) + "'," +
                    "'ShipperCode': '" + logistics.getCode() + "'," +
                    "'LogisticCode': '" + expNo + "'," +
                    "'SenderCityName': '" + from + "'," +
                    "'ReceiverCityName': '" + to + "'," +
                    "'IsReturnCoordinates': 1," +
                    "'IsReturnRouteMap': 1," +
                    "}";
            // 组装系统级参数
            Map<String, String> params = new HashMap<String, String>();
            params.put("RequestData", urlEncoder(RequestData, "UTF-8"));
            params.put("EBusinessID", logisticsSetting.getKdniaoEbusinessID());
            params.put("RequestType", "8003");
            String dataSign = encrypt(RequestData, logisticsSetting.getKdniaoAppKey(), "UTF-8");
            params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
            // params.put("DataType", "2");
            // 以form表单形式提交post请求,post请求体中包含了应用级参数和系统级参数
            String result = sendPost(reqURL, params);
            log.error(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    @Override
    public Map<String, Object> labelOrder(LabelOrderDTO labelOrderDTO) {
        try {
            Map<String, Object> resultMap = new HashMap();
            //订单
            Order order = labelOrderDTO.getOrder();
            //订单货物
            List<OrderItem> orderItems = labelOrderDTO.getOrderItems();
            //获取对应物流
            Logistics logistics = labelOrderDTO.getLogistics();
            //收件人地址
            String[] ConsigneeAddress = order.getConsigneeAddressPath().split(",");
            //获取店家信息
            StoreDeliverGoodsAddressDTO storeDeliverGoodsAddressDTO = labelOrderDTO.getStoreDeliverGoodsAddressDTO();
            //发件人地址
            String[] consignorAddress = storeDeliverGoodsAddressDTO.getSalesConsignorAddressPath().split(",");
            //店铺-物流公司设置
            StoreLogistics storeLogistics = labelOrderDTO.getStoreLogistics();
 
            //组装快递鸟应用级参数
            String resultDate = "{" +
                    "'OrderCode': '" + order.getSn() + "'," + //订单编码
                    "'ShipperCode': '" + logistics.getCode() + "'," +   //快递公司编码
                    "'CustomerName': '" + storeLogistics.getCustomerName() + "'," +//客户编码
                    "'CustomerPwd': '" + storeLogistics.getCustomerPwd() + "'," +     //客户密码
                    "'MonthCode': '" + storeLogistics.getMonthCode() + "'," +       //密钥
                    "'SendSite': '" + storeLogistics.getSendSite() + "'," +         //归属网点
                    "'SendStaff': '" + storeLogistics.getSendStaff() + "'," +       //收件快递员
                    "'PayType': " + storeLogistics.getPayType() + "," +
                    "'ExpType': " + storeLogistics.getExpType() + "," +
                    //发件人信息
                    "'Sender': {" +
                    "'Name': '" + storeDeliverGoodsAddressDTO.getSalesConsignorName() + "'," +
                    "'Mobile': '" + storeDeliverGoodsAddressDTO.getSalesConsignorMobile() + "'," +
                    "'ProvinceName': '" + consignorAddress[0] + "'," +   //省
                    "'CityName': '" + consignorAddress[1] + "'," +       //市
                    "'ExpAreaName': '" + consignorAddress[2] + "'," +    //区
                    "'Address': '" + storeDeliverGoodsAddressDTO.getSalesConsignorDetail() + "'" +   //发件人详细地址
                    "}," +
                    //收件人信息
                    "'Receiver': {" +
                    "'Name': '" + order.getConsigneeName() + "'," +
                    "'Mobile': '" + order.getConsigneeMobile() + "'," +
                    "'ProvinceName': '" + ConsigneeAddress[0] + "'," +     //省
                    "'CityName': '" + ConsigneeAddress[1] + "'," +       //市
                    "'ExpAreaName': '" + ConsigneeAddress[2] + "'," +    //区
                    "'Address': '" + order.getConsigneeDetail() + "'" +  //收件人详细地址
                    "}," +
                    //商品信息
                    "'Commodity': [";
 
            //子订单信息
            for (OrderItem orderItem : orderItems) {
                resultDate = resultDate + "{" +
                        "'GoodsName': '" + orderItem.getGoodsName() + "'," +
                        "'Goodsquantity': '" + orderItem.getNum() + "'" +
                        "},";
            }
            resultDate = resultDate + "]," +
                    "'Quantity': " + orderItems.size() + "," +  //包裹数
                    "'IsReturnPrintTemplate':1," +  //生成电子面单模板
                    "'Remark': '" + order.getRemark() + "'" +//商家备注
                    "}";
 
 
            //组织系统级参数
            Map<String, String> params = new HashMap<>();
            //请求地址-测试地址
            String testReqURL = "http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json";
            //请求地址-正式地址
            String reqURL = "https://api.kdniao.com/api/EOrderService";
 
            //进行格式加密
            params.put("RequestData", urlEncoder(resultDate, "UTF-8"));
            params.put("EBusinessID", logisticsSetting.getKdniaoEbusinessID());
            params.put("RequestType", "1007");
 
            String dataSign = encrypt(resultDate, logisticsSetting.getKdniaoAppKey(), "UTF-8");
            params.put("DataSign", dataSign);
            params.put("DataType", "2");
            // 以form表单形式提交post请求,post请求体中包含了应用级参数和系统级参数
            String result = sendPost(reqURL, params);
            if (CharSequenceUtil.isEmpty(result) || CharSequenceUtil.isBlank(result)) {
                throw new ServiceException(ResultCode.LOGISTICS_CHECK_SETTING);
            }
            //根据公司业务处理返回的信息......
            JSONObject obj = JSONObject.parseObject(result);
            log.info("电子面单响应:{}", result);
            if (!"100".equals(obj.getString("ResultCode"))) {
//                resultMap.put("Reason",obj.getString("Reason"));
                throw new ServiceException(obj.getString("Reason"));
//                return resultMap;
            }
 
            JSONObject orderJson = JSONObject.parseObject(obj.getString("Order"));
            resultMap.put("printTemplate", obj.getString("PrintTemplate"));
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    @Override
    public String createOrder(OrderDetailVO orderDetailVO) {
        return null;
    }
 
 
    /**
     * MD5加密
     *
     * @param str     内容
     * @param charset 编码方式
     * @throws Exception
     */
    @SuppressWarnings("unused")
    private String MD5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }
 
    /**
     * base64编码
     *
     * @param str     内容
     * @param charset 编码方式di
     * @throws UnsupportedEncodingException
     */
    private String base64(String str, String charset) throws UnsupportedEncodingException {
        return base64Encode(str.getBytes(charset));
    }
 
    @SuppressWarnings("unused")
    private String urlEncoder(String str, String charset) throws UnsupportedEncodingException {
        return URLEncoder.encode(str, charset);
    }
 
    /**
     * 电商Sign签名生成
     *
     * @param content  内容
     * @param keyValue Appkey
     * @param charset  编码方式
     * @return DataSign签名
     * @throws UnsupportedEncodingException ,Exception
     */
    @SuppressWarnings("unused")
    private String encrypt(String content, String keyValue, String charset) throws Exception {
        if (keyValue != null) {
            return base64(MD5(content + keyValue, charset), charset);
        }
        return base64(MD5(content, charset), charset);
    }
 
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求的参数集合
     * @return 远程资源的响应结果
     */
    @SuppressWarnings("unused")
    private String sendPost(String url, Map<String, String> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            //发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //POST方法
            conn.setRequestMethod("POST");
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            //发送请求参数
            if (params != null) {
                StringBuilder param = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (param.length() > 0) {
                        param.append("&");
                    }
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                }
                out.write(param.toString());
            }
            //flush输出流的缓冲
            out.flush();
            //定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("向指定 URL 发送POST方法的请求错误", e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }
 
 
    private static final char[] BASE64_ENCODE_CHARS = new char[]{
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/'};
 
    public static String base64Encode(byte[] data) {
        StringBuffer sb = new StringBuffer();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;
        while (i < len) {
            b1 = data[i++] & 0xff;
            if (i == len) {
                sb.append(BASE64_ENCODE_CHARS[b1 >>> 2]);
                sb.append(BASE64_ENCODE_CHARS[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len) {
                sb.append(BASE64_ENCODE_CHARS[b1 >>> 2]);
                sb.append(BASE64_ENCODE_CHARS[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(BASE64_ENCODE_CHARS[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(BASE64_ENCODE_CHARS[b1 >>> 2]);
            sb.append(BASE64_ENCODE_CHARS[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
            sb.append(BASE64_ENCODE_CHARS[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
            sb.append(BASE64_ENCODE_CHARS[b3 & 0x3f]);
        }
        return sb.toString();
    }
}