jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using HH.WMS.Entitys.Common;
using Newtonsoft.Json;
using System.Configuration;
using HH.WMS.Entitys;
using Newtonsoft.Json.Linq;
 
namespace HH.WMS.Common
{
    /**
    *
    * 快递鸟电子面单接口
    *
    * @技术QQ群: 340378554
    * @see: http://kdniao.com/api-eorder
    * @copyright: 深圳市快金数据技术服务有限公司
    * 
    * ID和Key请到官网申请:http://kdniao.com/reg
    */
    public static class KdApiEOrderHelper
    {
        //电商ID
        private static string EBusinessID = ConfigurationManager.AppSettings["KdEID"];
        //电商加密私钥,快递鸟提供,注意保管,不要泄漏
        private static string AppKey = ConfigurationManager.AppSettings["KdEAppKey"];
        //请求url
        private static string ReqURL = ConfigurationManager.AppSettings["KdEReqURL"];
 
        /// <summary>
        /// 生成物流单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static KdEBusiness GenerateLogistics(TN_WM_OUT_MSTEntity outMst)
        {
            KdEOrder order = new KdEOrder()
            {
                OrderCode = outMst.CN_S_OP_NO,
                ShipperCode = "SF",
                PayType = 1,
                ExpType = "1",
                Cost = 1.0,
                OtherCost = 1.0,
                Sender = new KdEOrderSender() //发货人地址
                {
                    Company = outMst.CN_S_OWNER,
                    Name = outMst.CN_S_RECEIVER_NAME,
                    Mobile = outMst.CN_S_PHONE,
                    ProvinceName = "安徽",
                    CityName = "合肥",
                    ExpAreaName = "蜀山区",
                    Address = (string.IsNullOrEmpty(outMst.CN_S_DETAIL_ADDRESS)) ? "-" : outMst.CN_S_DETAIL_ADDRESS
                },
                Receiver = new KdEOrderReceiver()   //收件人地址
                {
                    Company = outMst.CN_S_OWNER,
                    Name = outMst.CN_S_RECEIVER_NAME,
                    Mobile = outMst.CN_S_PHONE,
                    ProvinceName = "安徽",
                    CityName = "合肥",
                    ExpAreaName = "蜀山区",
                    Address = (string.IsNullOrEmpty(outMst.CN_S_DETAIL_ADDRESS)) ? "-" : outMst.CN_S_DETAIL_ADDRESS
                },
                Commodity = outMst.OutDtlList.Select(x => new KdEOrderCommoditys()
                {
                    GoodsName = x.CN_S_ITEM_NAME,
                    Goodsquantity = Convert.ToInt32(x.CN_F_QUANTITY),
                    GoodsWeight = 1.0
                }).ToList(),
                Weight = 1.0,
                Quantity = Convert.ToInt32(outMst.OutDtlList.Sum(x => x.CN_F_QUANTITY)),
                Volume = 0.0,
                Remark = "",
                IsReturnPrintTemplate = "0"
            };
 
            string requestData = JsonConvert.SerializeObject(order);
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
            param.Add("EBusinessID", EBusinessID);
            param.Add("RequestType", "1007");
            string dataSign = Encrypt(requestData, AppKey, "UTF-8");
            param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
            param.Add("DataType", "2");
            string result = SendPost(ReqURL, param);
            string r1 = JsonConvert.SerializeObject(result);
            KdEBusiness business = JsonConvert.DeserializeObject<KdEBusiness>(r1);
            return business;
        }
 
