WeChatFunctionForHD.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. using System;
  2. using System.Collections.Generic;
  3. using Library;
  4. using LitJson;
  5. using System.Linq;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.IO;
  10. using System.Net;
  11. using System.Web;
  12. using MySystem.Models;
  13. using Org.BouncyCastle.Crypto.Modes;
  14. using Org.BouncyCastle.Crypto.Parameters;
  15. using Org.BouncyCastle.Crypto.Engines;
  16. namespace MySystem
  17. {
  18. public class WeChatFunctionForHD
  19. {
  20. public readonly static WeChatFunctionForHD Instance = new WeChatFunctionForHD();
  21. private WeChatFunctionForHD()
  22. { }
  23. public string MchId = "178590308";
  24. public string ApiKey = "XTH7TLTSJH4SOZC3NVFQJ726B5VRNVO6"; //AesGcmDecrypt解密使用
  25. public string serialNo = "5293C873581457469F1BE1839EA127B08ADE2D7B";
  26. public string getSerialNo = "7C6E6AD5DA1F7EB4A1071F2333C2FED0D8CC3A46"; //平台证书序列号Wechatpay-Serial
  27. // string pubkey = "MIIEJzCCAw+gAw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gQDRIyFJFXfHPQx0/12bqkc8mLSNWGqO1OdxMoUYld7UHXgbNusM2w4f/3TsvZHSWEwAtP4BfeeuEfmXPMK8O8kvrEmbW/tsb3SZ5d1TTtmxb4LVFgMk05BY4G/XaLX4BwcqLPMkzJ1r3vHl86u3cqCLy0Pzb7TULgEaKKjwvPg2eQKBgQCxR7QOQ4IYF0NPoqN0M7P8TrdiHVBNuc+ic8aqmiSPmlenOlYtRIP+VIygWJzUAqkGRYZDfZN1f0TvwwpTPHTWN/vjFofkSubXGyaTaoGEiwe61in9WdHO7dEIcIr3EN3v3hbSZVtIU4MmCWHri4BeNqDkxZeOvLf8bVEY5Hn/vwKBgCq3bDMLSX3OgF7dUfdbnlVIM4izSICICAXc9caBxhO5OTEF1Ji5nXb3rKA2UDSQiGWUklUnrEynqz0y0eu0onE0VYyACyio0z4j70L21gwh5K01Y8r/03nzzaRH5PMWLGZ26+rWSEkiLnJzhN1hcl1bVTPB20ODagI3z9nsHx6xAoGBANoqZ97soR2+lCWxwaa4wrNb4DNLgI1ky91o3LpIFH/lX3grCpNBee9E6kW2XoSe7PUh8/WzQMxtyYEYvt9z+QPWcUjCjs9sexck/o+RTTVBM6JtOwKbUQzsQ0bUUSFAIw1ofGruQMHt/2v4ODFGCNI5FSy4ZruWGmN2d2t3uMP8"; //私钥
  31. #region 间连商户开户意愿确认(提交申请单)
  32. public string MerchantApply(MerchantAddInfo info)
  33. {
  34. Dictionary<string, object> result = new Dictionary<string, object>();
  35. string business_code = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
  36. result.Add("business_code", business_code); //业务申请编号
  37. WebCMSEntities dbpxc = new WebCMSEntities();
  38. //超级管理员信息
  39. Dictionary<string, object> contact_info = new Dictionary<string, object>();
  40. contact_info.Add("contact_type", "LEGAL"); //联系人类型
  41. contact_info.Add("name", RSAEncrypt(info.CertLegalPerson)); //联系人姓名
  42. contact_info.Add("id_card_number", RSAEncrypt(info.IdCardNumber)); //超级管理员身份证件号码
  43. contact_info.Add("contact_id_doc_type", "IDENTIFICATION_TYPE_IDCARD"); //联系人证件类型
  44. contact_info.Add("mobile", RSAEncrypt(info.MobilePhone)); //联系手机
  45. result.Add("contact_info", contact_info);
  46. //主体资料
  47. Dictionary<string, object> subject_info = new Dictionary<string, object>();
  48. string SubjectType = info.SubjectType;
  49. if(SubjectType == "SUBJECT_TYPE_SMALL") SubjectType = "SUBJECT_TYPE_MICRO";
  50. subject_info.Add("subject_type", SubjectType); //主体类型
  51. Dictionary<string, object> business_licence_info = new Dictionary<string, object>();
  52. business_licence_info.Add("licence_number", info.LicenseNumber); //注册号/统一社会信用代码
  53. business_licence_info.Add("licence_copy", GetMediaId("/" + info.LicenseCopy)); //营业执照照片
  54. business_licence_info.Add("merchant_name", info.CertMerchantName); //商户名称
  55. business_licence_info.Add("legal_person", info.CertLegalPerson); //个体户经营者/法人姓名
  56. business_licence_info.Add("company_address", info.BizStoreAddress); //注册地址
  57. string PeriodEnd = info.PeriodEnd.Value.ToString("yyyy-MM-dd");
  58. if(PeriodEnd.Substring(0, 4) == "2050")
  59. {
  60. PeriodEnd = "forever";
  61. }
  62. business_licence_info.Add("licence_valid_date", "[\"" + info.PeriodBegin.Value.ToString("yyyy-MM-dd") + "\",\"" + PeriodEnd + "\"]"); //营业执照有效日期
  63. subject_info.Add("business_licence_info", business_licence_info); //营业执照
  64. result.Add("subject_info", subject_info);
  65. Dictionary<string, object> identification_info = new Dictionary<string, object>();
  66. identification_info.Add("id_holder_type", "LEGAL"); //证件持有人类型
  67. identification_info.Add("identification_type", "IDENTIFICATION_TYPE_IDCARD"); //证件类型
  68. identification_info.Add("identification_name", RSAEncrypt(info.CertLegalPerson)); //身份证姓名
  69. identification_info.Add("identification_number", RSAEncrypt(info.IdCardNumber)); //身份证号码
  70. string CardPeriodEnd = info.CardPeriodEnd.Value.ToString("yyyy-MM-dd");
  71. if(CardPeriodEnd.Substring(0, 4) == "2050")
  72. {
  73. CardPeriodEnd = "forever";
  74. }
  75. identification_info.Add("identification_valid_date", "[\"" + info.CardPeriodBegin.Value.ToString("yyyy-MM-dd") + "\",\"" + CardPeriodEnd + "\"]"); //身份证有效期
  76. identification_info.Add("identification_front_copy", GetMediaId("/" + info.IdCardCopy)); //身份证件正面照片
  77. identification_info.Add("identification_back_copy", GetMediaId("/" + info.IdCardNational)); //身份证件反面照片
  78. bool owner = true;
  79. if(info.SubjectType == "SUBJECT_TYPE_ENTERPRISE")
  80. {
  81. identification_info.Add("identification_address", RSAEncrypt(info.IdCardAddress)); //身份证居住地址
  82. identification_info.Add("owner", owner);
  83. }
  84. result.Add("identification_info", identification_info); //经营者/法人身份证件
  85. //最终受益人信息列表(UBO)----仅企业需要填写
  86. if(info.SubjectType == "SUBJECT_TYPE_ENTERPRISE" && !owner)
  87. {
  88. List<Dictionary<string, object>> ubo_info_list = new List<Dictionary<string, object>>();
  89. Dictionary<string, object> ubo_info_list_item = new Dictionary<string, object>();
  90. ubo_info_list_item.Add("ubo_id_doc_type", "IDENTIFICATION_TYPE_IDCARD"); //证件类型
  91. ubo_info_list_item.Add("ubo_id_doc_copy", GetMediaId("/" + info.IdCardCopy)); //身份证件正面照片
  92. ubo_info_list_item.Add("ubo_id_doc_copy_back", GetMediaId("/" + info.IdCardNational)); //身份证件反面照片
  93. ubo_info_list_item.Add("ubo_id_doc_name", RSAEncrypt(info.CertLegalPerson)); //身份证姓名
  94. ubo_info_list_item.Add("ubo_id_doc_number", RSAEncrypt(info.IdCardNumber)); //身份证号码
  95. ubo_info_list_item.Add("ubo_id_doc_address", RSAEncrypt(info.IdCardAddress)); //身份证居住地址
  96. ubo_info_list_item.Add("ubo_period_begin", info.CardPeriodBegin.Value.ToString("yyyy-MM-dd")); //身份证有效期
  97. if(CardPeriodEnd == "forever")
  98. {
  99. CardPeriodEnd = "长期";
  100. }
  101. ubo_info_list_item.Add("ubo_period_end", CardPeriodEnd); //身份证有效期
  102. ubo_info_list.Add(ubo_info_list_item);
  103. result.Add("ubo_info_list", ubo_info_list);
  104. }
  105. dbpxc.Dispose();
  106. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  107. // 如何查看证书序列号?
  108. // 登陆商户平台【API安全】->【API证书】->【查看证书】,可查看商户API证书序列号。
  109. // 商户API证书和微信支付平台证书均可以使用第三方的证书解析工具,查看证书内容。或者使用openssl命令行工具查看证书序列号。
  110. // $ openssl x509 -in 1900009191_20180326_cert.pem -noout -serial
  111. // serial=1DDE55AD98ED71D6EDD4A4A16996DE7B47773A8C
  112. function.WriteLog(req, "间连商户开户意愿确认");
  113. string resp = postJson("https://api.mch.weixin.qq.com/v3/apply4subject/applyment", req);
  114. function.WriteLog(resp + "\n\n", "间连商户开户意愿确认");
  115. return resp;
  116. }
  117. #endregion
  118. #region 服务商平台查询申请单状态API
  119. public Dictionary<string, object> QueryMerchant(string BusinessCode)
  120. {
  121. Dictionary<string, object> return_result = new Dictionary<string, object>();
  122. try
  123. {
  124. string result = postJson("https://api.mch.weixin.qq.com/v3/apply4subject/applyment?applyment_id=" + BusinessCode, "", "GET");
  125. //"{\"applyment_state\":\"APPLYMENT_STATE_REJECTED\",\"reject_param\":\"licence_valid_date|cert_valid_date\",\"reject_reason\":\"有效期开始日期填写有误,请填写与营业执照上一致的开始日期,如影印件上无开始日期请填写成立日期/注册日期;有效期结束日期填写有误,请填写与营业执照上一致的日期,如影印件上无结束日期请填写“长期”\"}"
  126. //{\"applyment_id\":2000002247709762,\"applyment_state\":\"APPLYMENT_STATE_FINISHED\",\"applyment_state_msg\":\"商户入驻申请已完成\",\"audit_detail\":[],\"business_code\":\"0123456789\",\"sign_url\":\"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFv7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyUXE1czkzb3JlUjIxZHpXbTF5Y2YAAgRjbe9hAwQAjScA\",\"sub_mchid\":\"1619775262\"}
  127. JsonData jsonObj = JsonMapper.ToObject(result);
  128. bool logFlag = true;
  129. if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_AUDITING" || jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_TO_BE_SIGNED" || jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_TO_BE_CONFIRMED")
  130. {
  131. string check = RedisDbconn.Instance.Get<string>("WeChatQueryMerchant:" + BusinessCode + ":" + jsonObj["applyment_state"].ToString());
  132. if(!string.IsNullOrEmpty(check))
  133. {
  134. logFlag = false;
  135. }
  136. else
  137. {
  138. RedisDbconn.Instance.Set("WeChatQueryMerchant:" + BusinessCode + ":" + jsonObj["applyment_state"].ToString(), result);
  139. RedisDbconn.Instance.SetExpire("WeChatQueryMerchant:" + BusinessCode + ":" + jsonObj["applyment_state"].ToString(), 7200);
  140. }
  141. }
  142. if(logFlag)
  143. {
  144. function.WriteLog(BusinessCode, "服务商平台商户进件提交申请单API");
  145. function.WriteLog(result + "\n\n", "服务商平台查询申请单状态API");
  146. }
  147. return_result.Add("applyment_id", jsonObj["applyment_id"].ToString()); //微信支付申请单号
  148. return_result.Add("applyment_state", jsonObj["applyment_state"].ToString()); //申请单状态
  149. return_result.Add("applyment_state_msg", jsonObj["applyment_state_msg"].ToString()); //申请状态描述
  150. if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_TO_BE_SIGNED" || jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_FINISHED")
  151. {
  152. return_result.Add("sub_mchid", jsonObj["sub_mchid"].ToString());
  153. }
  154. if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_REJECTED")
  155. {
  156. List<Dictionary<string, string>> audit_detail = new List<Dictionary<string, string>>();
  157. JsonData auditObj = jsonObj["audit_detail"]; //驳回原因详情
  158. // for (int i = 0; i < auditObj.Count; i++)
  159. // {
  160. // Dictionary<string, string> row = new Dictionary<string, string>();
  161. // // row.Add("field", auditObj[i]["field"].ToString()); //字段名
  162. // // row.Add("field_name", auditObj[i]["field_name"].ToString()); //字段名称
  163. // row.Add("reject_reason", auditObj[i]["reject_reason"].ToString()); //驳回原因
  164. // audit_detail.Add(row);
  165. // }
  166. return_result.Add("reject_reason", auditObj[0]["reject_reason"].ToString());
  167. return_result.Add("audit_detail", audit_detail); //申请状态描述
  168. }
  169. if (result.Contains("\"sign_url\":"))
  170. {
  171. return_result.Add("sign_url", jsonObj["sign_url"].ToString()); //进件通过申请,待商家签约的地址
  172. }
  173. }
  174. catch (Exception ex)
  175. {
  176. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "服务商平台查询申请单状态API异常");
  177. }
  178. return return_result;
  179. }
  180. #endregion
  181. #region 获取平台证书
  182. public string GetPlatCert()
  183. {
  184. string merchantId = MchId; //商户号
  185. string result = postJson("https://api.mch.weixin.qq.com/v3/certificates", "", "GET");
  186. return result;
  187. }
  188. #endregion
  189. #region 敏感信息加密
  190. public string RSAEncrypt(string text)
  191. {
  192. byte[] publicKey = Convert.FromBase64String(pubkey);
  193. // var rsa = RSA.Create();
  194. // rsa.ImportRSAPublicKey(publicKey, out _);
  195. // var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.OaepSHA1);
  196. // return Convert.ToBase64String(buff);
  197. using (var x509 = new X509Certificate2(publicKey))
  198. {
  199. using (var rsa = x509.GetRSAPublicKey())
  200. {
  201. var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.OaepSHA1);
  202. return Convert.ToBase64String(buff);
  203. }
  204. }
  205. }
  206. public string RSADecrypt(string text)
  207. {
  208. byte[] key = Encoding.UTF8.GetBytes(AppConfig.WeChatParam.AesGemKey);
  209. byte[] nonce = Encoding.UTF8.GetBytes("1234567890ab");
  210. byte[] ciphertext = Convert.FromBase64String(text);
  211. AesGcm aes = new AesGcm(key);
  212. byte[] plaintext = new byte[ciphertext.Length];
  213. aes.Decrypt(nonce, ciphertext, plaintext, null);
  214. return Encoding.UTF8.GetString(plaintext);
  215. }
  216. public string AesGcmDecrypt(string associatedData, string nonce, string ciphertext)
  217. {
  218. // GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine());
  219. // AeadParameters aeadParameters = new AeadParameters(
  220. // new KeyParameter(Encoding.UTF8.GetBytes(AppConfig.WeChatParam.AesGemKey)),
  221. // 128,
  222. // Encoding.UTF8.GetBytes(nonce),
  223. // Encoding.UTF8.GetBytes(associatedData));
  224. // gcmBlockCipher.Init(false, aeadParameters);
  225. // byte[] data = Convert.FromBase64String(ciphertext);
  226. // byte[] plaintext = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
  227. // int length = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plaintext, 0);
  228. // gcmBlockCipher.DoFinal(plaintext, length);
  229. // return Encoding.UTF8.GetString(plaintext);
  230. byte[] key = Encoding.UTF8.GetBytes(ApiKey); // 256-bit key
  231. byte[] nonceByte = Encoding.UTF8.GetBytes(nonce); // 96-bit nonce
  232. byte[] cipherByte = Convert.FromBase64String(ciphertext);
  233. byte[] associatedByte = Encoding.UTF8.GetBytes(associatedData);
  234. GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine());
  235. AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, nonceByte, associatedByte);
  236. cipher.Init(false, parameters);
  237. byte[] plaintext = new byte[cipher.GetOutputSize(cipherByte.Length)];
  238. int len = cipher.ProcessBytes(cipherByte, 0, cipherByte.Length, plaintext, 0);
  239. cipher.DoFinal(plaintext, len);
  240. return Encoding.UTF8.GetString(plaintext);
  241. }
  242. public string postJson(string url, string postData, string method = "POST")
  243. {
  244. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  245. request.Method = method;
  246. request.ContentType = "application/json;charset=UTF-8";
  247. request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36";
  248. request.Accept = "application/json";
  249. string Authorization = GetAuthorization(url, method, postData, prikey, MchId, serialNo);
  250. request.Headers.Add("Authorization", Authorization);
  251. request.Headers.Add("Wechatpay-Serial", getSerialNo);
  252. if (!string.IsNullOrEmpty(postData))
  253. {
  254. byte[] paramJsonBytes;
  255. paramJsonBytes = System.Text.Encoding.UTF8.GetBytes(postData);
  256. request.ContentLength = paramJsonBytes.Length;
  257. Stream writer;
  258. try
  259. {
  260. writer = request.GetRequestStream();
  261. }
  262. catch (Exception ex)
  263. {
  264. writer = null;
  265. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "http请求异常");
  266. }
  267. writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
  268. writer.Close();
  269. }
  270. HttpWebResponse response;
  271. try
  272. {
  273. response = (HttpWebResponse)request.GetResponse();
  274. }
  275. catch (WebException ex)
  276. {
  277. response = ex.Response as HttpWebResponse;
  278. }
  279. Stream resStream = response.GetResponseStream();
  280. StreamReader reader = new StreamReader(resStream);
  281. string text = reader.ReadToEnd();
  282. return text;
  283. //{\"code\":\"PARAM_ERROR\",\"message\":\"请确认待处理的消息是否为加密后的密文\"}
  284. //{\"applyment_id\":2000002247709762}
  285. }
  286. #endregion
  287. #region 图片上传
  288. public string GetMediaId(string imgPath)
  289. {
  290. if (string.IsNullOrEmpty(imgPath))
  291. {
  292. return "";
  293. }
  294. if (imgPath.Contains(","))
  295. {
  296. imgPath = imgPath.Split(',')[0];
  297. }
  298. string key = "wechatpic:" + function.MD5_16(imgPath);
  299. string media_id = RedisDbconn.Instance.Get<string>(key);
  300. if (!string.IsNullOrEmpty(media_id))
  301. {
  302. return media_id;
  303. }
  304. string filePath = function.getPath(imgPath);
  305. var filename = Path.GetFileName(filePath);
  306. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  307. Byte[] imgBytesIn = new Byte[fs.Length];
  308. fs.Read(imgBytesIn, 0, imgBytesIn.Length);
  309. fs.Close();
  310. byte[] hash = SHA256Managed.Create().ComputeHash(imgBytesIn);
  311. StringBuilder builder = new StringBuilder();
  312. for (int i = 0; i < hash.Length; i++)
  313. {
  314. builder.Append(hash[i].ToString("x2"));
  315. }
  316. var sha256 = builder.ToString();
  317. string metaStr = "{\"filename\":\""+ filename + "\",\"sha256\":\"" + sha256 + "\"}";
  318. media_id = UploadImgApi(metaStr, imgBytesIn, filename);
  319. RedisDbconn.Instance.Set(key, media_id);
  320. return media_id;
  321. }
  322. public string UploadImgApi(string metaStr, Byte[] imgBytesIn,string filename)
  323. {
  324. string url = "https://api.mch.weixin.qq.com/v3/merchant/media/upload";
  325. string merchantId = MchId; //商户号
  326. string privateKey = prikey;
  327. #region 定义请求体中的内容 并转成二进制
  328. string boundary = "lc199aecd61b4653ef";
  329. string Enter = "\r\n";
  330. string campaignIDStr1
  331. = "--" + boundary
  332. + Enter
  333. + "Content-Disposition: form-data; name=\"meta\";"
  334. + Enter
  335. + "Content-Type:application/json;"
  336. + Enter
  337. + Enter
  338. + metaStr
  339. + Enter
  340. + "--" + boundary
  341. + Enter
  342. + "Content-Disposition:form-data;name=\"file\";filename=\""+ filename + "\";"
  343. + Enter
  344. + "Content-Type:image/jpeg"
  345. + Enter
  346. + Enter;
  347. byte[] byteData2
  348. = imgBytesIn;
  349. string campaignIDStr3
  350. = Enter
  351. + "--" + boundary
  352. + Enter;
  353. var byteData1 = System.Text.Encoding.UTF8.GetBytes(campaignIDStr1);
  354. var byteData3 = System.Text.Encoding.UTF8.GetBytes(campaignIDStr3);
  355. #endregion
  356. string transactionsResponse = UploadImg_postJson(url, byteData1, byteData2, byteData3, metaStr, privateKey, merchantId, serialNo, boundary, "POST");
  357. var result=JsonMapper.ToObject(transactionsResponse);
  358. return result["media_id"].ToString();
  359. }
  360. public string UploadImg_postJson(string url, byte[] b1, byte[] b2, byte[] b3, string metaStr, string privateKey, string merchantId, string serialNo, string boundary, string method = "POST")
  361. {
  362. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  363. request.Method = method;
  364. //request.ContentType = "application/json;charset=UTF-8";
  365. request.ContentType = "multipart/form-data;boundary=" + boundary;
  366. request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36";
  367. request.Accept = "application/json";
  368. string Authorization = GetAuthorization(url, method, metaStr, privateKey, merchantId, serialNo);
  369. request.Headers.Add("Authorization", Authorization);
  370. Stream writer;
  371. try
  372. {
  373. writer = request.GetRequestStream();
  374. }
  375. catch (Exception)
  376. {
  377. writer = null;
  378. }
  379. writer.Write(b1, 0, b1.Length);
  380. writer.Write(b2, 0, b2.Length);
  381. writer.Write(b3, 0, b3.Length);
  382. writer.Close();
  383. HttpWebResponse response;
  384. try
  385. {
  386. response = (HttpWebResponse)request.GetResponse();
  387. }
  388. catch (WebException ex)
  389. {
  390. response = ex.Response as HttpWebResponse;
  391. }
  392. Stream resStream = response.GetResponseStream();
  393. StreamReader reader = new StreamReader(resStream);
  394. string text = reader.ReadToEnd();
  395. return text;
  396. }
  397. protected string GetAuthorization(string url, string method, string jsonParame, string privateKey, string merchantId, string serialNo)
  398. {
  399. var uri = new Uri(url);
  400. string urlPath = uri.PathAndQuery;
  401. string nonce = Guid.NewGuid().ToString();
  402. var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
  403. //数据签名 HTTP请求方法\n接口地址的url\n请求时间戳\n请求随机串\n请求报文主体\n
  404. method = string.IsNullOrEmpty(method) ? "" : method;
  405. string message = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n", method, urlPath, timestamp, nonce, jsonParame);
  406. string signTxt = Sign(message, privateKey);
  407. //Authorization和格式
  408. string authorzationTxt = string.Format("WECHATPAY2-SHA256-RSA2048 mchid=\"{0}\",nonce_str=\"{1}\",timestamp=\"{2}\",serial_no=\"{3}\",signature=\"{4}\"",
  409. merchantId,
  410. nonce,
  411. timestamp,
  412. serialNo,
  413. signTxt
  414. );
  415. return authorzationTxt;
  416. }
  417. protected string Sign(string message, string privateKey)
  418. {
  419. byte[] keyData = Convert.FromBase64String(privateKey);
  420. byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
  421. var rsa = RSA.Create();
  422. rsa.ImportPkcs8PrivateKey(keyData, out _);
  423. return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
  424. // using (CngKey cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob))
  425. // using (RSACng rsa = new RSACng(cngKey))
  426. // {
  427. // return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
  428. // }
  429. }
  430. #endregion
  431. #region 获取文件sha256
  432. public string GetSha256(FileStream stream)
  433. {
  434. using (SHA256 mySHA256 = SHA256.Create())
  435. {
  436. byte[] hashValue = mySHA256.ComputeHash(stream);
  437. return Encoding.UTF8.GetString(hashValue);
  438. }
  439. }
  440. #endregion
  441. #region 判断长期
  442. public string CheckForever(DateTime? time)
  443. {
  444. if (time == null)
  445. {
  446. return "";
  447. }
  448. if (time.Value.Year >= 2050)
  449. {
  450. return "长期";
  451. }
  452. return time.Value.ToString("yyyy-MM-dd");
  453. }
  454. #endregion
  455. }
  456. }