WeChatFunction.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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.Models;
  12. using Org.BouncyCastle.Crypto.Modes;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Crypto.Engines;
  15. namespace MySystem
  16. {
  17. public class WeChatFunction
  18. {
  19. public readonly static WeChatFunction Instance = new WeChatFunction();
  20. private WeChatFunction()
  21. { }
  22. public string AppId = "wx6e074b8e07b6577e";
  23. public string AppSecret = "883f9ef7831d8ca82168c3fd6dcfb750";
  24. public string MchId = "1613112281";
  25. public string serialNo = "14E9FD7F0981BEA23F94137607521CB51C4F76EF";
  26. public string platSerialNo = "";
  27. #region 服务商平台商户进件提交申请单API
  28. public string MerchantCreate(MerchantAddInfo info, MerchantInfo merchant)
  29. {
  30. // pubkey = GetPublicKey();
  31. Dictionary<string, object> result = new Dictionary<string, object>();
  32. result.Add("business_code", info.BusinessCode); //业务申请编号
  33. WebCMSEntities dbpxc = new WebCMSEntities();
  34. //超级管理员信息
  35. Dictionary<string, object> contact_info = new Dictionary<string, object>();
  36. contact_info.Add("contact_type", "LEGAL"); //超级管理员姓名
  37. contact_info.Add("contact_name", RSAEncrypt(info.ContactName)); //超级管理员姓名
  38. contact_info.Add("contact_id_number", RSAEncrypt(info.ContactIdNumber)); //超级管理员身份证件号码
  39. // contact_info.Add("openid", info.OpenId); //超级管理员微信openid
  40. contact_info.Add("mobile_phone", RSAEncrypt(info.MobilePhone)); //联系手机
  41. contact_info.Add("contact_email", RSAEncrypt(info.ContactEmail)); //联系邮箱
  42. result.Add("contact_info", contact_info);
  43. //主体资料
  44. Dictionary<string, object> subject_info = new Dictionary<string, object>();
  45. subject_info.Add("subject_type", info.SubjectType); //主体类型
  46. Dictionary<string, object> business_license_info = new Dictionary<string, object>();
  47. business_license_info.Add("license_copy", GetMediaId("/" + info.LicenseCopy)); //营业执照照片
  48. business_license_info.Add("license_number", info.LicenseNumber); //注册号/统一社会信用代码
  49. business_license_info.Add("merchant_name", merchant.Name); //商户名称
  50. business_license_info.Add("legal_person", info.LegalPerson); //个体户经营者/法人姓名
  51. subject_info.Add("business_license_info", business_license_info); //营业执照
  52. // Dictionary<string, object> certificate_info = new Dictionary<string, object>();
  53. // certificate_info.Add("cert_copy", GetMediaId("/" + info.CertCopy)); //登记证书照片
  54. // certificate_info.Add("cert_type", info.CertType); //登记证书类型
  55. // certificate_info.Add("cert_number", info.CertNumber); //证书号
  56. // certificate_info.Add("merchant_name", info.CertMerchantName); //商户名称
  57. // certificate_info.Add("company_address", info.CompanyAddress); //注册地址
  58. // certificate_info.Add("legal_person", info.CertLegalPerson); //法人姓名
  59. // certificate_info.Add("period_begin", CheckForever(info.PeriodBegin)); //有效期限开始日期
  60. // certificate_info.Add("period_end", CheckForever(info.PeriodEnd)); //有效期限结束日期
  61. // subject_info.Add("certificate_info", certificate_info); //登记证书
  62. // Dictionary<string, object> organization_info = new Dictionary<string, object>();
  63. // organization_info.Add("organization_copy", GetMediaId("/" + info.OrganizationCopy)); //组织机构代码证照片
  64. // organization_info.Add("organization_code", info.OrganizationCode); //组织机构代码
  65. // organization_info.Add("org_period_begin", CheckForever(info.OrgPeriodBegin)); //组织机构代码证有效期开始日期
  66. // organization_info.Add("org_period_end", CheckForever(info.OrgPeriodEnd)); //组织机构代码证有效期结束日期
  67. // subject_info.Add("organization_info", organization_info); //组织机构代码证
  68. // subject_info.Add("certificate_letter_copy", GetMediaId("/" + info.CertificateLetterCopy)); //单位证明函照片
  69. Dictionary<string, object> identity_info = new Dictionary<string, object>();
  70. info.IdDocType = "IDENTIFICATION_TYPE_IDCARD";
  71. identity_info.Add("id_holder_type", "LEGAL"); //证件持有人类型
  72. identity_info.Add("id_doc_type", info.IdDocType); //证件类型
  73. Dictionary<string, object> id_card_info = new Dictionary<string, object>();
  74. id_card_info.Add("id_card_copy", GetMediaId("/" + info.IdCardCopy)); //身份证人像面照片
  75. id_card_info.Add("id_card_national", GetMediaId("/" + info.IdCardNational)); //身份证人像面照片
  76. id_card_info.Add("id_card_name", RSAEncrypt(info.IdCardName)); //身份证姓名
  77. id_card_info.Add("id_card_number", RSAEncrypt(info.IdCardNumber)); //身份证号码
  78. id_card_info.Add("id_card_address", RSAEncrypt(info.IdCardAddress)); //身份证居住地址
  79. id_card_info.Add("card_period_begin", CheckForever(info.CardPeriodBegin)); //身份证有效期开始时间
  80. id_card_info.Add("card_period_end", CheckForever(info.CardPeriodEnd)); //身份证有效期结束时间
  81. identity_info.Add("id_card_info", id_card_info); //身份证信息
  82. // identity_info.Add("owner", info.Owner == 1 ? true : false); //经营者/法人是否为受益人
  83. identity_info.Add("owner", true);
  84. subject_info.Add("identity_info", identity_info); //经营者/法人身份证件
  85. // if (info.Owner == 0)
  86. // {
  87. // Dictionary<string, object> ubo_info = new Dictionary<string, object>();
  88. // ubo_info.Add("id_type", info.UboInfoIdType); //证件类型
  89. // ubo_info.Add("id_card_copy", GetMediaId("/" + info.UboInfoIdCardCopy)); //身份证人像面照片
  90. // ubo_info.Add("id_card_national", GetMediaId("/" + info.UboInfoIdCardNational)); //身份证国徽面照片
  91. // ubo_info.Add("id_doc_copy", GetMediaId("/" + info.UboInfoIdDocCopy)); //证件照片
  92. // ubo_info.Add("name", RSAEncrypt(info.UboInfoName)); //受益人姓名
  93. // ubo_info.Add("id_number", RSAEncrypt(info.UboInfoIdNumber)); //证件号码
  94. // ubo_info.Add("id_period_begin", CheckForever(info.UboInfoIdPeriodBegin)); //证件有效期开始时间
  95. // ubo_info.Add("id_period_end", CheckForever(info.UboInfoIdPeriodEnd)); //证件有效期结束时间
  96. // subject_info.Add("ubo_info", ubo_info); //最终受益人信息(UBO)
  97. // }
  98. result.Add("subject_info", subject_info);
  99. //经营资料
  100. Dictionary<string, object> business_info = new Dictionary<string, object>();
  101. business_info.Add("merchant_shortname", info.MerchantShortname); //商户简称
  102. business_info.Add("service_phone", info.ServicePhone); //客服电话
  103. Dictionary<string, object> sales_info = new Dictionary<string, object>();
  104. info.SalesScenesType = "SALES_SCENES_STORE";
  105. sales_info.Add("sales_scenes_type", info.SalesScenesType.Split(',').ToList()); //经营场景类型
  106. Dictionary<string, object> biz_store_info = new Dictionary<string, object>();
  107. biz_store_info.Add("biz_store_name", info.BizStoreName); //门店名称
  108. OpenBankCityTable BizAddress = dbpxc.OpenBankCityTable.FirstOrDefault(m => m.CityName.EndsWith(info.BizAddressCode)) ?? new OpenBankCityTable();
  109. biz_store_info.Add("biz_address_code", BizAddress.Code); //门店省市编码
  110. biz_store_info.Add("biz_store_address", info.BizStoreAddress); //门店地址
  111. List<string> store_entrance_pic = new List<string>();
  112. store_entrance_pic.Add(GetMediaId("/" + info.StoreEntrancePic));
  113. biz_store_info.Add("store_entrance_pic", store_entrance_pic); //门店门头照片
  114. List<string> indoor_pic = new List<string>();
  115. indoor_pic.Add(GetMediaId("/" + info.IndoorPic));
  116. biz_store_info.Add("indoor_pic", indoor_pic); //店内环境照片
  117. biz_store_info.Add("biz_sub_appid", info.BizSubAppid); //线下场所对应的商家APPID
  118. sales_info.Add("biz_store_info", biz_store_info); //线下门店场景
  119. // Dictionary<string, object> mp_info = new Dictionary<string, object>();
  120. // mp_info.Add("mp_appid", info.MpAppid); //服务商公众号APPID
  121. // mp_info.Add("mp_sub_appid", info.MpSubAppid); //商家公众号APPID
  122. // mp_info.Add("mp_pics", GetMediaId("/" + info.MpPics)); //公众号页面截图
  123. // sales_info.Add("mp_info", mp_info); //公众号场景
  124. // Dictionary<string, object> mini_program_info = new Dictionary<string, object>();
  125. // mini_program_info.Add("mini_program_appid", info.MiniProgramAppid); //服务商小程序APPID
  126. // mini_program_info.Add("mini_program_sub_appid", info.MiniProgramSubAppid); //商家小程序APPID
  127. // mini_program_info.Add("mini_program_pics", GetMediaId("/" + info.MiniProgramPics)); //小程序截图
  128. // sales_info.Add("mini_program_info", mini_program_info); //小程序场景
  129. // Dictionary<string, object> app_info = new Dictionary<string, object>();
  130. // app_info.Add("app_appid", info.AppAppid); //服务商应用APPID
  131. // app_info.Add("app_sub_appid", info.AppSubAppid); //商家应用APPID
  132. // app_info.Add("app_pics", GetMediaId("/" + info.AppPics)); //商家应用APPID
  133. // sales_info.Add("app_info", app_info); //APP场景
  134. // Dictionary<string, object> web_info = new Dictionary<string, object>();
  135. // web_info.Add("domain", info.WebDomain); //互联网网站域名
  136. // web_info.Add("web_authorisation", GetMediaId("/" + info.WebAuthorisation)); //网站授权函
  137. // web_info.Add("web_appid", info.WebAppId); //互联网网站对应的商家APPID
  138. // sales_info.Add("web_info", web_info); //互联网网站场景
  139. // Dictionary<string, object> wework_info = new Dictionary<string, object>();
  140. // wework_info.Add("sub_corp_id", info.SubCorpId); //商家企业微信CorpID
  141. // wework_info.Add("wework_pics", GetMediaId("/" + info.WeworkPics)); //企业微信页面截图
  142. // sales_info.Add("wework_info", wework_info); //企业微信场景
  143. business_info.Add("sales_info", sales_info); //经营场景
  144. result.Add("business_info", business_info);
  145. //结算规则
  146. Dictionary<string, object> settlement_info = new Dictionary<string, object>();
  147. settlement_info.Add("settlement_id", info.SettlementId); //入驻结算规则ID
  148. string QualificationType = function.CheckNull(info.QualificationType);
  149. if (QualificationType.Contains(","))
  150. {
  151. QualificationType = QualificationType.Split(',')[0];
  152. }
  153. settlement_info.Add("qualification_type", QualificationType); //所属行业
  154. if (!string.IsNullOrEmpty(info.Qualifications))
  155. {
  156. List<string> Qualifications = new List<string>();
  157. Qualifications.Add(GetMediaId("/" + info.Qualifications));
  158. settlement_info.Add("qualifications", Qualifications); //特殊资质图片
  159. }
  160. settlement_info.Add("activities_id", info.ActivitiesId); //优惠费率活动ID
  161. settlement_info.Add("activities_rate", info.ActivitiesRate); //优惠费率活动值
  162. result.Add("settlement_info", settlement_info);
  163. //结算银行账户
  164. Dictionary<string, object> bank_account_info = new Dictionary<string, object>();
  165. bank_account_info.Add("bank_account_type", info.BankAccountType); //账户类型
  166. bank_account_info.Add("account_name", RSAEncrypt(info.AccountName)); //开户名称
  167. bank_account_info.Add("account_bank", info.AccountBank); //开户银行
  168. OpenBankCityTable BankAddress = dbpxc.OpenBankCityTable.FirstOrDefault(m => m.CityName.EndsWith(info.BankAddressCode)) ?? new OpenBankCityTable();
  169. bank_account_info.Add("bank_address_code", BankAddress.Code); //开户银行省市编码
  170. OpenBankTable BankBranch = dbpxc.OpenBankTable.FirstOrDefault(m => m.BankName == info.BankName) ?? new OpenBankTable();
  171. bank_account_info.Add("bank_branch_id", BankBranch.BankCode); //开户银行联行号
  172. bank_account_info.Add("bank_name", info.BankName); //开户银行全称(含支行)
  173. bank_account_info.Add("account_number", RSAEncrypt(info.AccountNumber)); //银行账号
  174. result.Add("bank_account_info", bank_account_info);
  175. dbpxc.Dispose();
  176. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  177. Dictionary<string, string> header = new Dictionary<string, string>();
  178. // 如何查看证书序列号?
  179. // 登陆商户平台【API安全】->【API证书】->【查看证书】,可查看商户API证书序列号。
  180. // 商户API证书和微信支付平台证书均可以使用第三方的证书解析工具,查看证书内容。或者使用openssl命令行工具查看证书序列号。
  181. // $ openssl x509 -in 1900009191_20180326_cert.pem -noout -serial
  182. // serial=1DDE55AD98ED71D6EDD4A4A16996DE7B47773A8C
  183. function.WriteLog(req, "服务商平台商户进件提交申请单API");
  184. string resp = postJson("https://api.mch.weixin.qq.com/v3/applyment4sub/applyment/", req, prikey, MchId, serialNo);
  185. function.WriteLog(resp + "\n\n", "服务商平台商户进件提交申请单API");
  186. return resp;
  187. }
  188. #endregion
  189. #region 服务商平台查询申请单状态API
  190. public Dictionary<string, object> QueryMerchant(string BusinessCode)
  191. {
  192. Dictionary<string, object> return_result = new Dictionary<string, object>();
  193. try
  194. {
  195. string result = postJson("https://api.mch.weixin.qq.com/v3/applyment4sub/applyment/business_code/" + BusinessCode, "", prikey, MchId, serialNo, "GET");
  196. //{\"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\"}
  197. JsonData jsonObj = JsonMapper.ToObject(result);
  198. bool logFlag = true;
  199. 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")
  200. {
  201. string check = RedisDbconn.Instance.Get<string>("WeChatQueryMerchant:" + BusinessCode + ":" + jsonObj["applyment_state"].ToString());
  202. if(!string.IsNullOrEmpty(check))
  203. {
  204. logFlag = false;
  205. }
  206. else
  207. {
  208. RedisDbconn.Instance.Set("WeChatQueryMerchant:" + BusinessCode + ":" + jsonObj["applyment_state"].ToString(), result);
  209. RedisDbconn.Instance.SetExpire("WeChatQueryMerchant:" + BusinessCode + ":" + jsonObj["applyment_state"].ToString(), 7200);
  210. }
  211. }
  212. if(logFlag)
  213. {
  214. function.WriteLog(BusinessCode, "服务商平台商户进件提交申请单API");
  215. function.WriteLog(result + "\n\n", "服务商平台查询申请单状态API");
  216. }
  217. return_result.Add("applyment_id", jsonObj["applyment_id"].ToString()); //微信支付申请单号
  218. return_result.Add("applyment_state", jsonObj["applyment_state"].ToString()); //申请单状态
  219. return_result.Add("applyment_state_msg", jsonObj["applyment_state_msg"].ToString()); //申请状态描述
  220. if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_TO_BE_SIGNED")
  221. {
  222. return_result.Add("sub_mchid", jsonObj["sub_mchid"].ToString());
  223. }
  224. if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_REJECTED")
  225. {
  226. List<Dictionary<string, string>> audit_detail = new List<Dictionary<string, string>>();
  227. JsonData auditObj = jsonObj["audit_detail"]; //驳回原因详情
  228. // for (int i = 0; i < auditObj.Count; i++)
  229. // {
  230. // Dictionary<string, string> row = new Dictionary<string, string>();
  231. // // row.Add("field", auditObj[i]["field"].ToString()); //字段名
  232. // // row.Add("field_name", auditObj[i]["field_name"].ToString()); //字段名称
  233. // row.Add("reject_reason", auditObj[i]["reject_reason"].ToString()); //驳回原因
  234. // audit_detail.Add(row);
  235. // }
  236. return_result.Add("reject_reason", auditObj[0]["reject_reason"].ToString());
  237. return_result.Add("audit_detail", audit_detail); //申请状态描述
  238. }
  239. if (result.Contains("\"sign_url\":"))
  240. {
  241. return_result.Add("sign_url", jsonObj["sign_url"].ToString()); //进件通过申请,待商家签约的地址
  242. }
  243. }
  244. catch (Exception ex)
  245. {
  246. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "服务商平台查询申请单状态API异常");
  247. }
  248. return return_result;
  249. }
  250. #endregion
  251. #region 服务商平台申请退款API
  252. public Dictionary<string, string> Refund(string SubMchId, decimal RefundMoney, decimal TotalMoney, string OrderNo, string RefundNo, string Reason = "")
  253. {
  254. Dictionary<string, string> return_result = new Dictionary<string, string>();
  255. int refund = (int)(RefundMoney * 100);
  256. int amount = (int)(TotalMoney * 100);
  257. //具体请求参数
  258. SortedList<string, object> par = new SortedList<string, object>();
  259. par.Add("sub_mchid", SubMchId); //子商户号
  260. par.Add("out_trade_no", OrderNo); //商户订单号
  261. par.Add("out_refund_no", RefundNo); //商户退款单号
  262. par.Add("reason", Reason); //退款原因
  263. Dictionary<string, object> amountDic = new Dictionary<string, object>();
  264. amountDic.Add("refund", refund); //退款金额
  265. amountDic.Add("total", amount); //原订单金额
  266. amountDic.Add("currency", "CNY"); //退款币种
  267. par.Add("amount", amountDic); //金额信息
  268. string req = Newtonsoft.Json.JsonConvert.SerializeObject(par);
  269. try
  270. {
  271. function.WriteLog(req, "服务商平台申请退款API");
  272. string result = postJson("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds", req, prikey, MchId, serialNo);
  273. function.WriteLog(result + "\n\n", "服务商平台申请退款API");
  274. JsonData jsonObj = JsonMapper.ToObject(result);
  275. return_result.Add("refund_id", jsonObj["refund_id"].ToString()); //微信支付退款单号
  276. return_result.Add("channel", jsonObj["channel"].ToString()); //退款渠道
  277. return_result.Add("user_received_account", jsonObj["user_received_account"].ToString()); //退款入账账户
  278. return_result.Add("status", jsonObj["status"].ToString()); //退款状态
  279. return_result.Add("payer_total", jsonObj["amount"]["payer_total"].ToString()); //用户支付金额
  280. return_result.Add("payer_refund", jsonObj["amount"]["payer_refund"].ToString()); //用户退款金额
  281. return_result.Add("settlement_refund", jsonObj["amount"]["settlement_refund"].ToString()); //应结退款金额
  282. return_result.Add("settlement_total", jsonObj["amount"]["settlement_total"].ToString()); //应结订单金额
  283. return_result.Add("discount_refund", jsonObj["amount"]["discount_refund"].ToString()); //优惠退款金额
  284. }
  285. catch (Exception ex)
  286. {
  287. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "服务商平台申请退款API异常");
  288. }
  289. return return_result;
  290. }
  291. #endregion
  292. #region 服务商平台请求分账API
  293. public string ProfitShare(string SubMchId, string TradeNo, string OrderNo, List<ReceiverList> Receivers) //有活动分0.62%,没活动不分账
  294. {
  295. Dictionary<string, object> result = new Dictionary<string, object>();
  296. result.Add("sub_mchid", SubMchId); //子商户号
  297. result.Add("appid", AppId); //应用ID
  298. result.Add("transaction_id", TradeNo); //微信订单号
  299. result.Add("out_order_no", OrderNo); //商户分账单号
  300. result.Add("receivers", Receivers); //分账接收方列表
  301. result.Add("unfreeze_unsplit", true); //是否解冻剩余未分资金
  302. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  303. function.WriteLog(req, "服务商平台请求分账API");
  304. string resp = postJson("https://api.mch.weixin.qq.com/v3/profitsharing/orders", req, prikey, MchId, serialNo);
  305. function.WriteLog(resp + "\n\n", "服务商平台请求分账API");
  306. return resp;
  307. //{"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"}
  308. }
  309. #endregion
  310. #region 服务商平台添加分账接收方API
  311. public string AddReceive(string SubMchId, string TypeName, string Account, string Name, string Relation)
  312. {
  313. Dictionary<string, object> result = new Dictionary<string, object>();
  314. result.Add("sub_mchid", SubMchId); //子商户号
  315. result.Add("appid", AppId); //应用ID
  316. result.Add("type", TypeName); //分账接收方类型 MERCHANT_ID:商户ID PERSONAL_OPENID:个人openid(由父商户APPID转换得到) PERSONAL_SUB_OPENID:个人sub_openid(由子商户APPID转换得到)
  317. result.Add("account", Account); //分账接收方账号
  318. if(!string.IsNullOrEmpty(Name))
  319. {
  320. result.Add("name", RSAEncrypt(Name)); //分账个人接收方姓名
  321. }
  322. result.Add("relation_type", Relation); //与分账方的关系类型 STORE:门店 STAFF:员工 STORE_OWNER:店主 PARTNER:合作伙伴 HEADQUARTER:总部 BRAND:品牌方 DISTRIBUTOR:分销商 USER:用户 SUPPLIER: 供应商 CUSTOM:自定义
  323. string req = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  324. function.WriteLog(req, "服务商平台添加分账接收方API");
  325. string resp = postJson("https://api.mch.weixin.qq.com/v3/profitsharing/receivers/add", req, prikey, MchId, serialNo);
  326. function.WriteLog(resp + "\n\n", "服务商平台添加分账接收方API");
  327. return resp;
  328. //{"account":"1611167423","name":"x+8m5jM4x2jSZLDOpN46Js9JyeNgUXkFSmGjCBN45QcSYUNPN86TOheRF64WlwDeO45E/walWPeZSksNN/LfJiB2fZRVun1CJuJ7zxePma8L7iDbKS92i+d38rvOmNTjLhKX64O8oJR4HMtFw1HryxJlUFgM5/ickJ79WGrX3GaVArWisgEzwOyxGBfGSL3ofJhi5TdTnrxHMzqYWv43DRvI9Ja5eMgFbgrGcn+JiJVKQcYj1L8tZ6xQeQCXkY6ubyDiV9wQps2nQA1Oh+UdFcS13Ex4FUSYLCczGFAl4EV8TBJQleZeC1p4ZJquJjje0uMjI2xB6S41yUBoN86gkA==","relation_type":"PARTNER","sub_mchid":"1645266943","type":"MERCHANT_ID"}
  329. }
  330. #endregion
  331. #region 服务商平台查询分账结果API
  332. public string QueryProfitShare(string SubMchId, string TradeNo, string OrderNo)
  333. {
  334. string req = "";
  335. req += "sub_mchid=" + SubMchId + "&"; //子商户号
  336. req += "transaction_id=" + TradeNo + "&"; //微信订单号
  337. function.WriteLog(req, "服务商平台查询分账结果API");
  338. string resp = postJson("https://api.mch.weixin.qq.com/v3/profitsharing/orders/" + OrderNo + "?" + req, "", prikey, MchId, serialNo, "GET");
  339. function.WriteLog(resp + "\n\n", "服务商平台查询分账结果API");
  340. return resp;
  341. //{"order_id":"30000404702023060849818491190","out_order_no":"2023060816062365164446474","receivers":[{"account":"1611167423","amount":3,"create_time":"2023-06-08T17:55:45+08:00","description":"服务费","detail_id":"36000404702023060870422622364","finish_time":"2023-06-08T17:56:16+08:00","result":"SUCCESS","type":"MERCHANT_ID"},{"account":"1646405429","amount":151,"create_time":"2023-06-08T17:55:45+08:00","description":"解冻给分账方","detail_id":"36000404702023060870422622365","finish_time":"2023-06-08T17:56:16+08:00","result":"SUCCESS","type":"MERCHANT_ID"}],"state":"FINISHED","sub_mchid":"1646405429","transaction_id":"4200001821202306083551994076"}
  342. }
  343. #endregion
  344. #region 敏感信息加密
  345. string pubkey = "MIIEKDCCAxCgAwIBAgIUFOn9fwmBvqI/lBN2B1IctRxPdu8wDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsTFFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3QgQ0EwHhcNMjMwNjI2MDMwNTU2WhcNMjgwNjI0MDMwNTU2WjCBgTETMBEGA1UEAwwKMTYxMzExMjI4MTEbMBkGA1UECgwS5b6u5L+h5ZWG5oi357O757ufMS0wKwYDVQQLDCTlm5vlt53nnIHmtqbop4LnsbPnp5HmioDmnInpmZDlhazlj7gxCzAJBgNVBAYMAkNOMREwDwYDVQQHDAhTaGVuWmhl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UQmY679ILlT4fD7kKhUZ3PQVlmgITPJH9DWhyCM3HtRFpN2jTa4js4jrqSxlwQbcCffIRlMaqRhl+eEOYqSI/JheO+RhLerFVHeTFZAF7qnM4SHjvwAEswgoeQ6Xt8m//9bPeLCqjBcNU6wgHBDrbF/ddYba0QKBgH4lLjA5U0P4YBXuQpt0raazOy52+NLdJfMlkHV6ZC3IeOo+n9aDVjq9R5YaZKfexLcZEYvVI08cLcQJ5sK1nbh2/DmN0xf3cRMzU/TkXNmpSCNxy/0V9fPFKZVn9QHvdTS32Kvd9rLc6LXXjetuCDuVJ5DAPeRfbNHks9CmT973AoGBAK400faHTcodLHR/MXEmfI6BZlsTh2Cbm5q+k8Of095xKB/sfTWPprMQW+/U5OEQrKDbt+FI+psJFixmSNFuZdt4JU9P5/bp4SGIQpCfsp1p7GP/irc1yikrHXeGes9HPeUn7yGmvz4QC+sFO32haYr1SaAzZvMhf3RQVuAiFOnw"; //私钥
  347. public string RSAEncrypt(string text)
  348. {
  349. byte[] publicKey = Convert.FromBase64String(pubkey);
  350. // var rsa = RSA.Create();
  351. // rsa.ImportRSAPublicKey(publicKey, out _);
  352. // var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.OaepSHA1);
  353. // return Convert.ToBase64String(buff);
  354. using (var x509 = new X509Certificate2(publicKey))
  355. {
  356. using (var rsa = x509.GetRSAPublicKey())
  357. {
  358. var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.OaepSHA1);
  359. return Convert.ToBase64String(buff);
  360. }
  361. }
  362. }
  363. // public string RSADecrypt(string text)
  364. // {
  365. // // byte[] key = Encoding.UTF8.GetBytes(AppConfig.WeChatParam.AesGemKey);
  366. // // byte[] nonce = Encoding.UTF8.GetBytes("1234567890ab");
  367. // // byte[] ciphertext = Convert.FromBase64String(text);
  368. // // AesGcm aes = new AesGcm(key);
  369. // // byte[] plaintext = new byte[ciphertext.Length];
  370. // // aes.Decrypt(nonce, ciphertext, plaintext, null);
  371. // // return Encoding.UTF8.GetString(plaintext);
  372. // }
  373. public string AesGcmDecrypt(string associatedData, string nonce, string ciphertext)
  374. {
  375. // GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine());
  376. // AeadParameters aeadParameters = new AeadParameters(
  377. // new KeyParameter(Encoding.UTF8.GetBytes(AppConfig.WeChatParam.AesGemKey)),
  378. // 128,
  379. // Encoding.UTF8.GetBytes(nonce),
  380. // Encoding.UTF8.GetBytes(associatedData));
  381. // gcmBlockCipher.Init(false, aeadParameters);
  382. // byte[] data = Convert.FromBase64String(ciphertext);
  383. // byte[] plaintext = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
  384. // int length = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plaintext, 0);
  385. // gcmBlockCipher.DoFinal(plaintext, length);
  386. // return Encoding.UTF8.GetString(plaintext);
  387. byte[] key = Encoding.UTF8.GetBytes(AppConfig.WeChatParam.AesGemKey); // 256-bit key
  388. byte[] nonceByte = Encoding.UTF8.GetBytes(nonce); // 96-bit nonce
  389. byte[] cipherByte = Convert.FromBase64String(ciphertext);
  390. byte[] associatedByte = Encoding.UTF8.GetBytes(associatedData);
  391. GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine());
  392. AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, nonceByte, associatedByte);
  393. cipher.Init(false, parameters);
  394. byte[] plaintext = new byte[cipher.GetOutputSize(cipherByte.Length)];
  395. int len = cipher.ProcessBytes(cipherByte, 0, cipherByte.Length, plaintext, 0);
  396. cipher.DoFinal(plaintext, len);
  397. return Encoding.UTF8.GetString(plaintext);
  398. }
  399. public string postJson(string url, string postData, string privateKey, string merchantId, string serialNo, string method = "POST")
  400. {
  401. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  402. request.Method = method;
  403. request.ContentType = "application/json;charset=UTF-8";
  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, postData, privateKey, merchantId, serialNo);
  407. request.Headers.Add("Authorization", Authorization);
  408. request.Headers.Add("Wechatpay-Serial", platSerialNo);
  409. if (!string.IsNullOrEmpty(postData))
  410. {
  411. byte[] paramJsonBytes;
  412. paramJsonBytes = System.Text.Encoding.UTF8.GetBytes(postData);
  413. request.ContentLength = paramJsonBytes.Length;
  414. Stream writer;
  415. try
  416. {
  417. writer = request.GetRequestStream();
  418. }
  419. catch (Exception ex)
  420. {
  421. writer = null;
  422. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "http请求异常");
  423. }
  424. writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
  425. writer.Close();
  426. }
  427. HttpWebResponse response;
  428. try
  429. {
  430. response = (HttpWebResponse)request.GetResponse();
  431. }
  432. catch (WebException ex)
  433. {
  434. response = ex.Response as HttpWebResponse;
  435. }
  436. Stream resStream = response.GetResponseStream();
  437. StreamReader reader = new StreamReader(resStream);
  438. string text = reader.ReadToEnd();
  439. return text;
  440. //{\"code\":\"PARAM_ERROR\",\"message\":\"请确认待处理的消息是否为加密后的密文\"}
  441. //{\"applyment_id\":2000002247709762}
  442. }
  443. #endregion
  444. #region 图片上传
  445. public string GetMediaId(string imgPath)
  446. {
  447. if (string.IsNullOrEmpty(imgPath))
  448. {
  449. return "";
  450. }
  451. if (imgPath.Contains(","))
  452. {
  453. imgPath = imgPath.Split(',')[0];
  454. }
  455. string key = "wechatpic:" + function.MD5_16(imgPath);
  456. string media_id = RedisDbconn.Instance.Get<string>(key);
  457. if (!string.IsNullOrEmpty(media_id))
  458. {
  459. return media_id;
  460. }
  461. string filePath = function.getPath(imgPath);
  462. var filename = Path.GetFileName(filePath);
  463. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  464. Byte[] imgBytesIn = new Byte[fs.Length];
  465. fs.Read(imgBytesIn, 0, imgBytesIn.Length);
  466. fs.Close();
  467. byte[] hash = SHA256Managed.Create().ComputeHash(imgBytesIn);
  468. StringBuilder builder = new StringBuilder();
  469. for (int i = 0; i < hash.Length; i++)
  470. {
  471. builder.Append(hash[i].ToString("x2"));
  472. }
  473. var sha256 = builder.ToString();
  474. string metaStr = "{\"filename\":\""+ filename + "\",\"sha256\":\"" + sha256 + "\"}";
  475. media_id = UploadImgApi(metaStr, imgBytesIn, filename);
  476. RedisDbconn.Instance.Set(key, media_id);
  477. return media_id;
  478. }
  479. public string UploadImgApi(string metaStr, Byte[] imgBytesIn,string filename)
  480. {
  481. string url = "https://api.mch.weixin.qq.com/v3/merchant/media/upload";
  482. string merchantId = MchId; //商户号
  483. string privateKey = prikey;
  484. #region 定义请求体中的内容 并转成二进制
  485. string boundary = "lc199aecd61b4653ef";
  486. string Enter = "\r\n";
  487. string campaignIDStr1
  488. = "--" + boundary
  489. + Enter
  490. + "Content-Disposition: form-data; name=\"meta\";"
  491. + Enter
  492. + "Content-Type:application/json;"
  493. + Enter
  494. + Enter
  495. + metaStr
  496. + Enter
  497. + "--" + boundary
  498. + Enter
  499. + "Content-Disposition:form-data;name=\"file\";filename=\""+ filename + "\";"
  500. + Enter
  501. + "Content-Type:image/jpeg"
  502. + Enter
  503. + Enter;
  504. byte[] byteData2
  505. = imgBytesIn;
  506. string campaignIDStr3
  507. = Enter
  508. + "--" + boundary
  509. + Enter;
  510. var byteData1 = System.Text.Encoding.UTF8.GetBytes(campaignIDStr1);
  511. var byteData3 = System.Text.Encoding.UTF8.GetBytes(campaignIDStr3);
  512. #endregion
  513. string transactionsResponse = UploadImg_postJson(url, byteData1, byteData2, byteData3, metaStr, privateKey, merchantId, platSerialNo, boundary, "POST");
  514. var result=JsonMapper.ToObject(transactionsResponse);
  515. return result["media_id"].ToString();
  516. }
  517. 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")
  518. {
  519. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  520. request.Method = method;
  521. //request.ContentType = "application/json;charset=UTF-8";
  522. request.ContentType = "multipart/form-data;boundary=" + boundary;
  523. 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";
  524. request.Accept = "application/json";
  525. string Authorization = GetAuthorization(url, method, metaStr, privateKey, merchantId, serialNo);
  526. request.Headers.Add("Authorization", Authorization);
  527. Stream writer;
  528. try
  529. {
  530. writer = request.GetRequestStream();
  531. }
  532. catch (Exception)
  533. {
  534. writer = null;
  535. }
  536. writer.Write(b1, 0, b1.Length);
  537. writer.Write(b2, 0, b2.Length);
  538. writer.Write(b3, 0, b3.Length);
  539. writer.Close();
  540. HttpWebResponse response;
  541. try
  542. {
  543. response = (HttpWebResponse)request.GetResponse();
  544. }
  545. catch (WebException ex)
  546. {
  547. response = ex.Response as HttpWebResponse;
  548. }
  549. Stream resStream = response.GetResponseStream();
  550. StreamReader reader = new StreamReader(resStream);
  551. string text = reader.ReadToEnd();
  552. return text;
  553. }
  554. protected string GetAuthorization(string url, string method, string jsonParame, string privateKey, string merchantId, string serialNo)
  555. {
  556. var uri = new Uri(url);
  557. string urlPath = uri.PathAndQuery;
  558. string nonce = Guid.NewGuid().ToString();
  559. var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
  560. //数据签名 HTTP请求方法\n接口地址的url\n请求时间戳\n请求随机串\n请求报文主体\n
  561. method = string.IsNullOrEmpty(method) ? "" : method;
  562. string message = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n", method, urlPath, timestamp, nonce, jsonParame);
  563. string signTxt = Sign(message, privateKey);
  564. //Authorization和格式
  565. string authorzationTxt = string.Format("WECHATPAY2-SHA256-RSA2048 mchid=\"{0}\",nonce_str=\"{1}\",timestamp=\"{2}\",serial_no=\"{3}\",signature=\"{4}\"",
  566. merchantId,
  567. nonce,
  568. timestamp,
  569. serialNo,
  570. signTxt
  571. );
  572. return authorzationTxt;
  573. }
  574. protected string Sign(string message, string privateKey)
  575. {
  576. byte[] keyData = Convert.FromBase64String(privateKey);
  577. byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
  578. var rsa = RSA.Create();
  579. rsa.ImportPkcs8PrivateKey(keyData, out _);
  580. return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
  581. // using (CngKey cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob))
  582. // using (RSACng rsa = new RSACng(cngKey))
  583. // {
  584. // return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
  585. // }
  586. }
  587. #endregion
  588. #region 获取文件sha256
  589. public string GetSha256(FileStream stream)
  590. {
  591. using (SHA256 mySHA256 = SHA256.Create())
  592. {
  593. byte[] hashValue = mySHA256.ComputeHash(stream);
  594. return Encoding.UTF8.GetString(hashValue);
  595. }
  596. }
  597. #endregion
  598. #region 判断长期
  599. public string CheckForever(DateTime? time)
  600. {
  601. if (time == null)
  602. {
  603. return "";
  604. }
  605. if (time.Value.Year >= 2050)
  606. {
  607. return "长期";
  608. }
  609. return time.Value.ToString("yyyy-MM-dd");
  610. }
  611. #endregion
  612. }
  613. }