From 610782d5127af072b204792f4c9e38911498e61e Mon Sep 17 00:00:00 2001
From: 南骏 池 <chiffly@163.com>
Date: 星期五, 25 四月 2025 09:02:19 +0800
Subject: [PATCH] 1.携客云初步demo

---
 service/QC/OAJyService.cs                 |   62 ++++++----
 NewPdaSqlServer.csproj                    |    3 
 Controllers/Warehouse/MesXkyController.cs |   38 ++++++
 util/XkyApiHelper.cs                      |  150 +++++++++++++++++++++++++
 service/Warehouse/MesXkyService.cs        |   79 +++++++++++++
 5 files changed, 307 insertions(+), 25 deletions(-)

diff --git a/Controllers/Warehouse/MesXkyController.cs b/Controllers/Warehouse/MesXkyController.cs
new file mode 100644
index 0000000..0788b71
--- /dev/null
+++ b/Controllers/Warehouse/MesXkyController.cs
@@ -0,0 +1,38 @@
+锘縰sing System.Dynamic;
+using Microsoft.AspNetCore.Mvc;
+using NewPdaSqlServer.Dto.service;
+using NewPdaSqlServer.entity;
+using NewPdaSqlServer.service.QC;
+using NewPdaSqlServer.util;
+using Newtonsoft.Json.Linq;
+
+namespace NewPdaSqlServer.Controllers.Warehouse;
+
+[Route("api/[controller]")]
+[ApiController]
+public class MesXkyController : ControllerBase
+{
+    MesXkyService m = new MesXkyService();
+
+    [HttpPost("GetXkyDhd")]
+    public ResponseResult GetXkyDhd([FromBody] string JsonObj)
+    {
+        try
+        {
+            dynamic resultInfos = new ExpandoObject();
+            resultInfos = m.GetXkyDHD(JsonObj);
+            var tbBillList = resultInfos;
+            return new ResponseResult
+            {
+                status = 0,
+                message = "OK",
+                data = tbBillList
+            };
+        }
+        catch (Exception ex)
+        {
+            return ResponseResult.ResponseError(ex);
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/NewPdaSqlServer.csproj b/NewPdaSqlServer.csproj
index a720b22..37df97b 100644
--- a/NewPdaSqlServer.csproj
+++ b/NewPdaSqlServer.csproj
@@ -10,9 +10,12 @@
         <PackageReference Include="Masuit.Tools.Core" Version="2024.5.8" />
         <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.8" />
         <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.10" />
+        <PackageReference Include="Portable.BouncyCastle" Version="1.9.0" />
         <PackageReference Include="SqlSugarCore" Version="5.1.4.169" />
         <PackageReference Include="Swashbuckle.AspNetCore" Version="6.8.0" />
         <PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
+        <PackageReference Include="System.Security.Cryptography.X509Certificates" Version="4.3.2" />
+        <PackageReference Include="System.Security.Cryptography.Xml" Version="9.0.4" />
     </ItemGroup>
 
 </Project>
diff --git a/service/QC/OAJyService.cs b/service/QC/OAJyService.cs
index cc9593b..a5191af 100644
--- a/service/QC/OAJyService.cs
+++ b/service/QC/OAJyService.cs
@@ -11,6 +11,13 @@
 using System.Security.Cryptography;
 using System.Text;
 using static Azure.Core.HttpHeader;
+using System.Security.Cryptography;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Security;
+using System.Security.Cryptography.X509Certificates;
+using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Security;
 
 namespace NewPdaSqlServer.service.QC;
 
@@ -23,34 +30,39 @@
     // private const string SPK = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApobID/gwmD9OofMG1gEcE94NCMeTYUq1cam/7ADZmxHCVpF143GaHWhqDdY0TTVbcUElsQ71DzAG2j3itWlIJBK5fVGwCo3sPpAvUDdKMh+Uivcp7yxdy/IDRA/PS4JARuEyM4cVJLhIOU2KnSlbIkheeoDkDgfaxu9kKrWnozJLiYraVTVDz9PdRX7fQdP+Zu/xB9txAGw4kvOm9HwgrzaSRdZEhisTJ5yyoNW/dLXtWKXA0cKhKOOIFu12TOrv/It6hl1ShTUuy79Pa51M9Oc2dEfVs1tluNXPWo1uFXQbBaJxdqZEJJlK7iW2uQFIao2O4XFHYThwy2+6116LtwIDAQAB";
     private const string HOST = "http://192.168.1.149:8099";
 
-    private const string SPK = @"-----BEGIN PUBLIC KEY-----
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApobID/gwmD9OofMG1gEc
-E94NCMeTYUq1cam/7ADZmxHCVpF143GaHWhqDdY0TTVbcUElsQ71DzAG2j3itWlI
-JBK5fVGwCo3sPpAvUDdKMh+Uivcp7yxdy/IDRA/PS4JARuEyM4cVJLhIOU2KnSlb
-IkheeoDkDgfaxu9kKrWnozJLiYraVTVDz9PdRX7fQdP+Zu/xB9txAGw4kvOm9Hwg
-rzaSRdZEhisTJ5yyoNW/dLXtWKXA0cKhKOOIFu12TOrv/It6hl1ShTUuy79Pa51M
-9Oc2dEfVs1tluNXPWo1uFXQbBaJxdqZEJJlK7iW2uQFIao2O4XFHYThwy2+6116L
-twIDAQAB
------END PUBLIC KEY-----";
+    private const string SPK = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApobID/gwmD9OofMG1gEcE94NCMeTYUq1cam/7ADZmxHCVpF143GaHWhqDdY0TTVbcUElsQ71DzAG2j3itWlIJBK5fVGwCo3sPpAvUDdKMh+Uivcp7yxdy/IDRA/PS4JARuEyM4cVJLhIOU2KnSlbIkheeoDkDgfaxu9kKrWnozJLiYraVTVDz9PdRX7fQdP+Zu/xB9txAGw4kvOm9HwgrzaSRdZEhisTJ5yyoNW/dLXtWKXA0cKhKOOIFu12TOrv/It6hl1ShTUuy79Pa51M9Oc2dEfVs1tluNXPWo1uFXQbBaJxdqZEJJlK7iW2uQFIao2O4XFHYThwy2+6116LtwIDAQAB";
 
 
     public static class RsaHelper
     {
         public static string Encrypt(string plainText, string publicKeyPem)
         {
-            // 灏哖EM鏍煎紡鐨勫叕閽ヨ浆鎹负XML鏍煎紡
-            var rsa = RSA.Create();
-            rsa.ImportFromPem(publicKeyPem);  // 浣跨敤.NET 5+ 鍐呯疆PEM瑙f瀽鏂规硶
+            //// 灏哖EM鏍煎紡鐨勫叕閽ヨ浆鎹负XML鏍煎紡
+            //var rsa = RSA.Create();
+            //rsa.ImportFromPem(publicKeyPem);  // 浣跨敤.NET 5+ 鍐呯疆PEM瑙f瀽鏂规硶
 
-            var parameters = rsa.ExportParameters(false);
-            string publicKeyXml = $"<RSAKeyValue><Modulus>{Convert.ToBase64String(parameters.Modulus)}</Modulus><Exponent>{Convert.ToBase64String(parameters.Exponent)}</Exponent></RSAKeyValue>";
+            //var parameters = rsa.ExportParameters(false);
+            //string publicKeyXml = $"<RSAKeyValue><Modulus>{Convert.ToBase64String(parameters.Modulus)}</Modulus><Exponent>{Convert.ToBase64String(parameters.Exponent)}</Exponent></RSAKeyValue>";
 
-            using var rsaProvider = new RSACryptoServiceProvider();
-            rsaProvider.FromXmlString(publicKeyXml);  // 浣跨敤杞崲鍚庣殑XML鏍煎紡鍏挜
+            //using var rsaProvider = new RSACryptoServiceProvider();
+            //rsaProvider.FromXmlString(publicKeyXml);  // 浣跨敤杞崲鍚庣殑XML鏍煎紡鍏挜
 
-            var data = Encoding.UTF8.GetBytes(plainText);
-            var encrypted = rsaProvider.Encrypt(data, false);
-            return Convert.ToBase64String(encrypted);
+            //var data = Encoding.UTF8.GetBytes(plainText);
+            //var encrypted = rsaProvider.Encrypt(data, false);
+            //return Convert.ToBase64String(encrypted);
+
+            RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKeyPem));
+            string XML = string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
+            Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
+            Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
+            string encryptedContent = string.Empty;
+            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
+            {
+                rsa.FromXmlString(XML);
+                byte[] encryptedData = rsa.Encrypt(Encoding.Default.GetBytes(plainText), false);
+                encryptedContent = Convert.ToBase64String(encryptedData);
+            }
+            return encryptedContent;
         }
     }
 
@@ -196,7 +208,7 @@
             //}
     
             // 鍔犲瘑澶勭悊
-            var userId = "FRadmin";
+            var userId = "1268";
             var encryptedUserId = RsaHelper.Encrypt(userId, SPK);
             string strToken = GetToken();
 
@@ -249,13 +261,13 @@
             var request = WebRequest.Create(url) as HttpWebRequest;
             request.Method = "POST";
             request.Timeout = 20000;
-            request.ContentType = "application/json; charset=utf-8";  // 淇敼涓篔SON鏍煎紡
+            request.ContentType = "application/x-www-form-urlencoded";  // 淇敼涓篔SON鏍煎紡
 
             // 鏋勫缓璇锋眰澶�
-            request.Headers.Add("appid", APPID);
-            request.Headers.Add("token", token);
-            request.Headers.Add("Content-Type", APPID);
-            request.Headers.Add("userId", encryptedUserId);
+            request.Headers.Set("appid", APPID);
+            request.Headers.Set("token", token);
+            request.Headers.Set("Content-Type", "application/x-www-form-urlencoded");
+            request.Headers.Set("userId", encryptedUserId);
             // 鍋囪闇�瑕佸姞瀵嗙殑userid浠庡叾浠栧湴鏂硅幏鍙栵紝杩欓噷闇�瑕佽ˉ鍏呰幏鍙栭�昏緫
 
             // 鏋勫缓璇锋眰浣�
diff --git a/service/Warehouse/MesXkyService.cs b/service/Warehouse/MesXkyService.cs
new file mode 100644
index 0000000..5e75066
--- /dev/null
+++ b/service/Warehouse/MesXkyService.cs
@@ -0,0 +1,79 @@
+锘縰sing MES.Service.Models;
+using Microsoft.IdentityModel.Tokens;
+using MySqlConnector;
+using NewPdaSqlServer.Controllers;
+using NewPdaSqlServer.DB;
+using NewPdaSqlServer.Dto.service;
+using NewPdaSqlServer.entity;
+using NewPdaSqlServer.util;
+using Newtonsoft.Json;
+using SqlSugar;
+using System.Collections;
+using System.Data;
+using System.Net;
+using System.Net.Http.Headers;
+using System.Security.Cryptography;
+using System.Text;
+using static Azure.Core.HttpHeader;
+
+namespace NewPdaSqlServer.service.QC;
+
+public class MesXkyService : RepositoryNoEntity
+{
+    public bool XKY_GET_DHD(dynamic entity)
+    {
+        string ErrorMsg = "";
+        ApiCommonParam Apiparam = ApiCommonParam.NewApiCommon();
+        try
+        {
+            string data_inserted = "";
+            ArrayList SQLStringList = new ArrayList();
+            // var client = new HttpClient();
+            var url = "https://openapi.xiekeyun.com/delivery/getNoList.json";
+            HttpClient httpClient = new HttpClient();
+            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+            string json = "{\"commonParam\":" + JsonConvert.SerializeObject(Apiparam) + ",\"body\":" + data_inserted + "}";
+            byte[] postData = Encoding.UTF8.GetBytes(json);
+
+            // 鍒涘缓璇锋眰瀵硅薄
+            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://openapi.xiekeyun.com/delivery/getNoList.json");
+            request.Method = "POST";
+            request.ContentType = "application/json";
+            request.ContentLength = postData.Length;
+
+            // 鍙戦�佽姹傛暟鎹�
+            using (Stream stream = request.GetRequestStream())
+            {
+                stream.Write(postData, 0, postData.Length);
+            }
+            dynamic responseJson;
+            // 鍙戦�佽姹傚苟鑾峰彇鍝嶅簲
+            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
+            using (Stream stream = response.GetResponseStream())
+            using (StreamReader reader = new StreamReader(stream))
+            {
+                string result2 = reader.ReadToEnd();
+
+                responseJson = JsonConvert.DeserializeObject(result2);
+
+            }
+        }
+        catch (Exception ex)
+        {
+            ErrorMsg = ex.Message;
+            return false;
+        }
+
+        return true;
+    }
+
+
+    public dynamic GetXkyDHD(dynamic entity)
+    {
+
+       return XKY_GET_DHD(entity);
+
+    }
+
+}
\ No newline at end of file
diff --git a/util/XkyApiHelper.cs b/util/XkyApiHelper.cs
new file mode 100644
index 0000000..fd073c9
--- /dev/null
+++ b/util/XkyApiHelper.cs
@@ -0,0 +1,150 @@
+锘縰sing Newtonsoft.Json;
+using System.Text;
+using NewPdaSqlServer.util;
+using System.Security.Cryptography;
+
+
+
+namespace NewPdaSqlServer.util
+{
+    /// SignUnit 绛惧悕灞炴�у父閲忕被
+    public class SignConst
+    {
+        public SignConst()
+        {
+            //this.appKey = "鍙橀噺_AppKey";
+            //this.operateCompanyCode = "鍙橀噺_operateCompanyCode";
+            //this.ownerCompanyCode = "鍙橀噺_ownerCompanyCode";
+            //this.appSecret = "鍙橀噺_appSecret";
+            this.appKey = "86d3ae868978beff0d39948c420ec4ff";
+            this.operateCompanyCode = "52265397";
+            this.ownerCompanyCode = "52265397";
+            this.appSecret = "978f5b950aefc3c1e0d4a56a562b0f8c";
+            this.version = "1.0";
+        }
+
+        public string appKey { get; set; }
+        public string version { get; set; }
+        public string operateCompanyCode { get; set; }
+        public string ownerCompanyCode { get; set; }
+        public string appSecret { get; set; }
+    }
+}
+
+namespace NewPdaSqlServer.util
+{
+    /// API鐩稿叧鍙傛暟瀹氫箟鐨勫叏灞�绫�
+    public partial class ApiGlobal
+    {
+        public ApiGlobal() { }
+
+        /// 鍒濆鍖�
+        public static void Init()
+        {
+            signConst = new SignConst();
+        }
+
+        public static SignConst signConst { get; set; }
+    }
+}
+
+
+namespace NewPdaSqlServer.util
+{
+    /// SignUtils 绛惧悕宸ュ叿绫�
+    public class SignUtils
+    {
+        public static MD5 md5 = MD5.Create();
+
+        public static string buildCurrentSign(IDictionary<string, string> parameters, String appSecret)
+        {
+            try
+            {
+                string secret = ":" + appSecret;
+                IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters, StringComparer.Ordinal);
+                IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
+                StringBuilder query = new StringBuilder();
+                while (dem.MoveNext())
+                {
+                    string key = dem.Current.Key;
+                    string value = dem.Current.Value;
+                    if (key == "sign")
+                    {
+                        continue;
+                    }
+                    if (!string.IsNullOrEmpty(key))
+                    {
+                        query.Append(value).Append(":");
+                    }
+                }
+                string strvalue = query.ToString().TrimEnd(':') + secret;
+                return MD5Encrypt32(strvalue);
+            }
+            catch (Exception)
+            {
+                throw new Exception("绛惧悕寮傚父!");
+            }
+        }
+
+        public static string MD5Encrypt32(string text)
+        {
+            string pwd = "";
+            // 鍔犲瘑鍚庢槸涓�涓瓧鑺傜被鍨嬬殑鏁扮粍锛岃繖閲岃娉ㄦ剰缂栫爜UTF8/Unicode鐨勯�夋嫨銆�
+            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(text));
+            // 閫氳繃浣跨敤寰幆锛屽皢瀛楄妭绫诲瀷鐨勬暟缁勮浆鎹负瀛楃涓诧紝姝ゅ瓧绗︿覆鏄父瑙勫瓧绗︽牸寮忓寲鎵�寰�
+            for (int i = 0; i < s.Length; i++)
+            {
+                //灏嗗緱鍒扮殑瀛楃涓蹭娇鐢ㄥ崄鍏繘鍒剁被鍨嬫牸寮忋�傛牸寮忓悗鐨勫瓧绗︽槸灏忓啓鐨勫瓧姣嶏紝濡傛灉浣跨敤澶у啓锛圶锛夊垯鏍煎紡鍚庣殑瀛楃鏄ぇ鍐欏瓧绗� 
+                pwd = pwd + s[i].ToString("x2");
+            }
+            return pwd.ToString().ToLower();
+        }
+
+        public static long GetTimestamp(DateTime d)
+        {
+            TimeSpan ts = d.ToUniversalTime() - new DateTime(1970, 1, 1);
+            return (long)ts.TotalSeconds;     //绮剧‘鍒扮
+        }
+    }
+}
+
+
+namespace NewPdaSqlServer.util
+{
+    /// ApiCommonParam API璇锋眰瀵瑰簲鐨凜ommon鍙傛暟绫�
+    public class ApiCommonParam
+    {
+        public ApiCommonParam() { }
+
+        public ApiCommonParam(string appKey, string version, string operateCompanyCode, string ownerCompanyCode, long timestamps)
+        {
+            this.appKey = appKey;
+            this.version = version;
+            this.operateCompanyCode = operateCompanyCode;
+            this.ownerCompanyCode = ownerCompanyCode;
+            this.timestamps = timestamps;
+        }
+
+        public string appKey { get; set; }//appKey    
+        public string version { get; set; }//鎺ュ彛鐗堟湰
+        public string ownerCompanyCode { get; set; }//鏁版嵁鎵�灞炲叕鍙哥紪鐮�
+        public string operateCompanyCode { get; set; }//鎿嶄綔鑰呮墍灞炲叕鍙哥紪鐮�
+        public string sign { get; set; }//绛惧悕
+        public long timestamps { get; set; }//璇锋眰鐨勬椂闂存埑
+        public object reserver { get; set; }//鎵╁睍瀛楁
+
+        /// 鏋勯�犲璞�
+        public static ApiCommonParam NewApiCommon()
+        {
+            //鏋勯�犲璞�
+            ApiCommonParam param = new ApiCommonParam(ApiGlobal.signConst.appKey, ApiGlobal.signConst.version, ApiGlobal.signConst.operateCompanyCode, ApiGlobal.signConst.ownerCompanyCode, SignUtils.GetTimestamp(DateTime.Now));
+            //璁$畻绛惧悕&璧嬪��
+            var jsonParam = JsonConvert.SerializeObject(param);
+            //JavaScriptSerializer json = new JavaScriptSerializer();
+            //string jsonParam = json.Serialize(param);
+            var paramDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonParam);
+            param.sign = SignUtils.buildCurrentSign(paramDict, ApiGlobal.signConst.appSecret);
+            return param;
+        }
+    }
+}
\ No newline at end of file

--
Gitblit v1.9.3