/// <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 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); }
public TaskStatus Handle(IHttpProxy httpProxy) { var json = httpProxy.Form["request"]; try { using (CLog log = new CLog("IPaysoonNotify Notify")) { log.Log(json); var result = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json); if (result["resultCode"].ToString() == "0000" && result["statusId"].ToString() == "14") { var tradid = result["merchantGenCode"].ToString(); var charge = Convert.ToDouble(result["charge"].ToString()) / 100.0; var amount = Convert.ToDouble(result["amount"].ToString()) / 100.0; log.Log("tradid:{0} charge:{1} amount:{2}", tradid, charge, amount); log.Log("excute OnPaySuccessed"); PayFactory.OnPaySuccessed(tradid, amount - charge, null, json); } httpProxy.ResponseWrite("SUCCESS"); } } catch (Exception ex) { using (CLog log = new CLog("IPaysoon Notify error ")) { log.Log(ex.ToString()); } } return(TaskStatus.Completed); }
public override string BeginPay(PayParameter parameter) { var config = PayFactory.GetConfig <Config>(this.GetType(), parameter.TradeID); var head = new Dictionary <string, object>(); head["service"] = ServiceType; var body = new Dictionary <string, object>(); body["merchant_no"] = config.merchant_id; body["channel_type"] = ChannelType; body["out_trade_no"] = parameter.TradeID; body["total_amount"] = parameter.Amount.ToString(); body["subject"] = parameter.TradeName; body["spbill_create_ip"] = "8.8.8.8"; body["auth_code"] = parameter.AuthCode; var strResult = LianTuo_Helper.PostJsonReturnString(config, URL, head, body, parameter.RequestTimeout); PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, strResult); var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseObject>(strResult); string serverSign = responseObj.head["sign"].ToString(); if (LianTuo_Helper.Sign(config.key, responseObj.head, responseObj.body) != serverSign) { throw new Exception("服务器返回信息签名检验失败"); } if ((string)responseObj.body["is_success"] == "S") { double?receipt_amount = null; try { if (responseObj.body["receipt_amount"] != null) { receipt_amount = Convert.ToDouble(responseObj.body["receipt_amount"]); } } catch { } PayFactory.OnPaySuccessed(parameter.TradeID, receipt_amount, null, strResult); } else if ((string)responseObj.body["is_success"] == "F") { throw new Exception((string)responseObj.body["message"]); } else if ((string)responseObj.body["is_success"] == "P") { new Thread(() => { CheckPayStateInLoop(parameter); }).Start(); } return(null); }
public override bool CheckPayState(PayParameter parameter) { var config = PayFactory.GetConfig <Config>(this.GetType(), parameter.TradeID); var head = new Dictionary <string, object>(); head["service"] = "front.query"; var body = new Dictionary <string, object>(); body["out_trade_no"] = parameter.TradeID; var strResult = LianTuo_Helper.PostJsonReturnString(config, URL, head, body, parameter.RequestTimeout); var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseObject>(strResult); string serverSign = responseObj.head["sign"].ToString(); if (LianTuo_Helper.Sign(config.key, responseObj.head, responseObj.body) != serverSign) { throw new Exception("服务器返回信息签名检验失败"); } if ((string)responseObj.body["is_success"] == "S") { if ((string)responseObj.body["trade_status"] == "success") { double?receipt_amount = null; try { if (responseObj.body["receipt_amount"] != null) { receipt_amount = Convert.ToDouble(responseObj.body["receipt_amount"]); } } catch { } PayFactory.OnPaySuccessed(parameter.TradeID, receipt_amount, null, strResult); return(true); } else if ((string)responseObj.body["trade_status"] == "fail") { PayFactory.OnPayFailed(parameter.TradeID, (string)responseObj.body["trade_error_msg"], strResult); return(true); } else if ((string)responseObj.body["trade_status"] == "closed") { throw new Exception("订单已关闭"); } else if ((string)responseObj.body["trade_status"] == "cancel") { throw new Exception("订单已取消"); } } return(false); }
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.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); }
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()); } } }
bool checkPayStateByConfig(PayParameter parameter, Config config) { 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); return(true); } return(false); }
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); }
public TaskStatus Handle(IHttpProxy httpProxy) { try { var requestJson = httpProxy.Form["requestJson"]; if (!string.IsNullOrEmpty(requestJson)) { var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseObject>(requestJson); var tradeId = responseObj.body["out_trade_no"].ToString(); var config = PayFactory.GetConfig <Config>(typeof(LianTuo_WeixinJsApi), tradeId); string serverSign = responseObj.head["sign"].ToString(); if (LianTuo_Helper.Sign(config.key, responseObj.head, responseObj.body) != serverSign) { throw new Exception("服务器返回信息签名检验失败"); } if ((string)responseObj.body["is_success"] == "S") { double?receipt_amount = null; try { if (responseObj.body["receipt_amount"] != null) { receipt_amount = Convert.ToDouble(responseObj.body["receipt_amount"]); } } catch { } PayFactory.OnPaySuccessed(tradeId, receipt_amount, null, requestJson); } else if ((string)responseObj.body["is_success"] == "F") { PayFactory.OnPayFailed(tradeId, (string)responseObj.body["message"], requestJson); } } httpProxy.ResponseWrite("success"); } catch (Exception ex) { using (Log log = new Log("Jack.Pay.LianTuo.WXJSApi.Result Error", false)) { log.Log(ex.ToString()); log.LogJson(httpProxy.Form); } } return(TaskStatus.Completed); }
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 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); }
/// <summary> /// 处理服务器返回的结果 /// </summary> /// <param name="result">服务器返回的内容</param> /// <param name="resultDict"></param> /// <param name="parameter">支付参数</param> /// <returns></returns> protected virtual string OnBeginPayPostGetResult(string result, Config config, Newtonsoft.Json.Linq.JObject resultDict, PayParameter parameter) { if (resultDict["resultCode"].ToString() == "0000") { var rsa = Way.Lib.RSA.CreateRsaFromPrivateKey(config.merchantPrivateKey, Way.Lib.RSAKeyType.PKCS8); rsa.KeySize = 1024; var detailJson = System.Text.Encoding.UTF8.GetString(Way.Lib.RSA.DecryptFromBase64(rsa, resultDict["detail"].ToString(), RSAEncryptionPadding.Pkcs1)); var resultDetail = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(detailJson); if (resultDetail[0]["statusId"].ToString() == "14") { //var charge = Convert.ToDouble(resultDetail[0]["charge"].ToString()) / 100.0; var amount = Convert.ToDouble(resultDetail[0]["amount"].ToString()) / 100.0; var receiptAmount = Convert.ToDouble(resultDetail[0]["receiptAmount"].ToString()) / 100.0; PayFactory.OnPaySuccessed(parameter.TradeID, receiptAmount, null, result); } } else { throw new PayServerReportException(resultDict["resultMsg"].ToString()); } return(null); }
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); }
public override bool CheckPayState(PayParameter parameter) { var config = getConfig(parameter.TradeID); SortedDictionary <string, object> postDict = new SortedDictionary <string, object>(); postDict["outTradeNo"] = parameter.TradeID; postDict["sign"] = Cailutong_Helper.Sign(postDict, config.Secret); var result = Helper.PostJsonString(QueryUrl, Newtonsoft.Json.JsonConvert.SerializeObject(postDict), 8000); var resultDict = Newtonsoft.Json.JsonConvert.DeserializeObject <SortedDictionary <string, object> >(result); if (Cailutong_Helper.Sign(resultDict, config.Secret) != (string)resultDict["sign"]) { throw new Exception("服务器返回的数据校验失败"); } var status = Convert.ToInt32(resultDict["status"]); if (status <= 1) { return(false);//未支付 或者支付金额不足 } if (status == 999) { throw new Exception("交易已无效"); } if (status == 2) { PayFactory.OnPaySuccessed(parameter.TradeID, Convert.ToDouble(resultDict["payedAmount"]), null, result); return(true); } return(false); }
/// <summary> /// 检查订单状态 /// </summary> /// <param name="parameter"></param> /// <param name="config"></param> /// <returns>只要有结果,无论成功或者失败,返回true,不确定支付结果返回false</returns> bool checkPayStateByConfig(PayParameter parameter, WxPayConfig config) { try { 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, result.ToXml()); return(true); } //用户支付中,需要继续查询 else if (result.GetValue("trade_state").ToString() == "USERPAYING") { return(false); } else if (result.GetValue("trade_state").ToString() == "NOTPAY") { //触发回调函数 PayFactory.OnPayFailed(parameter.TradeID, "放弃支付", xml); return(true); } } string returnMsg = result.GetValue("err_code_des").ToSafeString(); if (string.IsNullOrEmpty(returnMsg)) { returnMsg = result.GetValue("return_msg").ToSafeString(); } //如果返回错误码为“此交易订单号不存在”,直接失败 if (result.GetValue("err_code").ToString() == "ORDERNOTEXIST") { //触发回调函数 PayFactory.OnPayFailed(parameter.TradeID, returnMsg, xml); return(true); } else if (result.GetValue("err_code").ToString() == "SYSTEMERROR") { //如果是系统错误,则后续继续 return(false); } else if (result.GetValue("return_code").ToString() == "FAIL" || result.GetValue("result_code").ToString() == "FAIL") { //FAIL //触发回调函数 PayFactory.OnPayFailed(parameter.TradeID, returnMsg, xml); return(true); } } catch { } return(false); }
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 handleReturn() { using (CLog log = new CLog("alipay handleReturn ")) { log.Log(Request.QueryString.ToString()); SortedDictionary <string, string> sPara = GetRequestGet(); if (sPara.Count > 0)//判断是否有带返回参数 { //Com.Alipay.Notify aliNotify = new Com.Alipay.Notify(); //bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]); bool verifyResult = true; if (verifyResult)//验证成功 { ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //请在这里加上商户的业务逻辑程序代码 //——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表 //商户订单号 string out_trade_no = Request.QueryString["out_trade_no"]; //支付宝交易号 string trade_no = Request.QueryString["trade_no"]; //交易状态 string trade_status = Request.QueryString["trade_status"]; string myStatus = ""; log.Log("trade_status:{0}", Request.QueryString["trade_status"]); if (Request.QueryString["trade_status"] == "TRADE_FINISHED" || Request.QueryString["trade_status"] == "TRADE_SUCCESS") { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 PayFactory.OnPaySuccessed(out_trade_no, Request.Form.ToJson()); myStatus = "SUCCESS"; } else { myStatus = HttpUtility.UrlEncode(Request.QueryString["trade_status"]); } string returnUrl = ReturnUrlConfigs[out_trade_no]; if (returnUrl.IsNullOrEmpty() == false) { log.Log("returnUrl:{0}", returnUrl); if (returnUrl.Contains("?") == false) { returnUrl += "?"; } else { returnUrl += "&"; } returnUrl += "status=" + myStatus + "&tradeID=" + HttpUtility.UrlEncode(out_trade_no) + "&interface=" + this.GetType().Name; //移除跳转地址,防止堆积过多 ReturnUrlConfigs.Remove(out_trade_no); Response.Write("<script>location.href=\"" + returnUrl + "\"</script>"); } } } } }
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 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); }
public TaskStatus Handle(IHttpProxy httpHandler) { try { var xml = httpHandler.ReadRequestBody(); using (CLog log = new CLog("WeiXinNotify Notify", false)) { log.Log("xml:{0}", xml); XDocument xmldoc = XDocument.Parse(xml); SortedDictionary <string, string> xmlDict = new SortedDictionary <string, string>(); var nodes = xmldoc.Root.Elements(); foreach (var element in nodes) { if (element.Name.LocalName != "sign") { xmlDict[element.Name.LocalName] = element.Value; } } var return_code = xmlDict["return_code"]; var result_code = xmlDict["result_code"]; var out_trade_no = xmlDict["out_trade_no"]; PayFactory.OnLog(out_trade_no, LogEventType.ReceiveNotify, xml); var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, out_trade_no)); log.Log("签名校验"); var sign = xmldoc.Root.XPathSelectElement("sign").Value; var computeSign = Helper.GetMd5Hash(xmlDict, config.Key); if (sign != computeSign) { log.Log("正确签名:{0}", computeSign); log.Log("签名校验不通过"); throw new Exception("签名校验不通过"); } if (result_code == "SUCCESS" && return_code == "SUCCESS") { log.Log("excute OnPaySuccessed"); PayFactory.OnPaySuccessed(out_trade_no, null, null, xml); 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)); var writebackXml = data.ToXml(); log.Log("write to weixin:{0}", writebackXml); httpHandler.ResponseWrite(writebackXml); } } } catch (Exception ex) { using (CLog log = new CLog("WeiXin Notify error ")) { log.Log(ex.ToString()); WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", ex.Message); var writebackXml = res.ToXml(); log.Log("write to weixin:{0}", writebackXml); httpHandler.ResponseWrite(writebackXml); } } return(TaskStatus.Completed); }
/// <summary> /// 直接付款,适合条码支付 /// </summary> /// <param name="parameter"></param> public virtual string StartPay(PayParameter parameter) { if (parameter.AuthCode.IsNullOrEmpty()) { throw new Exception("条码为空"); } if (parameter.TradeID.IsNullOrEmpty()) { throw new Exception("交易编号为空"); } try { Config config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayBarcode, parameter.TradeID)); //创建提交的内容 AlipayTradePayContentBuilder builder = BuildPayContent(config, parameter); var client = config.AppConfig.CreateAopClient(); AlipayTradePayRequest payRequest = new AlipayTradePayRequest(); payRequest.BizContent = builder.BuildJson(); AlipayTradePayResponse payResponse = client.Execute(payRequest); PayFactory.OnLog(parameter.TradeID, payResponse.Body); string[] errorCodes = new string[] { "20000", "20001", "40001", "40002", "40003", "40004", "40006" };//明确一定是错误的代码 if (errorCodes.Contains(payResponse.Code)) { PayFactory.OnPayFailed(parameter.TradeID, payResponse.SubMsg, payResponse.Body); } else if (payResponse.Code == ResultCode.SUCCESS) { PayFactory.OnPaySuccessed(parameter.TradeID, payResponse.Body); } else { //到这里,不能确定支付结果,循环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) { } return(null); }
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 override string BeginPay(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.pay"; 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, object> { { "out_trade_no", parameter.TradeID }, { "subject", parameter.TradeName }, { "body", parameter.Description }, { "total_amount", parameter.Amount.ToString("0.00") }, { "undiscountable_amount", "0" }, { "scene", "bar_code" }, // 支付场景 条码支付 { "auth_code", parameter.AuthCode }, //客户出示的二维码 { "timeout_express", Math.Max(1, parameter.Timeout / 60) + "m" }, // 订单允许的最晚付款时间 为两分钟 //{"operator_id", "app"}, // 商户操作员编号 //{"store_id", "NJ_001"}, // 商户门店编号 //{"terminal_id", "NJ_T_001"},// 商户机具终端编号 //{"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); // 把json结果转为对象 var payResult = Newtonsoft.Json.JsonConvert.DeserializeObject <AlipayTradePayResult>(result); CheckSign(result, "alipay_trade_pay_response", payResult.sign, config); // 明确一定是错误的代码 string[] errorCodes = { "20000", "20001", "40001", "40002", "40003", "40004", "40006" }; if (payResult.alipay_trade_pay_response.code == "10003") { throw new PayServerReportException("二维码重复提交"); } if (errorCodes.Contains(payResult.alipay_trade_pay_response.code)) { //明确交易失败了 throw new PayServerReportException(payResult.alipay_trade_pay_response.sub_msg); } else if (payResult.alipay_trade_pay_response.code == "10000") { double?discountAmount = null; if (!string.IsNullOrEmpty(payResult.alipay_trade_pay_response.discount_goods_detail)) { var discount_details = Newtonsoft.Json.JsonConvert.DeserializeObject <AlipayTradePayResult.Discount_goods_detail[]>(payResult.alipay_trade_pay_response.discount_goods_detail); discountAmount = discount_details.Sum(m => Convert.ToDouble(m.discount_amount)); } //明确交易成功了 PayFactory.OnPaySuccessed(parameter.TradeID, payResult.alipay_trade_pay_response.receipt_amount, discountAmount, result); } else //到这里,不能确定支付结果 { new Thread(() => { CheckPayStateInLoop(parameter); }).Start(); } return(null); }