WeChatFunction.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. using System;
  2. using System.Collections.Generic;
  3. using Library;
  4. using System.Security.Cryptography.X509Certificates;
  5. using System.Security.Cryptography;
  6. using Microsoft.AspNetCore.Http;
  7. using System.Text;
  8. using System.IO;
  9. using System.Linq;
  10. using MySystem;
  11. using LitJson;
  12. using System.Net;
  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 WeChatFunction
  19. {
  20. private HttpContext _context;
  21. string AppId = "wx5417e0770bb19c4e";
  22. string MchId = "1611167423";
  23. string serialNo = "534165421BE2814DEC08F8D00BDAB9944B13646C";
  24. public WeChatFunction(HttpContext context)
  25. {
  26. _context = context;
  27. }
  28. public WeChatFunction()
  29. {
  30. }
  31. #region 领取会员卡
  32. public Dictionary<string, object> GetUserCard(int MerchantId)
  33. {
  34. string token = new WeChat.WeChatPublicClass(_context).getWXToken("wx5417e0770bb19c4e", "b853caabd367e1f3fd729c259ac8bee6");
  35. string resp = function.GetWebRequest("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=wx_card");
  36. JsonData jsonObj = JsonMapper.ToObject(resp);
  37. string ticket = jsonObj["ticket"].ToString();
  38. string timeStamp = function.ConvertDateTimeInt(DateTime.Now).ToString();
  39. string nonce_str = function.get_Random(12);
  40. var pay_param = new SortedList<string, string>
  41. {
  42. {"timeStamp", timeStamp},
  43. {"nonceStr", nonce_str},
  44. {"ticket", ticket}
  45. };
  46. var pay_param_str = String.Join("&", pay_param.Select(item => String.Format("{0}={1}", item.Key.Trim(), item.Value)).ToArray());
  47. string signature = new WeChat.WeChatPublicClass(_context).SHA1(pay_param_str);
  48. Dictionary<string, object> cardExt = new Dictionary<string, object>();
  49. cardExt.Add("timestamp", timeStamp);
  50. cardExt.Add("nonce_str", nonce_str);
  51. cardExt.Add("signature", signature);
  52. return cardExt;
  53. }
  54. #endregion
  55. #region 服务商平台JSAPI下单
  56. public Dictionary<string, string> Pay(string SubMchId, decimal PayMoney, string OrderNo, string Description, string OpenId, string Key, string NotifyUrl, bool IsAct = false)
  57. {
  58. Dictionary<string, string> return_result = new Dictionary<string, string>();
  59. int amount = (int)(PayMoney * 100);
  60. //具体请求参数
  61. SortedList<string, object> par = new SortedList<string, object>();
  62. par.Add("sp_appid", AppId); //服务商应用ID
  63. par.Add("sp_mchid", MchId); //服务商户号
  64. par.Add("sub_mchid", SubMchId); //子商户号
  65. par.Add("description", Description); //商品描述
  66. par.Add("out_trade_no", OrderNo); //商户订单号
  67. par.Add("notify_url", NotifyUrl); //服务商应用ID
  68. Dictionary<string, object> settle_info = new Dictionary<string, object>();
  69. settle_info.Add("profit_sharing", IsAct); //是否指定分账
  70. par.Add("settle_info", settle_info); //结算信息
  71. Dictionary<string, object> amountDic = new Dictionary<string, object>();
  72. amountDic.Add("total", amount); //总金额
  73. par.Add("amount", amountDic); //订单金额
  74. Dictionary<string, object> payer = new Dictionary<string, object>();
  75. payer.Add("sp_openid", OpenId); //用户在服务商appid下的唯一标识
  76. par.Add("payer", payer); //支付者
  77. string req = Newtonsoft.Json.JsonConvert.SerializeObject(par);
  78. function.WriteLog(req, "服务商平台JSAPI下单请求参数");
  79. try
  80. {
  81. function.WriteLog(serialNo, "服务商平台JSAPI下单请求参数");
  82. function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(par), "服务商平台JSAPI下单请求参数");
  83. string result = postJson("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi", req, prikey, MchId, serialNo);
  84. function.WriteLog(result, "服务商平台JSAPI下单请求参数");
  85. JsonData jsonObj = JsonMapper.ToObject(result);
  86. string timeStamp = function.ConvertDateTimeInt(DateTime.Now).ToString();
  87. string nonce_str = function.get_Random(12);
  88. string package = "prepay_id=" + jsonObj["prepay_id"].ToString();
  89. var pay_param = new SortedList<string, string>
  90. {
  91. {"appId", AppId},
  92. {"timeStamp", timeStamp},
  93. {"nonceStr", nonce_str},
  94. {"package", package},
  95. {"signType", "RSA"}
  96. };
  97. var pay_param_str = "";
  98. pay_param_str += AppId + "\n";
  99. pay_param_str += timeStamp + "\n";
  100. pay_param_str += nonce_str + "\n";
  101. pay_param_str += package + "\n";
  102. string paySign = Sign(pay_param_str, prikey);
  103. return_result.Add("appId", AppId);
  104. return_result.Add("timeStamp", timeStamp);
  105. return_result.Add("nonceStr", nonce_str);
  106. return_result.Add("package", package);
  107. return_result.Add("paySign", paySign);
  108. }
  109. catch (Exception ex)
  110. {
  111. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "服务商品台JSAPI下单异常");
  112. }
  113. return return_result;
  114. }
  115. #endregion
  116. #region 服务商平台申请退款API
  117. public Dictionary<string, string> Refund(string AppId, string MchId, string SubMchId, decimal RefundMoney, decimal TotalMoney, string OrderNo, string RefundNo, string Description, string OpenId, string Key, string NotifyUrl)
  118. {
  119. Dictionary<string, string> return_result = new Dictionary<string, string>();
  120. int refund = (int)(RefundMoney * 100);
  121. int amount = (int)(TotalMoney * 100);
  122. //具体请求参数
  123. SortedList<string, object> par = new SortedList<string, object>();
  124. par.Add("sub_mchid", SubMchId); //子商户号
  125. par.Add("out_trade_no", OrderNo); //商户订单号
  126. par.Add("out_refund_no", RefundNo); //商户退款单号
  127. Dictionary<string, object> amountDic = new Dictionary<string, object>();
  128. amountDic.Add("refund", refund); //退款金额
  129. amountDic.Add("total", amount); //原订单金额
  130. amountDic.Add("currency", "CNY"); //退款币种
  131. par.Add("amount", amountDic); //金额信息
  132. string req = Newtonsoft.Json.JsonConvert.SerializeObject(par);
  133. function.WriteLog(req, "服务商平台申请退款API");
  134. try
  135. {
  136. string merchantId = MchId; //商户号
  137. string serialNo = "62B64854B768D344249FDB9E6EF4A1232C000E84"; //证书编号
  138. string result = postJson("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds", req, prikey, merchantId, serialNo);
  139. function.WriteLog(result, "服务商平台申请退款API");
  140. JsonData jsonObj = JsonMapper.ToObject(result);
  141. return_result.Add("refund_id", jsonObj["refund_id"].ToString()); //微信支付退款单号
  142. return_result.Add("channel", jsonObj["channel"].ToString()); //退款渠道
  143. return_result.Add("user_received_account", jsonObj["user_received_account"].ToString()); //退款入账账户
  144. return_result.Add("status", jsonObj["status"].ToString()); //退款状态
  145. return_result.Add("payer_total", jsonObj["amount"]["payer_total"].ToString()); //用户支付金额
  146. return_result.Add("payer_refund", jsonObj["amount"]["payer_refund"].ToString()); //用户退款金额
  147. return_result.Add("settlement_refund", jsonObj["amount"]["settlement_refund"].ToString()); //应结退款金额
  148. return_result.Add("settlement_total", jsonObj["amount"]["settlement_total"].ToString()); //应结订单金额
  149. return_result.Add("discount_refund", jsonObj["amount"]["discount_refund"].ToString()); //优惠退款金额
  150. }
  151. catch (Exception ex)
  152. {
  153. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "服务商平台申请退款API异常");
  154. }
  155. return return_result;
  156. }
  157. #endregion
  158. #region 服务商平台查询单笔退款API
  159. public Dictionary<string, string> QueryRefund(string RefundNo)
  160. {
  161. Dictionary<string, string> return_result = new Dictionary<string, string>();
  162. try
  163. {
  164. string result = function.GetWebRequest("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds/" + RefundNo);
  165. JsonData jsonObj = JsonMapper.ToObject(result);
  166. return_result.Add("refund_id", jsonObj["refund_id"].ToString()); //微信支付退款单号
  167. return_result.Add("transaction_id", jsonObj["transaction_id"].ToString()); //微信支付订单号
  168. return_result.Add("out_trade_no", jsonObj["out_trade_no"].ToString()); //商户订单号
  169. return_result.Add("channel", jsonObj["channel"].ToString()); //退款渠道
  170. return_result.Add("user_received_account", jsonObj["user_received_account"].ToString()); //退款入账账户
  171. return_result.Add("status", jsonObj["status"].ToString()); //退款状态
  172. return_result.Add("total", jsonObj["amount"]["total"].ToString()); //订单金额
  173. return_result.Add("refund", jsonObj["amount"]["refund"].ToString()); //退款金额
  174. return_result.Add("payer_total", jsonObj["amount"]["payer_total"].ToString()); //用户支付金额
  175. return_result.Add("payer_refund", jsonObj["amount"]["payer_refund"].ToString()); //用户退款金额
  176. return_result.Add("settlement_refund", jsonObj["amount"]["settlement_refund"].ToString()); //应结退款金额
  177. return_result.Add("settlement_total", jsonObj["amount"]["settlement_total"].ToString()); //应结订单金额
  178. return_result.Add("discount_refund", jsonObj["amount"]["discount_refund"].ToString()); //优惠退款金额
  179. }
  180. catch (Exception ex)
  181. {
  182. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "服务商平台查询单笔退款API异常");
  183. }
  184. return return_result;
  185. }
  186. #endregion
  187. #region 服务商平台请求分账API
  188. public string ProfitShare(string SubMchId, string TradeNo, string OrderNo, List<ReceiverList> Receivers) //有活动分0.62%,没活动不分账
  189. {
  190. Dictionary<string, object> result = new Dictionary<string, object>();
  191. result.Add("sub_mchid", SubMchId); //子商户号
  192. result.Add("appid", AppId); //应用ID
  193. result.Add("transaction_id", TradeNo); //微信订单号
  194. result.Add("out_order_no", OrderNo); //商户分账单号
  195. result.Add("receivers", Receivers); //分账接收方列表
  196. result.Add("unfreeze_unsplit", true); //是否解冻剩余未分资金
  197. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  198. string resp = postJson("https://api.mch.weixin.qq.com/v3/profitsharing/orders", req, prikey, MchId, serialNo);
  199. return resp;
  200. //{"order_id":"30000104462023060249559178531","out_order_no":"2023060210583730173782834","receivers":[{"account":"1611167423","amount":3,"create_time":"2023-06-02T11:34:10+08:00","description":"服务费","detail_id":"36000104462023060269999025889","finish_time":"1970-01-01T08:00:00+08:00","result":"PENDING","type":"MERCHANT_ID"},{"account":"1645266943","amount":7,"create_time":"2023-06-02T11:34:10+08:00","description":"解冻给分账方","detail_id":"36000104462023060269999025890","finish_time":"1970-01-01T08:00:00+08:00","result":"PENDING","type":"MERCHANT_ID"}],"state":"PROCESSING","sub_mchid":"1645266943","transaction_id":"4200001833202306025522158377"}
  201. }
  202. #endregion
  203. #region 服务商平台请求分账回退API
  204. public string ProfitShareReturn(string SubMchId, string ReturnMchId, string OrderNo, string ReturnNo, decimal Amount)
  205. {
  206. int ReturnAmount = (int)(Amount * 100);
  207. Dictionary<string, object> result = new Dictionary<string, object>();
  208. result.Add("sub_mchid", SubMchId); //子商户号
  209. result.Add("out_order_no", OrderNo); //商户分账单号
  210. result.Add("out_return_no", ReturnNo); //商户回退单号
  211. result.Add("return_mchid", ReturnMchId); //回退商户号
  212. result.Add("amount", ReturnAmount); //回退金额
  213. result.Add("description", "用户退款"); //回退描述
  214. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  215. string resp = postJson("https://api.mch.weixin.qq.com/v3/profitsharing/return-orders", req, prikey, MchId, serialNo);
  216. return resp;
  217. }
  218. #endregion
  219. #region 服务商平台添加分账接收方API
  220. public string AddReceive(string SubMchId, string TypeName, string Account, string Name, string Relation)
  221. {
  222. Dictionary<string, object> result = new Dictionary<string, object>();
  223. result.Add("sub_mchid", SubMchId); //子商户号
  224. result.Add("appid", AppId); //应用ID
  225. result.Add("type", TypeName); //分账接收方类型 MERCHANT_ID:商户ID PERSONAL_OPENID:个人openid(由父商户APPID转换得到) PERSONAL_SUB_OPENID:个人sub_openid(由子商户APPID转换得到)
  226. result.Add("account", Account); //分账接收方账号
  227. if(!string.IsNullOrEmpty(Name))
  228. {
  229. result.Add("name", RSAEncrypt(Name)); //分账个人接收方姓名
  230. }
  231. result.Add("relation_type", Relation); //与分账方的关系类型 STORE:门店 STAFF:员工 STORE_OWNER:店主 PARTNER:合作伙伴 HEADQUARTER:总部 BRAND:品牌方 DISTRIBUTOR:分销商 USER:用户 SUPPLIER: 供应商 CUSTOM:自定义
  232. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  233. string resp = postJson("https://api.mch.weixin.qq.com/v3/profitsharing/receivers/add", req, prikey, MchId, serialNo);
  234. return resp;
  235. //{"account":"1611167423","name":"x+8m5jM4x2jSZLDOpN46Js9JyeNgUXkFSmGjCBN45QcSYUNPN86TOheRF64WlwDeO45E/walWPeZSksNN/LfJiB2fZRVun1CJuJ7zxePma8L7iDbKS92i+d38rvOmNTjLhKX64O8oJR4HMtFw1HryxJlUFgM5/ickJ79WGrX3GaVArWisgEzwOyxGBfGSL3ofJhi5TdTnrxHMzqYWv43DRvI9Ja5eMgFbgrGcn+JiJVKQcYj1L8tZ6xQeQCXkY6ubyDiV9wQps2nQA1Oh+UdFcS13Ex4FUSYLCczGFAl4EV8TBJQleZeC1p4ZJquJjje0uMjI2xB6S41yUBoN86gkA==","relation_type":"PARTNER","sub_mchid":"1645266943","type":"MERCHANT_ID"}
  236. }
  237. #endregion
  238. #region 服务商平台查询分账结果API
  239. public string QueryProfitShare(string SubMchId, string TradeNo, string OrderNo)
  240. {
  241. string resp = postJson("https://api.mch.weixin.qq.com/v3/profitsharing/orders/" + OrderNo + "?sub_mchid=" + SubMchId + "&transaction_id=" + TradeNo, "", prikey, MchId, serialNo, "GET");
  242. return resp;
  243. //{"order_id":"30000104462023060249559178531","out_order_no":"2023060210583730173782834","receivers":[{"account":"1611167423","amount":3,"create_time":"2023-06-02T11:34:10+08:00","description":"服务费","detail_id":"36000104462023060269999025889","finish_time":"2023-06-02T11:34:41+08:00","result":"SUCCESS","type":"MERCHANT_ID"},{"account":"1645266943","amount":7,"create_time":"2023-06-02T11:34:10+08:00","description":"解冻给分账方","detail_id":"36000104462023060269999025890","finish_time":"2023-06-02T11:34:41+08:00","result":"SUCCESS","type":"MERCHANT_ID"}],"state":"FINISHED","sub_mchid":"1645266943","transaction_id":"4200001833202306025522158377"}
  244. }
  245. #endregion
  246. #region 服务商平台解冻剩余资金API
  247. public string Unfreeze(string SubMchId, string TradeNo, string OrderNo, string Description)
  248. {
  249. Dictionary<string, object> result = new Dictionary<string, object>();
  250. result.Add("sub_mchid", SubMchId); //子商户号
  251. result.Add("transaction_id", TradeNo); //微信订单号
  252. result.Add("out_order_no", OrderNo); //商户分账单号
  253. result.Add("description", Description); //分账描述
  254. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  255. string resp = postJson("https://api.mch.weixin.qq.com/v3/profitsharing/orders/unfreeze", req, prikey, MchId, serialNo);
  256. return resp;
  257. }
  258. #endregion
  259. #region 微信客服
  260. public string CustomerServiceChat()
  261. {
  262. return "需要对接";
  263. }
  264. #endregion
  265. #region 获取平台证书
  266. public string GetPlatCert()
  267. {
  268. string merchantId = "1611167423"; //商户号
  269. string serialNo = "62B64854B768D344249FDB9E6EF4A1232C000E84"; //证书编号
  270. string result = postJson("https://api.mch.weixin.qq.com/v3/certificates", "", prikey, merchantId, serialNo, "GET");
  271. return result;
  272. //{"data":[{"effective_time":"2022-01-23T14:02:08+08:00","encrypt_certificate":{"algorithm":"AEAD_AES_256_GCM","associated_data":"certificate","ciphertext":"R+Z85w96Lv7GjtL2zGcwTugGAQkmRUnbKqpQ3VYU8cNcdamTTcJIOgFSXLdHykB1OC70onaRc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1CYeliYWDl9zl6vPUIeWqUQVADifUk7vrBLcchTqP39+OMJat1KkDE3p1rgwqk/c1DCaFGhtOevnma6E3DMRTPuI7AvUEk+pUKkNUyOEfXJeXA6yr2tHJN1u3Qg5mS/n5maGkhBW0M9fkkNkoC4KGXmGuh5pnl3bPCeugAg7ggtkLD7SqwotdgVbx33Lng2NlsOozJSFGhIZCCicCKwY5BFec73KrQJgo3VtrKppujssB4ag3nA3VcPunPg/ezMTdYbX6sl9/fRxgMafrQzOcKq0JdujwAz4Ecw6HCUyY420+P7qpUijnOhvTNX2ug37OwxhOcqGMzd8d4C4j7246CRgS7dahYOShtV8iBYbiy+F+kzudQgzKY9aD93IMjpNeuUpujzv9KRgqJRwxD9OxwnjMiLz+Mo4psNvl0GTSF3J+AdS6oeF5l4BmhGrXEEMe/KUook3m7s86MkoIKDM4nszNY8HdzzXdjfw+6Qh0oQd7eW0nwFPPtac0yVSjqrLQzKQsqYs4F7zF0eKwWyhRuR5N23Rk4MX49YIYMjXbWB6iiricIRiO1f6HJ8Xf6F66RFJy4dYR1uwWdKGk6kc5ZMSn0HE6zqGBdZQV3BsEkz6wJZ1ZOpFThr0vA9poN0F32c2mJyXDtB1qMytUiEKWyPy2sJ6BIXSB6DsDXQ9U9QGBnKjQ8+yvCglocPjs6JA84cjhXFeR8ElWNmZJ/njUlmlHQ==","nonce":"92306d7e8732"},"expire_time":"2027-01-22T14:02:08+08:00","serial_no":"62B64854B768D344249FDB9E6EF4A1232C000E84"}]}
  273. }
  274. public string AesGcmDecrypt(string associatedData, string nonce, string ciphertext)
  275. {
  276. GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine());
  277. AeadParameters aeadParameters = new AeadParameters(
  278. new KeyParameter(Encoding.UTF8.GetBytes("VyULlqfAW2gBfCNfLdupcL7zlha7d93F")),
  279. 128,
  280. Encoding.UTF8.GetBytes(nonce),
  281. Encoding.UTF8.GetBytes(associatedData));
  282. gcmBlockCipher.Init(false, aeadParameters);
  283. byte[] data = Convert.FromBase64String(ciphertext);
  284. byte[] plaintext = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
  285. int length = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plaintext, 0);
  286. gcmBlockCipher.DoFinal(plaintext, length);
  287. return Encoding.UTF8.GetString(plaintext);
  288. }
  289. public string GetPublicKey()
  290. {
  291. var result = Newtonsoft.Json.JsonConvert.DeserializeObject<certModel>(GetPlatCert());
  292. var cmodel = result.data.OrderByDescending(t => t.expire_time).FirstOrDefault();
  293. string pubkey = AesGcmDecrypt(cmodel.encrypt_certificate.associated_data, cmodel.encrypt_certificate.nonce, cmodel.encrypt_certificate.ciphertext);
  294. pubkey = pubkey.Replace("-----BEGIN CERTIFICATE-----", "").Replace("-----END CERTIFICATE-----", "").Replace("\n", "");
  295. return pubkey;
  296. }
  297. #endregion
  298. #region 敏感信息加密
  299. string pubkey = "MIID3DCCAsSgAwIBAgIUU0FlQhvigU3sCPjQC9q5lEsTZGwwDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsTFFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3QgQ0EwHhcNMjEwNjMwMDMwOTA5WhcNMjYwNjI5MDMwOTA5WjBuMRgwFgYDVQQDDA9UZW5wYXkuY29tIHNpZ24xEzARBgNVBAoMClRlbnBheS5jb20xHTAbBgNVBAsMFFRlbnBheS5jb20gQ0EgQ2VudGVyMQswCQYDVQQGDAJDTjERMA8GA1UEBwwIU2hlblpoZW4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC64SIwN1afgge2pjFeNZAlKz5ZdJw8W/hisaIJnkzbE/1oG5n+SgtbMLfBLBFp0zMyT5SP5ve5aJAvUjwnRwQoDG+4z3jE8vLyjFLxoy5sWGex8+FBC5hs81oAUHuazigi5NcSH9Ji/8Lq3zFh8Az4+ZchQ14SFhS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Q7kS5ul3OsGS9ZvOYeWsdUf73+Ic1WN/u1Fy5X2P/3rYNhtQKBgAIioAq8psFdy/itpJryaWdmDM6fM6ctp5P6VBWOVp2JGkOzHboiXFToJJBtmi7Rdp8AN1aYBbtVX1o0+RmfEiHqXn84GpSNT6tGirHvARi5ab3jvn+bkUWjZYOGd96hus8GirA+wQb/V92Ms3jS5VUS1HBfHaTGT5G2Slrr8YZu"; //私钥
  301. public string RSAEncrypt(string text)
  302. {
  303. byte[] publicKey = Convert.FromBase64String(pubkey);
  304. // var rsa = RSA.Create();
  305. // rsa.ImportRSAPublicKey(publicKey, out _);
  306. // var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.OaepSHA1);
  307. // return Convert.ToBase64String(buff);
  308. using (var x509 = new X509Certificate2(publicKey))
  309. {
  310. using (var rsa = x509.GetRSAPublicKey())
  311. {
  312. var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.OaepSHA1);
  313. return Convert.ToBase64String(buff);
  314. }
  315. }
  316. }
  317. public string postJson(string url, string postData, string privateKey, string merchantId, string serialNo, string method = "POST")
  318. {
  319. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  320. request.Method = method;
  321. request.ContentType = "application/json;charset=UTF-8";
  322. 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";
  323. request.Accept = "application/json";
  324. string Authorization = GetAuthorization(url, method, postData, privateKey, merchantId, "62B64854B768D344249FDB9E6EF4A1232C000E84");
  325. request.Headers.Add("Authorization", Authorization);
  326. request.Headers.Add("Wechatpay-Serial", serialNo);
  327. if (!string.IsNullOrEmpty(postData))
  328. {
  329. byte[] paramJsonBytes;
  330. paramJsonBytes = System.Text.Encoding.UTF8.GetBytes(postData);
  331. request.ContentLength = paramJsonBytes.Length;
  332. Stream writer;
  333. try
  334. {
  335. writer = request.GetRequestStream();
  336. }
  337. catch (Exception)
  338. {
  339. writer = null;
  340. Console.Write("连接服务器失败!");
  341. }
  342. writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
  343. writer.Close();
  344. }
  345. HttpWebResponse response;
  346. try
  347. {
  348. response = (HttpWebResponse)request.GetResponse();
  349. }
  350. catch (WebException ex)
  351. {
  352. response = ex.Response as HttpWebResponse;
  353. }
  354. Stream resStream = response.GetResponseStream();
  355. StreamReader reader = new StreamReader(resStream);
  356. string text = reader.ReadToEnd();
  357. return text;
  358. //{\"code\":\"PARAM_ERROR\",\"message\":\"请确认待处理的消息是否为加密后的密文\"}
  359. //{\"applyment_id\":2000002247709762}
  360. }
  361. #endregion
  362. #region 图片上传
  363. public string GetMediaId(string imgPath)
  364. {
  365. if (string.IsNullOrEmpty(imgPath))
  366. {
  367. return "";
  368. }
  369. string key = "wechatpic:" + function.MD5_16(imgPath);
  370. string media_id = RedisDbconn.Instance.Get<string>(key);
  371. if (!string.IsNullOrEmpty(media_id))
  372. {
  373. return media_id;
  374. }
  375. string filePath = function.getPath(imgPath);
  376. var filename = Path.GetFileName(filePath);
  377. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  378. Byte[] imgBytesIn = new Byte[fs.Length];
  379. fs.Read(imgBytesIn, 0, imgBytesIn.Length);
  380. fs.Close();
  381. byte[] hash = SHA256Managed.Create().ComputeHash(imgBytesIn);
  382. StringBuilder builder = new StringBuilder();
  383. for (int i = 0; i < hash.Length; i++)
  384. {
  385. builder.Append(hash[i].ToString("x2"));
  386. }
  387. var sha256 = builder.ToString();
  388. string metaStr = "{\"filename\":\""+ filename + "\",\"sha256\":\"" + sha256 + "\"}";
  389. media_id = UploadImgApi(metaStr, imgBytesIn, filename);
  390. return media_id;
  391. }
  392. public string UploadImgApi(string metaStr, Byte[] imgBytesIn,string filename)
  393. {
  394. string url = "https://api.mch.weixin.qq.com/v3/merchant/media/upload";
  395. string merchantId = "1611167423"; //商户号
  396. string serialNo = "62B64854B768D344249FDB9E6EF4A1232C000E84"; //证书编号
  397. string privateKey = prikey;
  398. #region 定义请求体中的内容 并转成二进制
  399. string boundary = "lc199aecd61b4653ef";
  400. string Enter = "\r\n";
  401. string campaignIDStr1
  402. = "--" + boundary
  403. + Enter
  404. + "Content-Disposition: form-data; name=\"meta\";"
  405. + Enter
  406. + "Content-Type:application/json;"
  407. + Enter
  408. + Enter
  409. + metaStr
  410. + Enter
  411. + "--" + boundary
  412. + Enter
  413. + "Content-Disposition:form-data;name=\"file\";filename=\""+ filename + "\";"
  414. + Enter
  415. + "Content-Type:image/jpeg"
  416. + Enter
  417. + Enter;
  418. byte[] byteData2
  419. = imgBytesIn;
  420. string campaignIDStr3
  421. = Enter
  422. + "--" + boundary
  423. + Enter;
  424. var byteData1 = System.Text.Encoding.UTF8.GetBytes(campaignIDStr1);
  425. var byteData3 = System.Text.Encoding.UTF8.GetBytes(campaignIDStr3);
  426. #endregion
  427. string transactionsResponse = UploadImg_postJson(url, byteData1, byteData2, byteData3, metaStr, privateKey, merchantId, serialNo, boundary, "POST");
  428. var result=JsonMapper.ToObject(transactionsResponse);
  429. return result["media_id"].ToString();
  430. }
  431. 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")
  432. {
  433. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  434. request.Method = method;
  435. //request.ContentType = "application/json;charset=UTF-8";
  436. request.ContentType = "multipart/form-data;boundary=" + boundary;
  437. 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";
  438. request.Accept = "application/json";
  439. string Authorization = GetAuthorization(url, method, metaStr, privateKey, merchantId, serialNo);
  440. request.Headers.Add("Authorization", Authorization);
  441. Stream writer;
  442. try
  443. {
  444. writer = request.GetRequestStream();
  445. }
  446. catch (Exception)
  447. {
  448. writer = null;
  449. }
  450. writer.Write(b1, 0, b1.Length);
  451. writer.Write(b2, 0, b2.Length);
  452. writer.Write(b3, 0, b3.Length);
  453. writer.Close();
  454. HttpWebResponse response;
  455. try
  456. {
  457. response = (HttpWebResponse)request.GetResponse();
  458. }
  459. catch (WebException ex)
  460. {
  461. response = ex.Response as HttpWebResponse;
  462. }
  463. Stream resStream = response.GetResponseStream();
  464. StreamReader reader = new StreamReader(resStream);
  465. string text = reader.ReadToEnd();
  466. return text;
  467. }
  468. protected string GetAuthorization(string url, string method, string jsonParame, string privateKey, string merchantId, string serialNo)
  469. {
  470. var uri = new Uri(url);
  471. string urlPath = uri.PathAndQuery;
  472. string nonce = Guid.NewGuid().ToString();
  473. var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
  474. //数据签名 HTTP请求方法\n接口地址的url\n请求时间戳\n请求随机串\n请求报文主体\n
  475. method = string.IsNullOrEmpty(method) ? "" : method;
  476. string message = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n", method, urlPath, timestamp, nonce, jsonParame);
  477. string signTxt = Sign(message, privateKey);
  478. //Authorization和格式
  479. string authorzationTxt = string.Format("WECHATPAY2-SHA256-RSA2048 mchid=\"{0}\",nonce_str=\"{1}\",timestamp=\"{2}\",serial_no=\"{3}\",signature=\"{4}\"",
  480. merchantId,
  481. nonce,
  482. timestamp,
  483. serialNo,
  484. signTxt
  485. );
  486. return authorzationTxt;
  487. }
  488. protected string Sign(string message, string privateKey)
  489. {
  490. byte[] keyData = Convert.FromBase64String(privateKey);
  491. byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
  492. var rsa = RSA.Create();
  493. rsa.ImportPkcs8PrivateKey(keyData, out _);
  494. return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
  495. // using (CngKey cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob))
  496. // using (RSACng rsa = new RSACng(cngKey))
  497. // {
  498. // return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
  499. // }
  500. }
  501. #endregion
  502. #region 获取文件sha256
  503. public string GetSha256(FileStream stream)
  504. {
  505. using (SHA256 mySHA256 = SHA256.Create())
  506. {
  507. byte[] hashValue = mySHA256.ComputeHash(stream);
  508. return Encoding.UTF8.GetString(hashValue);
  509. }
  510. }
  511. #endregion
  512. #region 判断长期
  513. public string CheckForever(DateTime? time)
  514. {
  515. if (time == null)
  516. {
  517. return "";
  518. }
  519. if (time.Value.Year >= 2050)
  520. {
  521. return "长期";
  522. }
  523. return time.Value.ToString("yyyy-MM-dd");
  524. }
  525. #endregion
  526. }
  527. }