public TaskStatus Handle(IHttpProxy httpProxy) { using (Log log = new Log("CailutongGateway.Notify_RequestHandler")) { try { string json = httpProxy.ReadRequestBody(); log.Log(json); SortedDictionary <string, object> dict = Newtonsoft.Json.JsonConvert.DeserializeObject <SortedDictionary <string, object> >(json); string outTradeNo = (string)dict["outTradeNo"]; var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.CailutongBTC, outTradeNo)); if (Cailutong_Helper.Sign(dict, config.Secret) != (string)dict["sign"]) { throw new Exception("校验失败"); } var status = Convert.ToInt32(dict["status"]); if (status == 2) { PayFactory.OnPaySuccessed(outTradeNo, Convert.ToDouble(dict["payedAmount"]), null, json); } httpProxy.ResponseWrite("{\"status\":\"success\"}"); } catch (Exception ex) { log.Log(ex.ToString()); } } return(TaskStatus.Completed); }
/// <summary> /// 创建支付 /// </summary> /// <returns>返回二维码内容</returns> public override string StartPay(PayParameter parameter) { if (parameter.TradeID.IsNullOrEmpty()) { throw new Exception("交易编号为空"); } Config config = new Alipay.Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, parameter.TradeID)); IAlipayTradeService serviceClient = config.AppConfig.CreateClientInstance(); AlipayTradePrecreateContentBuilder builder = BuildPrecreateContent(config, parameter); string out_trade_no = builder.out_trade_no; //回掉通知页面 string notifyUrl = string.Format("http://{0}/{1}", HttpContext.Current.Request.Url.Authority, Alipay_ScanPay_HttpModule.NotifyPageName); AlipayF2FPrecreateResult precreateResult = serviceClient.tradePrecreate(builder, notifyUrl); PayFactory.OnLog(parameter.TradeID, precreateResult.response.Body); if (precreateResult.response.QrCode.IsNullOrEmpty()) { //如果没有生成二维码内容,认为失败 throw new Exception(precreateResult.response.SubMsg); } if (precreateResult.Status == ResultEnum.FAILED) { throw new Exception(precreateResult.response.SubMsg); } return(precreateResult.response.QrCode); }
/// <summary> /// 检查支付状态 /// </summary> public override void CheckPayState(PayParameter parameter) { try { WxPayConfig config = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, parameter.TradeID)); WxPayData queryOrderInput = new WxPayData(); queryOrderInput.SetValue("out_trade_no", parameter.TradeID); WxPayData result = WxPayApi.OrderQuery(queryOrderInput, config); string xml = result.ToXml(); PayFactory.OnLog(parameter.TradeID, xml); if (result.GetValue("return_code").ToString() == "SUCCESS" && result.GetValue("result_code").ToString() == "SUCCESS") { //支付成功 if (result.GetValue("trade_state").ToString() == "SUCCESS") { //触发回调函数 PayFactory.OnPaySuccessed(parameter.TradeID, xml); return; } else if (result.GetValue("trade_state").ToString() == "NOTPAY") { //这是一开始生成二维码后,会是这个状态 return; } } } catch { } }
public virtual RefoundResult Refound(RefoundParameter parameter) { WxPayConfig config = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinBarcode, parameter.TradeID)); WxPayData data = new WxPayData(); data.SetValue("out_trade_no", parameter.TradeID); data.SetValue("total_fee", (int)(parameter.TotalAmount * 100)); //订单总金额 data.SetValue("refund_fee", (int)(parameter.Amount * 100)); //退款金额 data.SetValue("out_refund_no", Guid.NewGuid().ToString()); //随机生成商户退款单号 data.SetValue("op_user_id", config.MCHID); //操作员,默认为商户号 WxPayData result = WxPayApi.Refund(data, config); //提交退款申请给API,接收返回数据 string err = result.GetValue("err_code_des") as string; RefoundResult finallyResult = new RefoundResult(); if (result.GetValue("return_code").ToString() == "SUCCESS" && result.GetValue("result_code").ToString() == "SUCCESS") { //退款成功 finallyResult.Result = RefoundResult.ResultEnum.SUCCESS; } else { finallyResult.Result = RefoundResult.ResultEnum.FAIL; } finallyResult.Error = err; finallyResult.ServerMessage = result.ToXml(); return(finallyResult); }
public override bool CheckPayState(PayParameter parameter) { var attrs = this.GetType().GetCustomAttributes(typeof(PayInterfaceAttribute), false); //获取当前接口类型 var myInterfaceType = ((PayInterfaceAttribute)attrs[0]).InterfaceType; var config = new Config(PayFactory.GetInterfaceXmlConfig(myInterfaceType, parameter.TradeID)); Dictionary <string, object> postDict = new Dictionary <string, object>(); postDict["merchantCode"] = config.merchantCode; postDict["operatorCode"] = config.operatorCode; postDict["businessCode"] = this.BusinessCode; var detail = new Dictionary <string, string> { { "merchantGenCode", parameter.TradeID }, { "operatorCode", config.operatorCode }, }; postDict["detail"] = new object[] { detail }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(postDict); string queryStr = $"request={WebUtility.UrlEncode(json)}"; var result = Helper.PostQueryString(QueryUrl, queryStr, parameter.RequestTimeout); var resultDict = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); if (resultDict["resultCode"].ToString() == "0000") { var resultDetail = (Newtonsoft.Json.Linq.JArray)resultDict["detail"]; if (resultDetail[0]["statusId"].ToString() == "14") { var charge = Convert.ToDouble(resultDetail[0]["charge"].ToString()) / 100.0; var amount = Convert.ToDouble(resultDetail[0]["charge"].ToString()) / 100.0; PayFactory.OnPaySuccessed(parameter.TradeID, amount - charge, null, result); return(true); } else if (resultDetail[0]["statusId"].ToString() == "3") { PayFactory.OnPayFailed(parameter.TradeID, "订单已打回", result); return(true); } else if (resultDetail[0]["statusId"].ToString() == "12") { PayFactory.OnPayFailed(parameter.TradeID, "通道提交失败", result); return(true); } else if (resultDetail[0]["statusId"].ToString() == "15") { PayFactory.OnPayFailed(parameter.TradeID, "处理失败", result); return(true); } } return(false); }
public override string BeginPay(PayParameter parameter) { var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayWeb, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["app_id"] = config.appid; postDict["method"] = Method; postDict["charset"] = "utf-8"; postDict["sign_type"] = "RSA"; postDict["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); postDict["version"] = "1.0"; if (string.IsNullOrEmpty(parameter.NotifyDomain) == false) { if (!string.IsNullOrEmpty(parameter.ReturnUrl)) { postDict["return_url"] = $"{parameter.NotifyDomain}/{AlipayReturn_RequestHandler.ReturnPageName}?returnUrl={System.Web.HttpUtility.UrlEncode(parameter.ReturnUrl)}"; } postDict["notify_url"] = $"{parameter.NotifyDomain}/{AlipayNotify_RequestHandler.NotifyPageName}"; } var bizParameters = new SortedDictionary <string, string> { { "out_trade_no", parameter.TradeID }, { "subject", parameter.TradeName }, { "body", parameter.Description }, { "total_amount", parameter.Amount.ToString("0.00") }, { "undiscountable_amount", "0" }, { "timeout_express", Math.Max(1, parameter.Timeout / 60) + "m" }, { "product_code", "FAST_INSTANT_TRADE_PAY" }, }; postDict["biz_content"] = Newtonsoft.Json.JsonConvert.SerializeObject(bizParameters); //获取签名的内容 var signContent = Helper.GetUrlString(postDict); var rsa = Way.Lib.RSA.CreateRsaFromPrivateKey(config.merchantPrivateKey, Way.Lib.RSAKeyType.PKCS1); rsa.KeySize = 1024; var signatureBytes = rsa.SignData(Encoding.UTF8.GetBytes(signContent), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); // 把密文加入提交的参数列表中 postDict["sign"] = Convert.ToBase64String(signatureBytes); //var result = Helper.PostQueryString(ServerUrl, Helper.BuildQuery(postDict), parameter.RequestTimeout ); var body = BuildHtmlFormRequest(postDict, "POST"); //先把jsonStr保存成一个临时文件 string tranid = Guid.NewGuid().ToString("N"); string tempFile = $"{Helper.GetSaveFilePath()}\\{tranid}.txt"; System.IO.File.WriteAllText(tempFile, body, Encoding.UTF8); return($"{parameter.NotifyDomain}/{AlipayPostPage_RequestHandler.PageName}?tranId={tranid}"); }
/// <summary> /// 根据TradeID检查支付状态 /// </summary> public virtual void CheckPayState(PayParameter parameter) { try { Config config = new Alipay.Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayBarcode, parameter.TradeID)); checkPayStateByConfig(parameter, config); } catch { } }
/// <summary> /// 检查订单状态 /// </summary> public virtual void CheckPayState(PayParameter parameter) { try { WxPayConfig config = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinBarcode, parameter.TradeID)); checkPayStateByConfig(parameter, config); } catch { } }
public override string BeginPay(PayParameter parameter) { var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinBarcode, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["appid"] = config.AppID; postDict["mch_id"] = config.MchID; postDict["nonce_str"] = Guid.NewGuid().ToString().Replace("-", ""); //随机字符串 postDict["body"] = parameter.Description; //商品描述 postDict["out_trade_no"] = parameter.TradeID; postDict["total_fee"] = ((int)(parameter.Amount * 100)).ToString(); //单位:分 postDict["spbill_create_ip"] = "8.8.8.8"; //终端ip postDict["auth_code"] = parameter.AuthCode; postDict["sign_type"] = "MD5"; postDict["sign"] = Helper.GetMd5Hash(postDict, config.Key); var xml = ToXml(postDict); var result = Helper.PostXml(ServerUrl, xml, parameter.RequestTimeout); PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result); XDocument xmldoc = XDocument.Parse(result); WeiXinScanQRCode.CheckSign(xmldoc, config); var return_code = xmldoc.Root.XPathSelectElement("return_code").Value; var return_msg = xmldoc.Root.XPathSelectElement("return_msg").Value; if (return_code == "FAIL") { throw new Exception(return_msg); } else if (return_code == "SUCCESS" && return_msg == "OK") { if (xmldoc.Root.XPathSelectElement("result_code").Value == "SUCCESS") { //确定付款成功 PayFactory.OnPaySuccessed(parameter.TradeID, null, null, result); } else if (xmldoc.Root.XPathSelectElement("err_code").Value != "USERPAYING" && xmldoc.Root.XPathSelectElement("result_code").Value == "FAIL" && xmldoc.Root.XPathSelectElement("err_code_des") != null) { throw new PayServerReportException(xmldoc.Root.XPathSelectElement("err_code_des").Value); } else { new Thread(() => { CheckPayStateInLoop(parameter); }).Start(); } } return(null); }
public virtual RefoundResult Refound(RefoundParameter parameter) { if (parameter.TradeID.IsNullOrEmpty()) { throw new Exception("TradeID is null"); } Config config = new Alipay.Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayBarcode, parameter.TradeID)); var serviceClient = config.AppConfig.CreateClientInstance(); AlipayTradeRefundContentBuilder builder = new AlipayTradeRefundContentBuilder(); //支付宝交易号与商户网站订单号不能同时为空 builder.out_trade_no = parameter.TradeID; //退款金额 builder.refund_amount = parameter.Amount.ToString(); builder.refund_reason = parameter.Reason; AlipayF2FRefundResult refundResult = serviceClient.tradeRefund(builder); RefoundResult finallyResult = new RefoundResult(); //请在这里加上商户的业务逻辑程序代码 //——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— switch (refundResult.Status) { case ResultEnum.SUCCESS: finallyResult.Result = RefoundResult.ResultEnum.SUCCESS; finallyResult.ServerMessage = refundResult.response.Body; break; case ResultEnum.FAILED: finallyResult.Result = RefoundResult.ResultEnum.FAIL; finallyResult.ServerMessage = refundResult.response.Body; finallyResult.Error = refundResult.response.SubMsg; break; case ResultEnum.UNKNOWN: finallyResult.Result = RefoundResult.ResultEnum.FAIL; if (refundResult.response == null) { finallyResult.Error = "配置或网络异常,请检查"; } else { finallyResult.Error = "系统异常,请走人工退款流程"; } break; } return(finallyResult); }
public override RefundResult Refund(RefundParameter parameter) { var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayBarcode, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["app_id"] = config.appid; postDict["method"] = "alipay.trade.refund"; postDict["charset"] = "utf-8"; postDict["sign_type"] = "RSA"; postDict["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); postDict["version"] = "1.0"; var bizParameters = new SortedDictionary <string, string> { { "out_trade_no", parameter.TradeID }, { "refund_amount", parameter.Amount.ToString("0.00") }, }; postDict["biz_content"] = Newtonsoft.Json.JsonConvert.SerializeObject(bizParameters); //获取签名的内容 var signContent = Helper.GetUrlString(postDict); var rsa = Way.Lib.RSA.CreateRsaFromPrivateKey(config.merchantPrivateKey, Way.Lib.RSAKeyType.PKCS1); rsa.KeySize = 1024; var signatureBytes = rsa.SignData(Encoding.UTF8.GetBytes(signContent), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); // 把密文加入提交的参数列表中 postDict["sign"] = Convert.ToBase64String(signatureBytes); var result = Helper.PostQueryString(ServerUrl, Helper.BuildQuery(postDict), 15); // 把json结果转为对象 var refundResult = Newtonsoft.Json.JsonConvert.DeserializeObject <AlipayTradeRefundResult>(result); CheckSign(result, "alipay_trade_refund_response", refundResult.sign, config); if (refundResult.alipay_trade_refund_response.code == "10000") { return(new RefundResult() { Result = RefundResult.ResultEnum.SUCCESS, ServerMessage = result, }); } return(new RefundResult() { Result = RefundResult.ResultEnum.FAIL, ServerMessage = result, }); }
private void handleNotify() { using (CLog log = new CLog("weixin scan handleNotify ")) { WxPayData notifyData = GetNotifyData(); string json = notifyData.ToJson(); log.Log("xml:{0}", json); string out_trade_no = notifyData.GetValue("out_trade_no").ToString(); PayFactory.OnLog(out_trade_no, json); WxPayConfig config = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, out_trade_no)); try { notifyData.CheckSign(config); } catch (WxPayException ex) { log.Log("签名错误"); //若签名错误,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", ex.Message); Response.Write(res.ToXml()); Response.End(); } string result_code = notifyData.GetValue("result_code").ToString(); string return_code = notifyData.GetValue("return_code").ToString(); //out_trade_no result_code return_code if (result_code == "SUCCESS" && return_code == "SUCCESS") { PayFactory.OnPaySuccessed(out_trade_no, json); WxPayData data = new WxPayData(); data.SetValue("return_code", "SUCCESS"); data.SetValue("return_msg", "OK"); data.SetValue("appid", config.APPID); data.SetValue("mch_id", config.MCHID); data.SetValue("result_code", "SUCCESS"); data.SetValue("err_code_des", "OK"); data.SetValue("sign", data.MakeSign(config)); //log.Log("write to weixin:{0}", data.ToJson()); Response.Write(data.ToXml()); } } }
public override bool CheckPayState(PayParameter parameter) { var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayBarcode, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["app_id"] = config.appid; postDict["method"] = "alipay.trade.query"; postDict["charset"] = "utf-8"; postDict["sign_type"] = "RSA"; postDict["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); postDict["version"] = "1.0"; var bizParameters = new SortedDictionary <string, string> { { "out_trade_no", parameter.TradeID }, }; postDict["biz_content"] = Newtonsoft.Json.JsonConvert.SerializeObject(bizParameters); //获取签名的内容 var signContent = Helper.GetUrlString(postDict); var rsa = Way.Lib.RSA.CreateRsaFromPrivateKey(config.merchantPrivateKey, Way.Lib.RSAKeyType.PKCS1); rsa.KeySize = 1024; var signatureBytes = rsa.SignData(Encoding.UTF8.GetBytes(signContent), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); // 把密文加入提交的参数列表中 postDict["sign"] = Convert.ToBase64String(signatureBytes); var result = Helper.PostQueryString(ServerUrl, Helper.BuildQuery(postDict), parameter.RequestTimeout); PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result); // 把json结果转为对象 var payResult = Newtonsoft.Json.JsonConvert.DeserializeObject <AlipayTradeQueryResult>(result); CheckSign(result, "alipay_trade_query_response", payResult.sign, config); if (payResult.alipay_trade_query_response.code == "10000" && (payResult.alipay_trade_query_response.trade_status == "TRADE_SUCCESS" || payResult.alipay_trade_query_response.trade_status == "TRADE_FINISHED")) { //明确交易成功了 PayFactory.OnPaySuccessed(parameter.TradeID, payResult.alipay_trade_query_response.receipt_amount, null, result); return(true); } return(false); }
/// <summary> /// 注册店铺 /// </summary> /// <param name="ourshopid">我们自己的门店编号</param> public static string RegisterShop(string ourshopid) { var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.Bboqi, null)); SortedDictionary <string, string> dict = new SortedDictionary <string, string>(); dict["appid"] = config.AppId; dict["nonce_str"] = Guid.NewGuid().ToString("N"); dict["timestamp"] = Helper.ConvertDateTimeInt(DateTime.Now).ToString(); dict["shop_code"] = ourshopid; dict["sign"] = Bboqi_Helper.Sign(config, dict); dict = PostJson(config, Url, dict, 8); var bs = Convert.FromBase64String(dict["shopconfig"]); return(System.Text.Encoding.UTF8.GetString(bs)); }
public override bool CheckPayState(PayParameter parameter) { var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["appid"] = config.AppID; postDict["mch_id"] = config.MchID; postDict["out_trade_no"] = parameter.TradeID; postDict["nonce_str"] = Guid.NewGuid().ToString().Replace("-", "");//随机字符串 postDict["sign_type"] = "MD5"; postDict["sign"] = Helper.GetMd5Hash(postDict, config.Key); var xml = ToXml(postDict); var result = Helper.PostXml(QueryUrl, xml, parameter.RequestTimeout); XDocument xmldoc = XDocument.Parse(result); CheckSign(xmldoc, config); var return_code = xmldoc.Root.XPathSelectElement("return_code").Value; var return_msg = xmldoc.Root.XPathSelectElement("return_msg").Value; if (return_code == "SUCCESS" && return_msg == "OK") { if (xmldoc.Root.XPathSelectElement("err_code_des") != null) { throw new PayServerReportException(xmldoc.Root.XPathSelectElement("err_code_des").Value); } var trade_state = xmldoc.Root.XPathSelectElement("trade_state").Value; if (trade_state == "SUCCESS") { PayFactory.OnPaySuccessed(parameter.TradeID, null, null, result); return(true); } else { if (trade_state == "PAYERROR" || trade_state == "REVOKED") { var trade_state_desc = xmldoc.Root.XPathSelectElement("trade_state_desc").Value; PayFactory.OnPayFailed(parameter.TradeID, trade_state_desc, result); return(true); } } } return(false); }
/// <summary> /// 检查订单状态 /// </summary> public override void CheckPayState(PayParameter parameter) { try { Config config = new Alipay.Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, parameter.TradeID)); IAlipayTradeService serviceClient = config.AppConfig.CreateClientInstance(); var result = serviceClient.tradeQuery(parameter.TradeID); PayFactory.OnLog(parameter.TradeID, result.response.Body); //客户没有扫码之前,会返回交易不存在 if (result.Status == ResultEnum.SUCCESS) { PayFactory.OnPaySuccessed(parameter.TradeID, result.response.Body); } } catch { } }
public string BeginPay(PayParameter parameter) { if (string.IsNullOrEmpty(parameter.Description)) { throw new Exception("PayParameter.Description can not be empty"); } var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinTransfers, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["mch_appid"] = config.AppID; postDict["mchid"] = config.MchID; postDict["partner_trade_no"] = parameter.TradeID; postDict["nonce_str"] = Guid.NewGuid().ToString().Replace("-", "");//随机字符串 postDict["openid"] = parameter.AuthCode; postDict["check_name"] = "NO_CHECK"; postDict["amount"] = ((int)(parameter.Amount * 100)).ToString();//单位:分 postDict["desc"] = parameter.Description; postDict["spbill_create_ip"] = "8.8.8.8"; postDict["sign"] = Helper.GetMd5Hash(postDict, config.Key); var xml = WeiXinScanQRCode.ToXml(postDict); var result = Helper.PostXml(ServerUrl, xml, parameter.RequestTimeout, config.SSLCERT_PATH, config.SSLCERT_PASSWORD); PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result); XDocument xmldoc = XDocument.Parse(result); //这里不用验证sign if (xmldoc.Root.XPathSelectElement("return_msg").Value != "OK" && xmldoc.Root.XPathSelectElement("err_code_des") != null) { throw new PayServerReportException(xmldoc.Root.XPathSelectElement("err_code_des").Value); } var return_code = xmldoc.Root.XPathSelectElement("return_code").Value; if (return_code == "SUCCESS" && xmldoc.Root.XPathSelectElement("result_code").Value == "SUCCESS") { PayFactory.OnPaySuccessed(parameter.TradeID, null, null, result); } return(null); }
public override RefundResult Refund(RefundParameter parameter) { var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["appid"] = config.AppID; postDict["mch_id"] = config.MchID; postDict["nonce_str"] = Guid.NewGuid().ToString().Replace("-", ""); //随机字符串 postDict["out_trade_no"] = parameter.TradeID; postDict["out_refund_no"] = Guid.NewGuid().ToString("N"); //商户系统内部的退款单号,商户系统内部唯一,只能是数字、大小写字母_-|*@ ,同一退款单号多次请求只退一笔。 postDict["total_fee"] = ((int)(parameter.TotalAmount * 100)).ToString(); //单位:分 postDict["refund_fee"] = ((int)(parameter.Amount * 100)).ToString(); //单位:分 postDict["sign_type"] = "MD5"; postDict["sign"] = Helper.GetMd5Hash(postDict, config.Key); var xml = ToXml(postDict); var result = Helper.PostXml(RefundUrl, xml, 15, config.SSLCERT_PATH, config.SSLCERT_PASSWORD); XDocument xmldoc = XDocument.Parse(result); CheckSign(xmldoc, config); var return_code = xmldoc.Root.XPathSelectElement("return_code").Value; var return_msg = xmldoc.Root.XPathSelectElement("return_msg").Value; if (return_code == "SUCCESS" && return_msg == "OK") { return(new RefundResult() { Result = RefundResult.ResultEnum.SUCCESS, ServerMessage = result, }); } return(new RefundResult() { Result = RefundResult.ResultEnum.FAIL, ServerMessage = result, }); }
public string StartPay(PayParameter parameter) { if (parameter.TradeID.IsNullOrEmpty()) { throw new Exception("交易编号为空"); } Config config = new Alipay.Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayWebPay, parameter.TradeID)); //回掉通知页面 string notifyUrl = string.Format("http://{0}/{1}", HttpContext.Current.Request.Url.Authority, Alipay_WebPay_HttpModule.NotifyPageName); string returnUrl = string.Format("http://{0}/{1}", HttpContext.Current.Request.Url.Authority, Alipay_WebPay_HttpModule.ReturnPageName); //把请求参数打包成数组 SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>(); sParaTemp.Add("service", config.WebConfig.service); sParaTemp.Add("partner", config.WebConfig.pid); sParaTemp.Add("seller_id", config.WebConfig.seller_id); sParaTemp.Add("_input_charset", config.WebConfig.input_charset.ToLower()); sParaTemp.Add("payment_type", config.WebConfig.payment_type); sParaTemp.Add("notify_url", notifyUrl); sParaTemp.Add("return_url", returnUrl); sParaTemp.Add("anti_phishing_key", config.WebConfig.anti_phishing_key); sParaTemp.Add("exter_invoke_ip", config.WebConfig.exter_invoke_ip); sParaTemp.Add("out_trade_no", parameter.TradeID); sParaTemp.Add("subject", parameter.TradeName); //订单名称 sParaTemp.Add("total_fee", parameter.Amount.ToString()); sParaTemp.Add("body", parameter.Description); //商品描述 //其他业务参数根据在线开发文档,添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1 //如sParaTemp.Add("参数名","参数值"); //建立请求 var submitBuilder = new Com.Alipay.Submit(config); string sHtmlText = submitBuilder.BuildRequest(sParaTemp, "get", "确认"); Alipay_WebPay_HttpModule.ReturnUrlConfigs.Add(parameter.TradeID, parameter.ReturnUrl); return(sHtmlText); }
public override bool CheckPayState(PayParameter parameter) { var attrs = this.GetType().GetCustomAttributes(typeof(PayInterfaceAttribute), false); //获取当前接口类型 var myInterfaceType = ((PayInterfaceAttribute)attrs[0]).InterfaceType; var config = new Config(PayFactory.GetInterfaceXmlConfig(myInterfaceType, parameter.TradeID)); SortedDictionary <string, string> dict = new SortedDictionary <string, string>(); dict["out_tradeno"] = parameter.TradeID; var result = Bboqi_Helper.PostJson(config, QueryUrl, dict, parameter.RequestTimeout); if (result["pay_status"] == "2") { PayFactory.OnPayFailed(parameter.TradeID, "退款中", Newtonsoft.Json.JsonConvert.SerializeObject(result)); return(true); } else if (result["pay_status"] == "3") { PayFactory.OnPayFailed(parameter.TradeID, "已退款", Newtonsoft.Json.JsonConvert.SerializeObject(result)); return(true); } else if (result["pay_status"] == "4") { PayFactory.OnPayFailed(parameter.TradeID, "退款失败", Newtonsoft.Json.JsonConvert.SerializeObject(result)); return(true); } else if (result["pay_status"] == "5") { PayFactory.OnPayFailed(parameter.TradeID, "已撤销", Newtonsoft.Json.JsonConvert.SerializeObject(result)); return(true); } else if (result["pay_status"] == "1") { PayFactory.OnPaySuccessed(parameter.TradeID, Convert.ToDouble(result["total_fee"]), null, Newtonsoft.Json.JsonConvert.SerializeObject(result)); return(true); } return(false); }
public override string BeginPay(PayParameter parameter) { var attrs = this.GetType().GetCustomAttributes(typeof(PayInterfaceAttribute), false); //获取当前接口类型 var myInterfaceType = ((PayInterfaceAttribute)attrs[0]).InterfaceType; var config = new Config(PayFactory.GetInterfaceXmlConfig(myInterfaceType, parameter.TradeID)); SortedDictionary <string, string> dict = new SortedDictionary <string, string>(); dict["cashdesk_id"] = config.CashId ?? ""; dict["cashdesk_name"] = config.CashDesc ?? ""; dict["openid"] = parameter.AuthCode; dict["orig_fee"] = parameter.Amount.ToString(); dict["favo_fee"] = "0"; dict["total_fee"] = parameter.Amount.ToString(); dict["out_trade_no"] = parameter.TradeID; var resultJson = Bboqi_Helper.PostJson(config, Url, dict, parameter.RequestTimeout); var returnDict = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, object> >(resultJson["jsapipay"].Replace("\"packages\"", "\"package\"")); returnDict["ReturnUrl"] = parameter.ReturnUrl; returnDict["TradeID"] = parameter.TradeID; var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(returnDict); //先把jsonStr保存成一个临时文件 string tranid = Guid.NewGuid().ToString("N"); string tempFile = $"{Helper.GetSaveFilePath()}\\{tranid}.txt"; System.IO.File.WriteAllText(tempFile, jsonStr, Encoding.UTF8); new Thread(() => { CheckPayStateInLoop(parameter); }).Start(); return($"{parameter.NotifyDomain}/{Weixin.WeiXinPayRedirect_RequestHandler.NotifyPageName}?tranId={tranid}"); }
public bool CheckPayState(PayParameter parameter) { var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["appid"] = config.AppID; postDict["mch_id"] = config.MchID; postDict["partner_trade_no"] = parameter.TradeID; postDict["nonce_str"] = Guid.NewGuid().ToString().Replace("-", "");//随机字符串 postDict["sign"] = Helper.GetMd5Hash(postDict, config.Key); var xml = WeiXinScanQRCode.ToXml(postDict); var result = Helper.PostXml(QueryUrl, xml, parameter.RequestTimeout, config.SSLCERT_PATH, config.SSLCERT_PASSWORD); XDocument xmldoc = XDocument.Parse(result); //这里不用验证sign var return_code = xmldoc.Root.XPathSelectElement("return_code").Value; if (return_code == "SUCCESS") { if (xmldoc.Root.XPathSelectElement("err_code_des") != null) { throw new PayServerReportException(xmldoc.Root.XPathSelectElement("err_code_des").Value); } var result_code = xmldoc.Root.XPathSelectElement("result_code").Value; if (result_code == "SUCCESS") { PayFactory.OnPaySuccessed(parameter.TradeID, null, null, result); return(true); } } return(false); }
/// <summary> /// 创建支付 /// </summary> /// <param name="parameter"></param> /// <returns>返回二维码内容</returns> public override string StartPay(PayParameter parameter) { if (parameter.TradeID.IsNullOrEmpty()) { throw new Exception("交易编号为空"); } WxPayConfig config = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, parameter.TradeID)); //回掉通知页面 string notifyUrl = string.Format("http://{0}/{1}", HttpContext.Current.Request.Url.Authority, WeiXin_ScanPay_HttpModule.NotifyPageName); WxPayData data = new WxPayData(); data.SetValue("body", parameter.TradeName == null ? parameter.Description : parameter.TradeName); //商品描述 data.SetValue("attach", ""); //附加数据 data.SetValue("out_trade_no", parameter.TradeID); //随机字符串 data.SetValue("total_fee", Convert.ToInt32(parameter.Amount * 100).ToString()); //总金额 data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); //交易起始时间 data.SetValue("notify_url", notifyUrl); //不用回调的话可以注释这句 if (parameter.ExpireTime != DateTime.MinValue) { data.SetValue("time_expire", parameter.ExpireTime.ToString("yyyyMMddHHmmss"));//交易结束时间 } else { //默认十分钟 data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间 } data.SetValue("goods_tag", ""); //商品标记 data.SetValue("trade_type", "NATIVE"); //交易类型 data.SetValue("product_id", "123456"); //商品ID WxPayData result = WxPayApi.UnifiedOrder(data, config, 30); //调用统一下单接口 string qrcode = result.GetValue("code_url").ToString(); //获得统一下单接口返回的二维码内容 return(qrcode); }
public virtual string StartPay(PayParameter parameter) { try { WxPayConfig config = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinBarcode, parameter.TradeID)); WxPayData data = new WxPayData(); data.SetValue("auth_code", parameter.AuthCode); //授权码 data.SetValue("body", parameter.TradeName == null ? parameter.Description : parameter.TradeName); //商品描述 data.SetValue("total_fee", Convert.ToInt32(parameter.Amount * 100)); //总金额,以分为单位 data.SetValue("out_trade_no", parameter.TradeID); //产生随机的商户订单号 WxPayData result = WxPayApi.Micropay(data, config, 20); //提交被扫支付,接收返回结果 string xml = result.ToXml(); PayFactory.OnLog(parameter.TradeID, xml); string returnMsg = result.IsSet("return_msg") ? result.GetValue("return_msg").ToSafeString() : result.GetValue("err_code_des").ToSafeString(); //如果提交被扫支付接口调用失败,则抛异常 if (!result.IsSet("return_code") || result.GetValue("return_code").ToString() == "FAIL") { //触发回调函数 PayFactory.OnPayFailed(parameter.TradeID, returnMsg, xml); return(null); } //签名验证 result.CheckSign(config); //刷卡支付直接成功 if (result.GetValue("return_code").ToString() == "SUCCESS" && result.GetValue("result_code").ToString() == "SUCCESS") { //触发回调函数 PayFactory.OnPaySuccessed(parameter.TradeID, result.ToXml()); return(null); } //1)业务结果明确失败 if (result.GetValue("err_code").ToString() != "USERPAYING" && result.GetValue("err_code").ToString() != "SYSTEMERROR") { //触发回调函数 PayFactory.OnPayFailed(parameter.TradeID, result.GetValue("err_code_des").ToSafeString(), xml); return(null); } //到这里,不能确定支付结果,循环30秒确定 int checkTimes = parameter.Timeout / 2; Thread.Sleep(1000); for (int i = 0; i < checkTimes; i++) { if (checkPayStateByConfig(parameter, config)) { break; } if (i + 1 == checkTimes) { break; } Thread.Sleep(2000); } } catch (Exception ex) { throw ex; } return(null); }
public override string BeginPay(PayParameter parameter) { var attrs = this.GetType().GetCustomAttributes(typeof(PayInterfaceAttribute), false); //获取当前接口类型 var myInterfaceType = ((PayInterfaceAttribute)attrs[0]).InterfaceType; var config = new Config(PayFactory.GetInterfaceXmlConfig(myInterfaceType, parameter.TradeID)); SortedDictionary <string, string> dict = new SortedDictionary <string, string>(); dict["cashdesk_id"] = config.CashId ?? ""; dict["cashdesk_name"] = config.CashDesc ?? ""; dict["orig_fee"] = parameter.Amount.ToString(); dict["favo_fee"] = "0"; dict["total_fee"] = parameter.Amount.ToString(); dict["out_trade_no"] = parameter.TradeID; var resultJson = Bboqi_Helper.PostJson(config, OrderUrl, dict, parameter.RequestTimeout); string trade_no = resultJson["trade_no"]; dict = new SortedDictionary <string, string>(); dict["trade_no"] = trade_no; dict["body"] = parameter.Description; dict["auth_code"] = parameter.AuthCode; dict["channel"] = "wx"; var strResult = Bboqi_Helper.PostJsonReturnString(config, PayUrl, dict, parameter.RequestTimeout); resultJson = (SortedDictionary <string, string>)Newtonsoft.Json.JsonConvert.DeserializeObject(strResult, typeof(SortedDictionary <string, string>)); if (resultJson["result_code"] == "FAIL" && (resultJson.ContainsKey("trade_status") == false || resultJson["trade_status"] != "2")) { throw new Exception(resultJson["return_msgs"]); } string serverSign = resultJson["sign"]; if (Bboqi_Helper.Sign(config, resultJson) != serverSign) { throw new Exception("服务器返回信息签名检验失败"); } if (resultJson["result_code"] == "SUCCESS") { if (resultJson["trade_status"] == "1") { PayFactory.OnPaySuccessed(parameter.TradeID, parameter.Amount, null, strResult); return(null); } else if (resultJson["trade_status"] == "0") { PayFactory.OnPayFailed(parameter.TradeID, resultJson["return_msgs"], strResult); return(null); } } if (resultJson.ContainsKey("trade_status") && resultJson["trade_status"] == "2") { new Thread(() => { CheckPayStateInLoop(parameter); }).Start(); } return(null); }
private void handleNotify() { using (CLog log = new CLog("alipay scan handleNotify ")) { log.Log(Request.Form.ToJson()); SortedDictionary <string, string> sPara = GetRequestPost(); if (sPara.Count > 0)//判断是否有带返回参数 { //商户订单号 string out_trade_no = Request.Form["out_trade_no"]; var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, out_trade_no)); Notify aliNotify = new Notify(config.AppConfig.charset, config.AppConfig.sign_type, config.AppConfig.pid, config.AppConfig.mapiUrl, config.AppConfig.alipay_public_key); ////对异步通知进行延签 bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]); log.Log("verifyResult:{0}", verifyResult); if (verifyResult && CheckParams()) //验签成功 && 关键业务参数校验成功 { ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //请在这里加上商户的业务逻辑程序代码 //——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表 //支付宝交易号 string trade_no = Request.Form["trade_no"]; //交易状态 //在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,才是买家付款成功。 string trade_status = Request.Form["trade_status"]; log.Log(trade_status); PayFactory.OnLog(out_trade_no, Request.Form.ToJson()); if (trade_status == "TRADE_SUCCESS") { PayFactory.OnPaySuccessed(out_trade_no, Request.Form.ToJson()); } //判断是否在商户网站中已经做过了这次通知返回的处理 //如果没有做过处理,那么执行商户的业务程序 //如果有做过处理,那么不执行商户的业务程序 Response.Write("success"); //请不要修改或删除 //——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— ///////////////////////////////////////////////////////////////////////////////////////////////////////////// } else//验证失败 { log.Log("fail"); Response.Write("fail"); } } else { log.Log("无通知参数"); Response.Write("无通知参数"); } } }
public override string BeginPay(PayParameter parameter) { var attrs = this.GetType().GetCustomAttributes(typeof(PayInterfaceAttribute), false); //获取当前接口类型 var myInterfaceType = ((PayInterfaceAttribute)attrs[0]).InterfaceType; var config = new Config(PayFactory.GetInterfaceXmlConfig(myInterfaceType, parameter.TradeID)); Dictionary <string, object> postDict = new Dictionary <string, object>(); postDict["merchantCode"] = config.merchantCode; postDict["operatorCode"] = config.operatorCode; postDict["businessCode"] = this.BusinessCode; var detail = new SortedDictionary <string, object> { { "amount", ((int)(parameter.Amount * 100)).ToString() }, { "businessCode", this.BusinessCode }, { "merchantGenCode", parameter.TradeID }, { "operatorCode", config.operatorCode }, { "purpose", parameter.Description }, }; if (!string.IsNullOrEmpty(parameter.AuthCode)) { detail["authCode"] = parameter.AuthCode; } if (parameter.GoodsDetails.Count > 0) { var goodsDetails = new List <object>(); foreach (var gooditem in parameter.GoodsDetails) { goodsDetails.Add(new { productCode = gooditem.GoodsId, productName = gooditem.GoodsName, productNumber = gooditem.Quantity.ToString(), productPrice = ((int)(gooditem.Price * 100)) }); } detail["requestProductList"] = goodsDetails; } if (SupportNotify) { if (string.IsNullOrEmpty(parameter.NotifyDomain) == false) { detail["callBackUrl"] = $"{parameter.NotifyDomain}/{Paysoon_RequestHandler.NotifyPageName}"; } } var signContent = Newtonsoft.Json.JsonConvert.SerializeObject(new object[] { detail }); var rsa = Way.Lib.RSA.CreateRsaFromPublicKey(config.platformPublicKey); rsa.KeySize = 1024; // 把密文加入提交的参数列表中 postDict["detail"] = Way.Lib.RSA.EncryptToBase64(rsa, Encoding.UTF8.GetBytes(signContent), RSAEncryptionPadding.Pkcs1); string json = Newtonsoft.Json.JsonConvert.SerializeObject(postDict); string queryStr = $"request={WebUtility.UrlEncode(json)}"; var result = Helper.PostQueryString(ServerUrl, queryStr, parameter.RequestTimeout); PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result); var resultDict = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); return(OnBeginPayPostGetResult(result, config, resultDict, parameter)); }
public override string BeginPay(PayParameter parameter) { var enableNotify = false; var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, parameter.TradeID)); SortedDictionary <string, string> postDict = new SortedDictionary <string, string>(); postDict["app_id"] = config.appid; postDict["method"] = "alipay.trade.precreate"; postDict["charset"] = "utf-8"; postDict["sign_type"] = "RSA"; postDict["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); postDict["version"] = "1.0"; if (string.IsNullOrEmpty(parameter.NotifyDomain) == false) { enableNotify = true; postDict["notify_url"] = $"{parameter.NotifyDomain}/{AlipayNotify_RequestHandler.NotifyPageName}"; } var bizParameters = new SortedDictionary <string, object> { { "out_trade_no", parameter.TradeID }, { "subject", parameter.TradeName }, { "body", parameter.Description }, { "total_amount", parameter.Amount.ToString("0.00") }, { "undiscountable_amount", "0" }, { "timeout_express", Math.Max(1, parameter.Timeout / 60) + "m" }, //{"seller_id", config.pid} }; if (parameter.GoodsDetails.Count > 0) { var goodsDetails = new List <object>(); foreach (var gooditem in parameter.GoodsDetails) { goodsDetails.Add(new { goods_id = gooditem.GoodsId, goods_name = gooditem.GoodsName, quantity = gooditem.Quantity, price = gooditem.Price }); } bizParameters["goods_detail"] = goodsDetails; } if (!string.IsNullOrEmpty(parameter.StoreId)) { bizParameters["store_id"] = parameter.StoreId; } postDict["biz_content"] = Newtonsoft.Json.JsonConvert.SerializeObject(bizParameters); //获取签名的内容 var signContent = Helper.GetUrlString(postDict); var rsa = Way.Lib.RSA.CreateRsaFromPrivateKey(config.merchantPrivateKey, Way.Lib.RSAKeyType.PKCS1); rsa.KeySize = 1024; var signatureBytes = rsa.SignData(Encoding.UTF8.GetBytes(signContent), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); // 把密文加入提交的参数列表中 postDict["sign"] = Convert.ToBase64String(signatureBytes); var result = Helper.PostQueryString(ServerUrl, Helper.BuildQuery(postDict), parameter.RequestTimeout); PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result); // 把json结果转为对象 var payResult = Newtonsoft.Json.JsonConvert.DeserializeObject <AlipayTradePrecreateResult>(result); AlipayBarcode.CheckSign(result, "alipay_trade_precreate_response", payResult.sign, config); if (payResult.alipay_trade_precreate_response.code == "10000") { if (enableNotify == false) { new Thread(() => { CheckPayStateInLoop(parameter); }).Start(); } return(payResult.alipay_trade_precreate_response.qr_code); } else { throw new Exception(payResult.alipay_trade_precreate_response.sub_msg); } }
private void handleNotify() { using (CLog log = new CLog("alipay handleNotify ")) { log.Log(Request.Form.ToJson()); SortedDictionary <string, string> sPara = GetRequestPost(); if (sPara.Count > 0)//判断是否有带返回参数 { string out_trade_no = Request.Form["out_trade_no"]; var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayWebPay, out_trade_no)); Com.Alipay.Notify aliNotify = new Com.Alipay.Notify(config); bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]); log.Log("verifyResult:{0}", verifyResult); if (verifyResult)//验证成功 { ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //请在这里加上商户的业务逻辑程序代码 //——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表 //商户订单号 //支付宝交易号 string trade_no = Request.Form["trade_no"]; //交易状态 string trade_status = Request.Form["trade_status"]; log.Log(Request.Form["trade_status"]); PayFactory.OnLog(out_trade_no, Request.Form.ToJson()); if (Request.Form["trade_status"] == "TRADE_FINISHED") { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的 //如果有做过处理,不执行商户的业务程序 //注意: //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 } else if (Request.Form["trade_status"] == "TRADE_SUCCESS") { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的 //如果有做过处理,不执行商户的业务程序 //注意: //付款完成后,支付宝系统发送该交易状态通知 log.Log("OnPaySuccessed"); PayFactory.OnPaySuccessed(out_trade_no, Request.Form.ToJson()); } else { } //——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— Response.Write("success"); //请不要修改或删除 ///////////////////////////////////////////////////////////////////////////////////////////////////////////// } else//验证失败 { log.Log("fail"); Response.Write("fail"); } } else { log.Log("无通知参数"); Response.Write("无通知参数"); } } }
public TaskStatus Handle(IHttpProxy httpProxy) { using (CLog log = new CLog("Alipay Notify", false)) { var data = GetRequestData(httpProxy.Form); var dataJson = Newtonsoft.Json.JsonConvert.SerializeObject(data); log.Log(dataJson); if (data.Count > 0) { string out_trade_no = data["out_trade_no"]; string sign = httpProxy.Form["sign"]; //string sign_type = form["sign_type"]; PayFactory.OnLog(out_trade_no, LogEventType.ReceiveNotify, dataJson); var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, out_trade_no)); var signStr = Helper.GetUrlString(data, false); System.Security.Cryptography.RSA rsacore = Way.Lib.RSA.CreateRsaFromPublicKey(config.alipayPublicKey); var isPass = rsacore.VerifyData(Encoding.GetEncoding("utf-8").GetBytes(signStr), Convert.FromBase64String(sign), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); if (isPass == false) { log.Log("sign:{0}", sign); log.Log("签名不一致"); httpProxy.ResponseWrite("fail"); return(TaskStatus.Completed); } //支付宝交易号 string trade_no = data["trade_no"]; //交易状态 //在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,才是买家付款成功。 string trade_status = data["trade_status"]; double?receipt_amount = null; try { receipt_amount = Convert.ToDouble(data["receipt_amount"]); } catch { } log.Log(trade_status); if (trade_status == "TRADE_SUCCESS") { log.Log("excute OnPaySuccessed"); PayFactory.OnPaySuccessed(out_trade_no, receipt_amount, null, dataJson); } httpProxy.ResponseWrite("success"); } else { httpProxy.ResponseWrite("无通知参数"); } } return(TaskStatus.Completed); }