        /// <summary>
        /// Json方式  电子面单
        /// </summary>
        /// <returns></returns>
        public static string orderTracesSubByJson()
        {
            string requestData = "{'OrderCode': '012657700222'," +
                                 "'ShipperCode':'SF'," +
                                  "'PayType':1," +
                                  "'ExpType':1," +
                                  "'Cost':1.0," +
                                  "'OtherCost':1.0," +
                                  "'Sender':" +
                                  "{" +
                                  "'Company':'LV','Name':'Taylor','Mobile':'15018442396','ProvinceName':'上海','CityName':'上海','ExpAreaName':'青浦区','Address':'明珠路73号'}," +
                                  "'Receiver':" +
                                  "{" +
                                  "'Company':'GCCUI','Name':'Yann','Mobile':'15018442396','ProvinceName':'北京','CityName':'北京','ExpAreaName':'朝阳区','Address':'三里屯街道雅秀大厦'}," +
                                  "'Commodity':" +
                                  "[{" +
                                  "'GoodsName':'鞋子','Goodsquantity':1,'GoodsWeight':1.0}]," +
                                  "'Weight':1.0," +
                                  "'Quantity':1," +
                                  "'Volume':0.0," +
                                  "'Remark':'小心轻放'," +
                                  "'IsReturnPrintTemplate':1}";
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
            param.Add("EBusinessID", EBusinessID);
            param.Add("RequestType", "1007");
            string dataSign = Encrypt(requestData, AppKey, "UTF-8");
            param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
            param.Add("DataType", "2");
 
            string result = SendPost(ReqURL, param);
 
            //根据公司业务处理返回的信息......
 
            return result;
        }
 
        /// <summary>
        /// Post方式提交数据,返回网页的源代码
        /// </summary>
        /// <param name="url">发送请求的 URL</param>
        /// <param name="param">请求的参数集合</param>
        /// <returns>远程资源的响应结果</returns>
        private static string SendPost(string url, Dictionary<string, string> param)
        {
            string result = "";
            StringBuilder postData = new StringBuilder();
            if (param != null && param.Count > 0)
            {
                foreach (var p in param)
                {
                    if (postData.Length > 0)
                    {
                        postData.Append("&");
                    }
                    postData.Append(p.Key);
                    postData.Append("=");
                    postData.Append(p.Value);
                }
            }
            byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(postData.ToString());
            try
            {
 
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = url;
                request.Accept = "*/*";
                request.Timeout = 30 * 1000;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.Method = "POST";
                request.ContentLength = byteData.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(byteData, 0, byteData.Length);
                stream.Flush();
                stream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream backStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(backStream, Encoding.GetEncoding("UTF-8"));
                result = sr.ReadToEnd();
                sr.Close();
                backStream.Close();
                response.Close();
                request.Abort();
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
 
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            throw new NotImplementedException();
        }
 
 
        ///<summary>
        ///电商Sign签名
        ///</summary>
        ///<param name="content">内容</param>
        ///<param name="keyValue">Appkey</param>
        ///<param name="charset">URL编码 </param>
        ///<returns>DataSign签名</returns>
        private static string Encrypt(String content, String keyValue, String charset)
        {
            if (keyValue != null)
            {
                return Base64(MD5(content + keyValue, charset), charset);
            }
            return Base64(MD5(content, charset), charset);
        }
 
        ///<summary>
        /// 字符串MD5加密
        ///</summary>
        ///<param name="str">要加密的字符串</param>
        ///<param name="charset">编码方式</param>
        ///<returns>密文</returns>
        private static string MD5(string str, string charset)
        {
            byte[] buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(str);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider check;
                check = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] somme = check.ComputeHash(buffer);
                string ret = "";
                foreach (byte a in somme)
                {
                    if (a < 16)
                        ret += "0" + a.ToString("X");
                    else
                        ret += a.ToString("X");
                }
                return ret.ToLower();
            }
            catch
            {
                throw;
            }
        }
 
        /// <summary>
        /// base64编码
        /// </summary>
        /// <param name="str">内容</param>
        /// <param name="charset">编码方式</param>
        /// <returns></returns>
        private static string Base64(String str, String charset)
        {
            return Convert.ToBase64String(System.Text.Encoding.GetEncoding(charset).GetBytes(str));
        }
    }
}