Kaynağa Gözat

测试对接

mengjie 5 yıl önce
ebeveyn
işleme
f6a612ac66

+ 432 - 0
codegit/CallCenterApi/CallCenterApi.Interface/CallCenterApi.Interface/Controllers/SignController.cs

@@ -0,0 +1,432 @@
1
+using CallCenter.Utility;
2
+using CallCenterApi.Interface.Controllers.Base;
3
+using Newtonsoft.Json;
4
+using Newtonsoft.Json.Linq;
5
+using System;
6
+using System.Collections;
7
+using System.Collections.Generic;
8
+using System.IO;
9
+using System.Linq;
10
+using System.Net;
11
+using System.Net.Security;
12
+using System.Security.Cryptography;
13
+using System.Security.Cryptography.X509Certificates;
14
+using System.Text;
15
+using System.Web;
16
+using System.Web.Mvc;
17
+
18
+namespace CallCenterApi.Interface.Controllers
19
+{
20
+    public class SignController : BaseController
21
+    {
22
+        // GET: Sign
23
+        public ActionResult Index()
24
+        {
25
+            return View();
26
+        }
27
+
28
+        public ActionResult GetSign(List<string> keyvalue)
29
+        {
30
+            //model.timestamp = DateTimeConvert.ToTimespan(DateTime.Now);//保存导入时间时间戳
31
+            var input = keyvalue;
32
+
33
+            var keys = new List<string>();
34
+            var values = new List<string>();
35
+
36
+            for (int index = 0; index < input.Count; index++)
37
+            {
38
+                if (index % 2 == 0) keys.Add(input[index]);
39
+                else values.Add(input[index]);
40
+            }
41
+            //添加时间戳
42
+            keys.Add("timestamp");
43
+            values.Add(DateTimeToInt(DateTime.Now).ToString());
44
+            var result = keys.Zip(values, (key, value) =>
45
+                                    new KeyValuePair<string, string>(key, value)).ToList();
46
+            var sign = GenerateSign(result, "");
47
+
48
+            return Success( sign);
49
+        }
50
+
51
+        public static int DateTimeToInt(DateTime dt)
52
+        {
53
+            int date = 0;
54
+            TimeSpan ts2 = new TimeSpan(dt.Ticks);
55
+            TimeSpan ts3 = new TimeSpan(DateTime.Parse("1970-01-01").Ticks);
56
+            TimeSpan ts_1 = ts2.Subtract(ts3).Duration();
57
+            Int32 NowMinu = (Int32)ts_1.TotalSeconds;
58
+            date = NowMinu;
59
+            return date;
60
+        }
61
+        /// <summary>  
62
+        /// 将c# DateTime时间格式转换为Unix时间戳格式  
63
+        /// </summary>  
64
+        /// <param name="time">时间</param>  
65
+        /// <returns>long</returns>  
66
+        public static long ConvertDateTimeToInt(System.DateTime time)
67
+        {
68
+            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
69
+            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
70
+            return t;
71
+        }
72
+
73
+        #region 计算签名
74
+        /// <summary>
75
+        /// 生成签名
76
+        /// </summary>
77
+        /// <param name="paramlst">参数列表</param>
78
+        /// <param name="IsToUpper">是否转大写</param>
79
+        /// <param name="IsDirect">是否直接加上签名Key</param>
80
+        /// <returns></returns>
81
+        public static string GenerateSign(List<KeyValuePair<string, string>> lst, string privateKey)
82
+        {
83
+            Comparison<KeyValuePair<string, string>> Comparer = new Comparison<KeyValuePair<string, string>>(CompareKeyValuepair);
84
+            lst.Sort(Comparer);
85
+            var paramlst = lst.Where(p => !string.IsNullOrEmpty(p.Value)).ToList();
86
+            string signstr = string.Join("&", paramlst.Select(p => p.Key + "=" + p.Value)) + privateKey;
87
+            return Sign(signstr, "UTF-8");
88
+        }
89
+
90
+        /// <summary>
91
+        /// 根据Key比较排序位置
92
+        /// </summary>
93
+        private static int CompareKeyValuepair(KeyValuePair<string, string> p1, KeyValuePair<string, string> p2)
94
+        {
95
+            return string.Compare(p1.Key, p2.Key);
96
+        }
97
+
98
+        /// <summary>
99
+        /// 签名字符串
100
+        /// </summary>
101
+        /// <param name="prestr">需要签名的字符串</param>
102
+        /// <param name="key">密钥</param>
103
+        /// <param name="inputCharset">编码格式</param>
104
+        /// <returns>签名结果</returns>
105
+        public static string Sign(string prestr, string inputCharset)
106
+        {
107
+            StringBuilder sb = new StringBuilder();
108
+            MD5 md5 = new MD5CryptoServiceProvider();
109
+            byte[] t = md5.ComputeHash(Encoding.GetEncoding(inputCharset).GetBytes(prestr));
110
+            foreach (byte t1 in t)
111
+            {
112
+                sb.Append(t1.ToString("x2"));
113
+            }
114
+            return sb.ToString();
115
+        }
116
+        #endregion
117
+
118
+        public ActionResult getsignature()
119
+        {
120
+            String appKey = "9b4a98b1bbce465381d323e0005c8588";
121
+            String appSecret = "hgtRQ2iauHEOMYg3QlvamA==";
122
+            String version = "1.0.0";
123
+            long timestamp = ConvertDateTimeToInt(DateTime.Now);
124
+            String nonce = System.Guid.NewGuid().ToString("N");
125
+            string mergeStr = nonce + appKey + appSecret + timestamp + version;
126
+            string encodedStr = System.Web.HttpUtility.UrlEncode(mergeStr);
127
+            string signStr = HmacSHA256(appSecret,encodedStr);
128
+            //return signStr;
129
+
130
+            string strURL = "https://openapi.17win.com";
131
+            var m = new
132
+            {
133
+                timestamp,
134
+                version,
135
+                appKey,
136
+                signStr,
137
+                nonce
138
+            };
139
+            //实体序列化和反序列化
140
+            string json1 = JsonConvert.SerializeObject(m);
141
+            string strHTML = HttpPost(strURL, json1);
142
+            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
143
+            if (jo1 != null && jo1["state"].ToString() == "success")
144
+            {
145
+                return Success("成功");
146
+            }
147
+            return Error("失败");
148
+        }
149
+
150
+
151
+
152
+        //加密算法HmacSHA256  
153
+        public string HmacSHA256(string secret, string signKey)
154
+        {
155
+            string signRet = string.Empty;
156
+            using (HMACSHA256 mac = new HMACSHA256(Encoding.UTF8.GetBytes(signKey)))
157
+            {
158
+                byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(secret));
159
+                signRet = Convert.ToBase64String(hash);
160
+                //signRet = ToHexString(hash); ;
161
+            }
162
+            return signRet;
163
+        }
164
+
165
+        //byte[]转16进制格式string
166
+        public static string ToHexString(byte[] bytes)
167
+        {
168
+            string hexString = string.Empty;
169
+            if (bytes != null)
170
+            {
171
+                StringBuilder strB = new StringBuilder();
172
+                foreach (byte b in bytes)
173
+                {
174
+                    strB.AppendFormat("{0:x2}", b);
175
+                }
176
+                hexString = strB.ToString();
177
+            }
178
+            return hexString;
179
+        }
180
+
181
+
182
+        #region POST
183
+        /// <summary>
184
+        /// HTTP POST方式请求数据
185
+        /// </summary>
186
+        /// <param name="url">URL.</param>
187
+        /// <param name="param">POST的数据</param>
188
+        /// <returns></returns>
189
+        public static string HttpPost(string url, string param = null)
190
+        {
191
+            HttpWebRequest request;
192
+
193
+            //如果是发送HTTPS请求  
194
+            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
195
+            {
196
+                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
197
+                request = WebRequest.Create(url) as HttpWebRequest;
198
+                request.ProtocolVersion = HttpVersion.Version10;
199
+            }
200
+            else
201
+            {
202
+                request = WebRequest.Create(url) as HttpWebRequest;
203
+            }
204
+
205
+            request.Method = "POST";
206
+            request.ContentType = "application/x-www-form-urlencoded";
207
+            request.Accept = "*/*";
208
+            request.Timeout = 15000;
209
+            request.AllowAutoRedirect = false;
210
+
211
+
212
+
213
+            StreamWriter requestStream = null;
214
+            WebResponse response = null;
215
+            string responseStr = null;
216
+
217
+            try
218
+            {
219
+                requestStream = new StreamWriter(request.GetRequestStream());
220
+                requestStream.Write(param);
221
+                requestStream.Close();
222
+
223
+                response = request.GetResponse();
224
+                if (response != null)
225
+                {
226
+                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
227
+                    responseStr = reader.ReadToEnd();
228
+                    reader.Close();
229
+                }
230
+            }
231
+            catch (Exception)
232
+            {
233
+                throw;
234
+            }
235
+            finally
236
+            {
237
+                request = null;
238
+                requestStream = null;
239
+                response = null;
240
+            }
241
+
242
+            return responseStr;
243
+        }
244
+
245
+
246
+        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
247
+        {
248
+            return true; //总是接受  
249
+        }
250
+        public static string BuildRequest(string strUrl, Dictionary<string, string> dicPara, string fileName)
251
+        {
252
+            string contentType = "image/jpeg";
253
+            //待请求参数数组
254
+            FileStream Pic = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
255
+            byte[] PicByte = new byte[Pic.Length];
256
+            Pic.Read(PicByte, 0, PicByte.Length);
257
+            int lengthFile = PicByte.Length;
258
+
259
+            //构造请求地址
260
+
261
+            //设置HttpWebRequest基本信息
262
+            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
263
+            //设置请求方式:get、post
264
+            request.Method = "POST";
265
+            //设置boundaryValue
266
+            string boundaryValue = DateTime.Now.Ticks.ToString("x");
267
+            string boundary = "--" + boundaryValue;
268
+            request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
269
+            //设置KeepAlive
270
+            request.KeepAlive = true;
271
+            //设置请求数据,拼接成字符串
272
+            StringBuilder sbHtml = new StringBuilder();
273
+            foreach (KeyValuePair<string, string> key in dicPara)
274
+            {
275
+                sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
276
+            }
277
+            sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"");
278
+            sbHtml.Append(fileName);
279
+            sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
280
+            string postHeader = sbHtml.ToString();
281
+            //将请求数据字符串类型根据编码格式转换成字节流
282
+            Encoding code = Encoding.GetEncoding("UTF-8");
283
+            byte[] postHeaderBytes = code.GetBytes(postHeader);
284
+            byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
285
+            //设置长度
286
+            long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;
287
+            request.ContentLength = length;
288
+
289
+            //请求远程HTTP
290
+            Stream requestStream = request.GetRequestStream();
291
+            Stream myStream = null;
292
+            try
293
+            {
294
+                //发送数据请求服务器
295
+                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
296
+                requestStream.Write(PicByte, 0, lengthFile);
297
+                requestStream.Write(boundayBytes, 0, boundayBytes.Length);
298
+                HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
299
+                myStream = HttpWResp.GetResponseStream();
300
+            }
301
+            catch (WebException e)
302
+            {
303
+                //LogResult(e.Message);
304
+                return "";
305
+            }
306
+            finally
307
+            {
308
+                if (requestStream != null)
309
+                {
310
+                    requestStream.Close();
311
+                }
312
+            }
313
+
314
+            //读取处理结果
315
+            StreamReader reader = new StreamReader(myStream, code);
316
+            StringBuilder responseData = new StringBuilder();
317
+
318
+            String line;
319
+            while ((line = reader.ReadLine()) != null)
320
+            {
321
+                responseData.Append(line);
322
+            }
323
+            myStream.Close();
324
+            Pic.Close();
325
+
326
+            return responseData.ToString();
327
+        }
328
+        #endregion
329
+
330
+        #region Get
331
+        /// <summary>
332
+        /// HTTP GET方式请求数据.
333
+        /// </summary>
334
+        /// <param name="url">URL.</param>
335
+        /// <returns></returns>
336
+        public static string HttpGet(string url, Hashtable headht = null)
337
+        {
338
+            HttpWebRequest request;
339
+
340
+            //如果是发送HTTPS请求  
341
+            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
342
+            {
343
+                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
344
+                request = WebRequest.Create(url) as HttpWebRequest;
345
+                request.ProtocolVersion = HttpVersion.Version10;
346
+            }
347
+            else
348
+            {
349
+                request = WebRequest.Create(url) as HttpWebRequest;
350
+            }
351
+            request.Method = "GET";
352
+            //request.ContentType = "application/x-www-form-urlencoded";
353
+            request.Accept = "*/*";
354
+            request.Timeout = 15000;
355
+            request.AllowAutoRedirect = false;
356
+            WebResponse response = null;
357
+            string responseStr = null;
358
+            if (headht != null)
359
+            {
360
+                foreach (DictionaryEntry item in headht)
361
+                {
362
+                    request.Headers.Add(item.Key.ToString(), item.Value.ToString());
363
+                }
364
+            }
365
+
366
+            try
367
+            {
368
+                response = request.GetResponse();
369
+
370
+                if (response != null)
371
+                {
372
+                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
373
+                    responseStr = reader.ReadToEnd();
374
+                    reader.Close();
375
+                }
376
+            }
377
+            catch (Exception)
378
+            {
379
+                throw;
380
+            }
381
+            return responseStr;
382
+        }
383
+        public static string HttpGet(string url, Encoding encodeing, Hashtable headht = null)
384
+        {
385
+            HttpWebRequest request;
386
+
387
+            //如果是发送HTTPS请求  
388
+            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
389
+            {
390
+                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
391
+                request = WebRequest.Create(url) as HttpWebRequest;
392
+                request.ProtocolVersion = HttpVersion.Version10;
393
+            }
394
+            else
395
+            {
396
+                request = WebRequest.Create(url) as HttpWebRequest;
397
+            }
398
+            request.Method = "GET";
399
+            //request.ContentType = "application/x-www-form-urlencoded";
400
+            request.Accept = "*/*";
401
+            request.Timeout = 15000;
402
+            request.AllowAutoRedirect = false;
403
+            WebResponse response = null;
404
+            string responseStr = null;
405
+            if (headht != null)
406
+            {
407
+                foreach (DictionaryEntry item in headht)
408
+                {
409
+                    request.Headers.Add(item.Key.ToString(), item.Value.ToString());
410
+                }
411
+            }
412
+
413
+            try
414
+            {
415
+                response = request.GetResponse();
416
+
417
+                if (response != null)
418
+                {
419
+                    StreamReader reader = new StreamReader(response.GetResponseStream(), encodeing);
420
+                    responseStr = reader.ReadToEnd();
421
+                    reader.Close();
422
+                }
423
+            }
424
+            catch (Exception)
425
+            {
426
+                throw;
427
+            }
428
+            return responseStr;
429
+        }
430
+        #endregion
431
+    }
432
+}