WeChatFunction.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 MySystem.PxcModels;
  12. namespace MySystem
  13. {
  14. public class WeChatFunction
  15. {
  16. public WeChatFunction()
  17. {
  18. }
  19. #region 服务商平台商户进件提交申请单API
  20. public string MerchantCreate(PxcModels.MerchantAddInfo info, PxcModels.MerchantInfo merchant)
  21. {
  22. // pubkey = GetPublicKey();
  23. Dictionary<string, object> result = new Dictionary<string, object>();
  24. result.Add("business_code", info.BusinessCode); //业务申请编号
  25. PxcModels.WebCMSEntities dbpxc = new PxcModels.WebCMSEntities();
  26. //超级管理员信息
  27. Dictionary<string, object> contact_info = new Dictionary<string, object>();
  28. contact_info.Add("contact_name", RSAEncrypt(info.ContactName)); //超级管理员姓名
  29. contact_info.Add("contact_id_number", RSAEncrypt(info.ContactIdNumber)); //超级管理员身份证件号码
  30. // contact_info.Add("openid", info.OpenId); //超级管理员微信openid
  31. contact_info.Add("mobile_phone", RSAEncrypt(info.MobilePhone)); //联系手机
  32. contact_info.Add("contact_email", RSAEncrypt(info.ContactEmail)); //联系邮箱
  33. result.Add("contact_info", contact_info);
  34. //主体资料
  35. Dictionary<string, object> subject_info = new Dictionary<string, object>();
  36. subject_info.Add("subject_type", info.SubjectType); //主体类型
  37. Dictionary<string, object> business_license_info = new Dictionary<string, object>();
  38. business_license_info.Add("license_copy", GetMediaId("/bsserver_com" + info.LicenseCopy)); //营业执照照片
  39. business_license_info.Add("license_number", info.LicenseNumber); //注册号/统一社会信用代码
  40. business_license_info.Add("merchant_name", merchant.Name); //商户名称
  41. business_license_info.Add("legal_person", info.LegalPerson); //个体户经营者/法人姓名
  42. subject_info.Add("business_license_info", business_license_info); //营业执照
  43. // Dictionary<string, object> certificate_info = new Dictionary<string, object>();
  44. // certificate_info.Add("cert_copy", GetMediaId("/bsserver_com" + info.CertCopy)); //登记证书照片
  45. // certificate_info.Add("cert_type", info.CertType); //登记证书类型
  46. // certificate_info.Add("cert_number", info.CertNumber); //证书号
  47. // certificate_info.Add("merchant_name", info.CertMerchantName); //商户名称
  48. // certificate_info.Add("company_address", info.CompanyAddress); //注册地址
  49. // certificate_info.Add("legal_person", info.CertLegalPerson); //法人姓名
  50. // certificate_info.Add("period_begin", CheckForever(info.PeriodBegin)); //有效期限开始日期
  51. // certificate_info.Add("period_end", CheckForever(info.PeriodEnd)); //有效期限结束日期
  52. // subject_info.Add("certificate_info", certificate_info); //登记证书
  53. // Dictionary<string, object> organization_info = new Dictionary<string, object>();
  54. // organization_info.Add("organization_copy", GetMediaId("/bsserver_com" + info.OrganizationCopy)); //组织机构代码证照片
  55. // organization_info.Add("organization_code", info.OrganizationCode); //组织机构代码
  56. // organization_info.Add("org_period_begin", CheckForever(info.OrgPeriodBegin)); //组织机构代码证有效期开始日期
  57. // organization_info.Add("org_period_end", CheckForever(info.OrgPeriodEnd)); //组织机构代码证有效期结束日期
  58. // subject_info.Add("organization_info", organization_info); //组织机构代码证
  59. // subject_info.Add("certificate_letter_copy", GetMediaId("/bsserver_com" + info.CertificateLetterCopy)); //单位证明函照片
  60. Dictionary<string, object> identity_info = new Dictionary<string, object>();
  61. info.IdDocType = "IDENTIFICATION_TYPE_IDCARD";
  62. identity_info.Add("id_doc_type", info.IdDocType); //证件类型
  63. Dictionary<string, object> id_card_info = new Dictionary<string, object>();
  64. id_card_info.Add("id_card_copy", GetMediaId("/bsserver_com" + info.IdCardCopy)); //身份证人像面照片
  65. id_card_info.Add("id_card_national", GetMediaId("/bsserver_com" + info.IdCardNational)); //身份证人像面照片
  66. id_card_info.Add("id_card_name", RSAEncrypt(info.IdCardName)); //身份证姓名
  67. id_card_info.Add("id_card_number", RSAEncrypt(info.IdCardNumber)); //身份证号码
  68. id_card_info.Add("card_period_begin", CheckForever(info.CardPeriodBegin)); //身份证有效期开始时间
  69. id_card_info.Add("card_period_end", CheckForever(info.CardPeriodEnd)); //身份证有效期结束时间
  70. identity_info.Add("id_card_info", id_card_info); //身份证信息
  71. // identity_info.Add("owner", info.Owner == 1 ? true : false); //经营者/法人是否为受益人
  72. identity_info.Add("owner", true);
  73. subject_info.Add("identity_info", identity_info); //经营者/法人身份证件
  74. // if (info.Owner == 0)
  75. // {
  76. // Dictionary<string, object> ubo_info = new Dictionary<string, object>();
  77. // ubo_info.Add("id_type", info.UboInfoIdType); //证件类型
  78. // ubo_info.Add("id_card_copy", GetMediaId("/bsserver_com" + info.UboInfoIdCardCopy)); //身份证人像面照片
  79. // ubo_info.Add("id_card_national", GetMediaId("/bsserver_com" + info.UboInfoIdCardNational)); //身份证国徽面照片
  80. // ubo_info.Add("id_doc_copy", GetMediaId("/bsserver_com" + info.UboInfoIdDocCopy)); //证件照片
  81. // ubo_info.Add("name", RSAEncrypt(info.UboInfoName)); //受益人姓名
  82. // ubo_info.Add("id_number", RSAEncrypt(info.UboInfoIdNumber)); //证件号码
  83. // ubo_info.Add("id_period_begin", CheckForever(info.UboInfoIdPeriodBegin)); //证件有效期开始时间
  84. // ubo_info.Add("id_period_end", CheckForever(info.UboInfoIdPeriodEnd)); //证件有效期结束时间
  85. // subject_info.Add("ubo_info", ubo_info); //最终受益人信息(UBO)
  86. // }
  87. result.Add("subject_info", subject_info);
  88. //经营资料
  89. Dictionary<string, object> business_info = new Dictionary<string, object>();
  90. business_info.Add("merchant_shortname", info.MerchantShortname); //商户简称
  91. business_info.Add("service_phone", info.ServicePhone); //客服电话
  92. Dictionary<string, object> sales_info = new Dictionary<string, object>();
  93. info.SalesScenesType = "SALES_SCENES_STORE";
  94. sales_info.Add("sales_scenes_type", info.SalesScenesType.Split(',').ToList()); //经营场景类型
  95. Dictionary<string, object> biz_store_info = new Dictionary<string, object>();
  96. biz_store_info.Add("biz_store_name", info.BizStoreName); //门店名称
  97. PxcModels.OpenBankCityTable BizAddress = dbpxc.OpenBankCityTable.FirstOrDefault(m => m.CityName.EndsWith(info.BizAddressCode)) ?? new PxcModels.OpenBankCityTable();
  98. biz_store_info.Add("biz_address_code", BizAddress.Code); //门店省市编码
  99. biz_store_info.Add("biz_store_address", info.BizStoreAddress); //门店地址
  100. List<string> store_entrance_pic = new List<string>();
  101. store_entrance_pic.Add(GetMediaId("/bsserver_com" + info.StoreEntrancePic));
  102. biz_store_info.Add("store_entrance_pic", store_entrance_pic); //门店门头照片
  103. List<string> indoor_pic = new List<string>();
  104. indoor_pic.Add(GetMediaId("/bsserver_com" + info.IndoorPic));
  105. biz_store_info.Add("indoor_pic", indoor_pic); //店内环境照片
  106. biz_store_info.Add("biz_sub_appid", info.BizSubAppid); //线下场所对应的商家APPID
  107. sales_info.Add("biz_store_info", biz_store_info); //线下门店场景
  108. // Dictionary<string, object> mp_info = new Dictionary<string, object>();
  109. // mp_info.Add("mp_appid", info.MpAppid); //服务商公众号APPID
  110. // mp_info.Add("mp_sub_appid", info.MpSubAppid); //商家公众号APPID
  111. // mp_info.Add("mp_pics", GetMediaId("/bsserver_com" + info.MpPics)); //公众号页面截图
  112. // sales_info.Add("mp_info", mp_info); //公众号场景
  113. // Dictionary<string, object> mini_program_info = new Dictionary<string, object>();
  114. // mini_program_info.Add("mini_program_appid", info.MiniProgramAppid); //服务商小程序APPID
  115. // mini_program_info.Add("mini_program_sub_appid", info.MiniProgramSubAppid); //商家小程序APPID
  116. // mini_program_info.Add("mini_program_pics", GetMediaId("/bsserver_com" + info.MiniProgramPics)); //小程序截图
  117. // sales_info.Add("mini_program_info", mini_program_info); //小程序场景
  118. // Dictionary<string, object> app_info = new Dictionary<string, object>();
  119. // app_info.Add("app_appid", info.AppAppid); //服务商应用APPID
  120. // app_info.Add("app_sub_appid", info.AppSubAppid); //商家应用APPID
  121. // app_info.Add("app_pics", GetMediaId("/bsserver_com" + info.AppPics)); //商家应用APPID
  122. // sales_info.Add("app_info", app_info); //APP场景
  123. // Dictionary<string, object> web_info = new Dictionary<string, object>();
  124. // web_info.Add("domain", info.WebDomain); //互联网网站域名
  125. // web_info.Add("web_authorisation", GetMediaId("/bsserver_com" + info.WebAuthorisation)); //网站授权函
  126. // web_info.Add("web_appid", info.WebAppId); //互联网网站对应的商家APPID
  127. // sales_info.Add("web_info", web_info); //互联网网站场景
  128. // Dictionary<string, object> wework_info = new Dictionary<string, object>();
  129. // wework_info.Add("sub_corp_id", info.SubCorpId); //商家企业微信CorpID
  130. // wework_info.Add("wework_pics", GetMediaId("/bsserver_com" + info.WeworkPics)); //企业微信页面截图
  131. // sales_info.Add("wework_info", wework_info); //企业微信场景
  132. business_info.Add("sales_info", sales_info); //经营场景
  133. result.Add("business_info", business_info);
  134. //结算规则
  135. Dictionary<string, object> settlement_info = new Dictionary<string, object>();
  136. settlement_info.Add("settlement_id", info.SettlementId); //入驻结算规则ID
  137. string QualificationType = function.CheckNull(info.QualificationType);
  138. if (QualificationType.Contains(","))
  139. {
  140. QualificationType = QualificationType.Split(',')[0];
  141. }
  142. settlement_info.Add("qualification_type", QualificationType); //所属行业
  143. if (!string.IsNullOrEmpty(info.Qualifications))
  144. {
  145. List<string> Qualifications = new List<string>();
  146. Qualifications.Add(GetMediaId("/bsserver_com" + info.Qualifications));
  147. settlement_info.Add("qualifications", Qualifications); //特殊资质图片
  148. }
  149. settlement_info.Add("activities_id", info.ActivitiesId); //优惠费率活动ID
  150. settlement_info.Add("activities_rate", info.ActivitiesRate); //优惠费率活动值
  151. result.Add("settlement_info", settlement_info);
  152. //结算银行账户
  153. Dictionary<string, object> bank_account_info = new Dictionary<string, object>();
  154. bank_account_info.Add("bank_account_type", info.BankAccountType); //账户类型
  155. bank_account_info.Add("account_name", RSAEncrypt(info.AccountName)); //开户名称
  156. bank_account_info.Add("account_bank", info.AccountBank); //开户银行
  157. PxcModels.OpenBankCityTable BankAddress = dbpxc.OpenBankCityTable.FirstOrDefault(m => m.CityName.EndsWith(info.BankAddressCode)) ?? new PxcModels.OpenBankCityTable();
  158. bank_account_info.Add("bank_address_code", BankAddress.Code); //开户银行省市编码
  159. PxcModels.OpenBankTable BankBranch = dbpxc.OpenBankTable.FirstOrDefault(m => m.BankName == info.BankName) ?? new PxcModels.OpenBankTable();
  160. bank_account_info.Add("bank_branch_id", BankBranch.BankCode); //开户银行联行号
  161. bank_account_info.Add("bank_name", info.BankName); //开户银行全称(含支行)
  162. bank_account_info.Add("account_number", RSAEncrypt(info.AccountNumber)); //银行账号
  163. result.Add("bank_account_info", bank_account_info);
  164. dbpxc.Dispose();
  165. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  166. Dictionary<string, string> header = new Dictionary<string, string>();
  167. // 如何查看证书序列号?
  168. // 登陆商户平台【API安全】->【API证书】->【查看证书】,可查看商户API证书序列号。
  169. // 商户API证书和微信支付平台证书均可以使用第三方的证书解析工具,查看证书内容。或者使用openssl命令行工具查看证书序列号。
  170. // $ openssl x509 -in 1900009191_20180326_cert.pem -noout -serial
  171. // serial=1DDE55AD98ED71D6EDD4A4A16996DE7B47773A8C
  172. string merchantId = "1611167423"; //商户号
  173. string serialNo = "534165421BE2814DEC08F8D00BDAB9944B13646C"; //证书编号
  174. string resp = postJson("https://api.mch.weixin.qq.com/v3/applyment4sub/applyment/", req, prikey, merchantId, serialNo);
  175. function.WriteLog(resp, "商户进件日志");
  176. return resp;
  177. }
  178. #endregion
  179. #region 服务商平台查询申请单状态API
  180. public Dictionary<string, object> QueryMerchant(string BusinessCode)
  181. {
  182. Dictionary<string, object> return_result = new Dictionary<string, object>();
  183. try
  184. {
  185. string merchantId = "1611167423"; //商户号
  186. string serialNo = "534165421BE2814DEC08F8D00BDAB9944B13646C"; //证书编号
  187. string result = postJson("https://api.mch.weixin.qq.com/v3/applyment4sub/applyment/business_code/" + BusinessCode, "", prikey, merchantId, serialNo, "GET");
  188. function.WriteLog(result, "服务商平台查询申请单状态API");
  189. //{\"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\"}
  190. JsonData jsonObj = JsonMapper.ToObject(result);
  191. return_result.Add("applyment_id", jsonObj["applyment_id"].ToString()); //微信支付申请单号
  192. return_result.Add("applyment_state", jsonObj["applyment_state"].ToString()); //申请单状态
  193. return_result.Add("applyment_state_msg", jsonObj["applyment_state_msg"].ToString()); //申请状态描述
  194. if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_REJECTED")
  195. {
  196. List<Dictionary<string, string>> audit_detail = new List<Dictionary<string, string>>();
  197. JsonData auditObj = jsonObj["audit_detail"]; //驳回原因详情
  198. // for (int i = 0; i < auditObj.Count; i++)
  199. // {
  200. // Dictionary<string, string> row = new Dictionary<string, string>();
  201. // // row.Add("field", auditObj[i]["field"].ToString()); //字段名
  202. // // row.Add("field_name", auditObj[i]["field_name"].ToString()); //字段名称
  203. // row.Add("reject_reason", auditObj[i]["reject_reason"].ToString()); //驳回原因
  204. // audit_detail.Add(row);
  205. // }
  206. return_result.Add("reject_reason", auditObj[0]["reject_reason"].ToString());
  207. return_result.Add("audit_detail", audit_detail); //申请状态描述
  208. }
  209. if (result.Contains("\"sign_url\":"))
  210. {
  211. return_result.Add("sign_url", jsonObj["sign_url"].ToString()); //进件通过申请,待商家签约的地址
  212. }
  213. }
  214. catch (Exception ex)
  215. {
  216. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "服务商平台查询申请单状态API异常");
  217. }
  218. return return_result;
  219. }
  220. #endregion
  221. #region 服务商平台申请退款API
  222. public Dictionary<string, string> Refund(string AppId, string MchId, string SubMchId, decimal RefundMoney, decimal TotalMoney, string OrderNo, string RefundNo)
  223. {
  224. Dictionary<string, string> return_result = new Dictionary<string, string>();
  225. int refund = (int)(RefundMoney * 100);
  226. int amount = (int)(TotalMoney * 100);
  227. //具体请求参数
  228. SortedList<string, object> par = new SortedList<string, object>();
  229. par.Add("sub_mchid", SubMchId); //子商户号
  230. par.Add("out_trade_no", OrderNo); //商户订单号
  231. par.Add("out_refund_no", RefundNo); //商户退款单号
  232. Dictionary<string, object> amountDic = new Dictionary<string, object>();
  233. amountDic.Add("refund", refund); //退款金额
  234. amountDic.Add("total", amount); //原订单金额
  235. amountDic.Add("currency", "CNY"); //退款币种
  236. par.Add("amount", amountDic); //金额信息
  237. string req = Newtonsoft.Json.JsonConvert.SerializeObject(par);
  238. function.WriteLog(req, "服务商平台申请退款API");
  239. try
  240. {
  241. string merchantId = MchId; //商户号
  242. string serialNo = "534165421BE2814DEC08F8D00BDAB9944B13646C"; //证书编号
  243. string result = postJson("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds", req, prikey, merchantId, serialNo);
  244. function.WriteLog(result, "服务商平台申请退款API");
  245. JsonData jsonObj = JsonMapper.ToObject(result);
  246. return_result.Add("refund_id", jsonObj["refund_id"].ToString()); //微信支付退款单号
  247. return_result.Add("channel", jsonObj["channel"].ToString()); //退款渠道
  248. return_result.Add("user_received_account", jsonObj["user_received_account"].ToString()); //退款入账账户
  249. return_result.Add("status", jsonObj["status"].ToString()); //退款状态
  250. return_result.Add("payer_total", jsonObj["amount"]["payer_total"].ToString()); //用户支付金额
  251. return_result.Add("payer_refund", jsonObj["amount"]["payer_refund"].ToString()); //用户退款金额
  252. return_result.Add("settlement_refund", jsonObj["amount"]["settlement_refund"].ToString()); //应结退款金额
  253. return_result.Add("settlement_total", jsonObj["amount"]["settlement_total"].ToString()); //应结订单金额
  254. return_result.Add("discount_refund", jsonObj["amount"]["discount_refund"].ToString()); //优惠退款金额
  255. }
  256. catch (Exception ex)
  257. {
  258. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "服务商平台申请退款API异常");
  259. }
  260. return return_result;
  261. }
  262. #endregion
  263. #region 敏感信息加密
  264. // string pubkey = "MIIBCgKCAQEAxK9K2ElQ0rUMwNFW4xMx7kmkpDlp7WGQ8VffXLpudJBIrRVFWJN7dlinCGu67ZATf+/GZvLSSzQPWejHEsI9vUp9ej0x5iZDHGc9/shNUjd03ORkKo/Ohj3Ju19RzX4mh+GoinKGiuKX8CdGPXPe7UObKWyETrDcxrit6VCJQjE604aNtVeAUE+41mOpCLGzTgAKt4psfHxsBRtqlveH4cH/51ip+cGkC/u36gfDMKaRluVfFO3ETxDkI94BwNtnthcA4WDKha+wjtB6HIJ5xxHV550+cfdkl4j8UKU6pB+C5JRNgvjAf6ljg/TF+cGF1d8C6IbYYodYKloqN2DzrwIDAQAB"; //公钥
  265. string pubkey = "MIID3DCCAsSgAwIBAgIUU0FlQhvigU3sCPjQC9q5lEsTZGwwDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5j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KBgQD8L5KiN9XRFCvUH6rhUcs/8lmGR2N8zSTts+BNCwIPGQWE0UvbjroyNxVbq6cXXlZZ6H07vEAgaIrLIkwLgen2IwsuOiyaEMvRP9oGwC+LnpP+9sxbW5w5do1hfyeGiSPPgSYIWZMOOwX+qfqXDMM3whJP1hk4El87kC+kl2URPQKBgQC4kTc8ebWgMI1Ik5wibIN2khlYAum+cB6P/BU6OCU+32NwwiI0mfY5fEfbVgiVvYMP20p3Ir/VgOIdCH2zNecnTx4eVbmwLRbDWH/VEU5pMEEroauY6XyInZVIIW3bfd4GAyqzFqijIHdGIMN5ZKGQ4A5VVhnmrkTGmyQCP37xhwKBgQCaLW+Fc4NqTt240x+Cn6IWV1E6UfzV+QmBtb4E/BznJBIGsHqjIbBeMOUC5X/DPq6mSwf9dEr0RVXNeQtq4aMrEyOrwG8yReCF7naaN/cZcfrjHvmzRN/PFda766Q7kS5ul3OsGS9ZvOYeWsdUf73+Ic1WN/u1Fy5X2P/3rYNhtQKBgAIioAq8psFdy/itpJryaWdmDM6fM6ctp5P6VBWOVp2JGkOzHboiXFToJJBtmi7Rdp8AN1aYBbtVX1o0+RmfEiHqXn84GpSNT6tGirHvARi5ab3jvn+bkUWjZYOGd96hus8GirA+wQb/V92Ms3jS5VUS1HBfHaTGT5G2Slrr8YZu"; //私钥
  267. public string RSAEncrypt(string text)
  268. {
  269. byte[] publicKey = Convert.FromBase64String(pubkey);
  270. // var rsa = RSA.Create();
  271. // rsa.ImportRSAPublicKey(publicKey, out _);
  272. // var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.OaepSHA1);
  273. // return Convert.ToBase64String(buff);
  274. using (var x509 = new X509Certificate2(publicKey))
  275. {
  276. using (var rsa = x509.GetRSAPublicKey())
  277. {
  278. var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.OaepSHA1);
  279. return Convert.ToBase64String(buff);
  280. }
  281. }
  282. }
  283. public string postJson(string url, string postData, string privateKey, string merchantId, string serialNo, string method = "POST")
  284. {
  285. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  286. request.Method = method;
  287. request.ContentType = "application/json;charset=UTF-8";
  288. 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";
  289. request.Accept = "application/json";
  290. string Authorization = GetAuthorization(url, method, postData, privateKey, merchantId, "62B64854B768D344249FDB9E6EF4A1232C000E84");
  291. request.Headers.Add("Authorization", Authorization);
  292. request.Headers.Add("Wechatpay-Serial", serialNo);
  293. if (!string.IsNullOrEmpty(postData))
  294. {
  295. byte[] paramJsonBytes;
  296. paramJsonBytes = System.Text.Encoding.UTF8.GetBytes(postData);
  297. request.ContentLength = paramJsonBytes.Length;
  298. Stream writer;
  299. try
  300. {
  301. writer = request.GetRequestStream();
  302. }
  303. catch (Exception)
  304. {
  305. writer = null;
  306. Console.Write("连接服务器失败!");
  307. }
  308. writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
  309. writer.Close();
  310. }
  311. HttpWebResponse response;
  312. try
  313. {
  314. response = (HttpWebResponse)request.GetResponse();
  315. }
  316. catch (WebException ex)
  317. {
  318. response = ex.Response as HttpWebResponse;
  319. }
  320. Stream resStream = response.GetResponseStream();
  321. StreamReader reader = new StreamReader(resStream);
  322. string text = reader.ReadToEnd();
  323. return text;
  324. //{\"code\":\"PARAM_ERROR\",\"message\":\"请确认待处理的消息是否为加密后的密文\"}
  325. //{\"applyment_id\":2000002247709762}
  326. }
  327. #endregion
  328. #region 图片上传
  329. public string GetMediaId(string imgPath)
  330. {
  331. if (string.IsNullOrEmpty(imgPath))
  332. {
  333. return "";
  334. }
  335. string key = "wechatpic:" + function.MD5_16(imgPath);
  336. string media_id = RedisDbconn.Instance.Get<string>(key);
  337. if (!string.IsNullOrEmpty(media_id))
  338. {
  339. return media_id;
  340. }
  341. string filePath = function.getPath(imgPath);
  342. var filename = Path.GetFileName(filePath);
  343. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  344. Byte[] imgBytesIn = new Byte[fs.Length];
  345. fs.Read(imgBytesIn, 0, imgBytesIn.Length);
  346. fs.Close();
  347. byte[] hash = SHA256Managed.Create().ComputeHash(imgBytesIn);
  348. StringBuilder builder = new StringBuilder();
  349. for (int i = 0; i < hash.Length; i++)
  350. {
  351. builder.Append(hash[i].ToString("x2"));
  352. }
  353. var sha256 = builder.ToString();
  354. string metaStr = "{\"filename\":\""+ filename + "\",\"sha256\":\"" + sha256 + "\"}";
  355. media_id = UploadImgApi(metaStr, imgBytesIn, filename);
  356. RedisDbconn.Instance.Set(key, media_id);
  357. return media_id;
  358. }
  359. public string UploadImgApi(string metaStr, Byte[] imgBytesIn,string filename)
  360. {
  361. string url = "https://api.mch.weixin.qq.com/v3/merchant/media/upload";
  362. string merchantId = "1611167423"; //商户号
  363. string serialNo = "62B64854B768D344249FDB9E6EF4A1232C000E84"; //证书编号
  364. string privateKey = prikey;
  365. #region 定义请求体中的内容 并转成二进制
  366. string boundary = "lc199aecd61b4653ef";
  367. string Enter = "\r\n";
  368. string campaignIDStr1
  369. = "--" + boundary
  370. + Enter
  371. + "Content-Disposition: form-data; name=\"meta\";"
  372. + Enter
  373. + "Content-Type:application/json;"
  374. + Enter
  375. + Enter
  376. + metaStr
  377. + Enter
  378. + "--" + boundary
  379. + Enter
  380. + "Content-Disposition:form-data;name=\"file\";filename=\""+ filename + "\";"
  381. + Enter
  382. + "Content-Type:image/jpeg"
  383. + Enter
  384. + Enter;
  385. byte[] byteData2
  386. = imgBytesIn;
  387. string campaignIDStr3
  388. = Enter
  389. + "--" + boundary
  390. + Enter;
  391. var byteData1 = System.Text.Encoding.UTF8.GetBytes(campaignIDStr1);
  392. var byteData3 = System.Text.Encoding.UTF8.GetBytes(campaignIDStr3);
  393. #endregion
  394. string transactionsResponse = UploadImg_postJson(url, byteData1, byteData2, byteData3, metaStr, privateKey, merchantId, serialNo, boundary, "POST");
  395. var result=JsonMapper.ToObject(transactionsResponse);
  396. return result["media_id"].ToString();
  397. }
  398. 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")
  399. {
  400. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  401. request.Method = method;
  402. //request.ContentType = "application/json;charset=UTF-8";
  403. request.ContentType = "multipart/form-data;boundary=" + boundary;
  404. 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";
  405. request.Accept = "application/json";
  406. string Authorization = GetAuthorization(url, method, metaStr, privateKey, merchantId, serialNo);
  407. request.Headers.Add("Authorization", Authorization);
  408. Stream writer;
  409. try
  410. {
  411. writer = request.GetRequestStream();
  412. }
  413. catch (Exception)
  414. {
  415. writer = null;
  416. }
  417. writer.Write(b1, 0, b1.Length);
  418. writer.Write(b2, 0, b2.Length);
  419. writer.Write(b3, 0, b3.Length);
  420. writer.Close();
  421. HttpWebResponse response;
  422. try
  423. {
  424. response = (HttpWebResponse)request.GetResponse();
  425. }
  426. catch (WebException ex)
  427. {
  428. response = ex.Response as HttpWebResponse;
  429. }
  430. Stream resStream = response.GetResponseStream();
  431. StreamReader reader = new StreamReader(resStream);
  432. string text = reader.ReadToEnd();
  433. return text;
  434. }
  435. protected string GetAuthorization(string url, string method, string jsonParame, string privateKey, string merchantId, string serialNo)
  436. {
  437. var uri = new Uri(url);
  438. string urlPath = uri.PathAndQuery;
  439. string nonce = Guid.NewGuid().ToString();
  440. var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
  441. //数据签名 HTTP请求方法\n接口地址的url\n请求时间戳\n请求随机串\n请求报文主体\n
  442. method = string.IsNullOrEmpty(method) ? "" : method;
  443. string message = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n", method, urlPath, timestamp, nonce, jsonParame);
  444. string signTxt = Sign(message, privateKey);
  445. //Authorization和格式
  446. string authorzationTxt = string.Format("WECHATPAY2-SHA256-RSA2048 mchid=\"{0}\",nonce_str=\"{1}\",timestamp=\"{2}\",serial_no=\"{3}\",signature=\"{4}\"",
  447. merchantId,
  448. nonce,
  449. timestamp,
  450. serialNo,
  451. signTxt
  452. );
  453. return authorzationTxt;
  454. }
  455. protected string Sign(string message, string privateKey)
  456. {
  457. byte[] keyData = Convert.FromBase64String(privateKey);
  458. byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
  459. var rsa = RSA.Create();
  460. rsa.ImportPkcs8PrivateKey(keyData, out _);
  461. return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
  462. // using (CngKey cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob))
  463. // using (RSACng rsa = new RSACng(cngKey))
  464. // {
  465. // return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
  466. // }
  467. }
  468. #endregion
  469. #region 获取文件sha256
  470. public string GetSha256(FileStream stream)
  471. {
  472. using (SHA256 mySHA256 = SHA256.Create())
  473. {
  474. byte[] hashValue = mySHA256.ComputeHash(stream);
  475. return Encoding.UTF8.GetString(hashValue);
  476. }
  477. }
  478. #endregion
  479. #region 判断长期
  480. public string CheckForever(DateTime? time)
  481. {
  482. if (time == null)
  483. {
  484. return "";
  485. }
  486. if (time.Value.Year >= 2050)
  487. {
  488. return "长期";
  489. }
  490. return time.Value.ToString("yyyy-MM-dd");
  491. }
  492. #endregion
  493. }
  494. }