public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查openid和product_id是否返回 if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "回调数据异常"); Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //调统一下单接口,获得下单结果 string openid = notifyData.GetValue("openid").ToString(); string product_id = notifyData.GetValue("product_id").ToString(); WxPayData unifiedOrderResult = new WxPayData(); try { unifiedOrderResult = UnifiedOrder(openid, product_id); } catch(Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台 { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //若下单失败,则立即返回结果给微信支付后台 if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //统一下单成功,则返回成功结果给微信支付后台 WxPayData data = new WxPayData(); data.SetValue("return_code", "SUCCESS"); data.SetValue("return_msg", "OK"); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("mch_id", WxPayConfig.MCHID); data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id")); data.SetValue("result_code", "SUCCESS"); data.SetValue("err_code_des", "OK"); data.SetValue("sign", data.MakeSign()); Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml()); page.Response.Write(data.ToXml()); page.Response.End(); }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); string out_trade_no= notifyData.GetValue("out_trade_no").ToString(); Log.Info(this.GetType().ToString(), "异步通知中的定单号:" + out_trade_no); //查询订单,判断订单真实性 if (!QueryOrder(transaction_id)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //查询订单成功 else { WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); //===========================修改定单状态 by xin.gao //确认支付,已支付,支付时间的更新 TOURISM.BLL.orders bll = new TOURISM.BLL.orders(); bool result = bll.UpdateField(out_trade_no, "status=2,payment_status=2,payment_id=4,payment_time='" + DateTime.Now + "'"); if (!result) { res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); Log.Error(this.GetType().ToString(), "修改订单状态失败 : " + res.ToXml()); } else { Log.Info(this.GetType().ToString(), "修改订单状态成功 : " + res.ToXml()); } //===========================修改定单状态结束 by xin.gao page.Response.Write(res.ToXml()); page.Response.End(); } }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 if (!QueryOrder(transaction_id)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //查询订单成功 else { if (notifyData.GetValue("result_code").ToString() == "SUCCESS") { Repair.DTO.Business.Order order = new Repair.DTO.Business.Order(); order.OrderID = int.Parse(notifyData.GetValue("attach").ToString()); order = Repair.Business.Business.OrderBLL.Get(order); order.Status = 6; order.TransactionID = transaction_id; order.PayTime = System.DateTime.Now; Repair.Business.Business.OrderBLL.Save(order); } WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } }
/** * 下载对账单 * @param WxPayData inputObj 提交给下载对账单API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData DownloadBill(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/downloadbill"; //检测必填参数 if (!inputObj.IsSet("bill_date")) { throw new WxPayException("对账单接口中,缺少必填参数bill_date!"); } inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串 inputObj.SetValue("sign", inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); Log.Debug("WxPayApi", "DownloadBill request : " + xml); string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API Log.Debug("WxPayApi", "DownloadBill result : " + response); WxPayData result = new WxPayData(); //若接口调用失败会返回xml格式的结果 if (response.Substring(0, 5) == "<xml>") { result.FromXml(response); } //接口调用成功则返回非xml格式的数据 else result.SetValue("result", response); return result; }
/** * * 关闭订单 * @param WxPayData inputObj 提交给关闭订单API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData CloseOrder(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/closeorder"; //检测必填参数 if(!inputObj.IsSet("out_trade_no")) { throw new WxPayException("关闭订单接口中,out_trade_no必填!"); } inputObj.SetValue("appid",WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id",WxPayConfig.MCHID);//商户号 inputObj.SetValue("nonce_str",GenerateNonceStr());//随机字符串 inputObj.SetValue("sign",inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 string response = HttpService.Post(xml, url, false, timeOut); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result; }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 if (!QueryOrder(transaction_id)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //查询订单成功 else { WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } }
/// <summary> /// 接收从微信支付后台发送过来的数据并验证签名 /// </summary> /// <returns>微信支付后台返回的数据</returns> public WxPayData GetNotifyData() { //接收从微信后台POST过来的数据 System.IO.Stream s = httpContext.Request.InputStream; int count = 0; byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); while ((count = s.Read(buffer, 0, 1024)) > 0) { builder.Append(Encoding.UTF8.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString()); //转换数据格式并验证签名 WxPayData data = new WxPayData(); try { data.FromXml(builder.ToString()); } catch(WxPayException ex) { //若签名错误,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", ex.Message); Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml()); httpContext.Response.Write(res.ToXml()); httpContext.Response.End(); } Log.Info(this.GetType().ToString(), "Check sign success"); return data; }
/** * 提交被扫支付API * 收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台, * 由商户收银台或者商户后台调用该接口发起支付。 * @param WxPayData inputObj 提交给被扫支付API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回调用结果,其他抛异常 */ public static WxPayData Micropay(WxPayData inputObj, int timeOut = 10) { string url = "https://api.mch.weixin.qq.com/pay/micropay"; //检测必填参数 if (!inputObj.IsSet("body")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数body!"); } else if (!inputObj.IsSet("out_trade_no")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数out_trade_no!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数total_fee!"); } else if (!inputObj.IsSet("auth_code")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数auth_code!"); } inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);//终端ip inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//随机字符串 inputObj.SetValue("sign", inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 Log.Debug("WxPayApi", "MicroPay request : " + xml); string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API Log.Debug("WxPayApi", "MicroPay response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result; }
public override Tuple <bool, WxPayData> ProcessNotify() { //System.IO.File.WriteAllText($"a{DateTime.Now.ToString("yyyyMMddHHmmssss")}.txt", "hi"); var result = GetNotifyData(); var notifyData = result.Item2; //System.IO.File.WriteAllText($"b-{DateTime.Now.ToString("yyyyMMddHHmmssss")}.txt", result.Item2.GetValue("out_trade_no").ToString() + "\r\n" + notifyData.ToJson()); //System.IO.File.WriteAllText($"c{DateTime.Now.ToString("yyyyMMddHHmmssss")}.txt", "result.Item1:" + result.Item1); if (result.Item1 == false) { return(Tuple.Create(false, notifyData)); } //检查openid和product_id是否返回 //if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id")) { if (!notifyData.IsSet("openid")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "回调数据异常"); Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml()); return(Tuple.Create(false, res)); } /* * //调统一下单接口,获得下单结果 * string openid = notifyData.GetValue("openid").ToString(); * //string product_id = notifyData.GetValue("product_id").ToString(); * //string product_id = "xxx"; * string orderId = notifyData.GetValue("out_trade_no").ToString(); * WxPayData unifiedOrderResult = new WxPayData(); * try { * unifiedOrderResult = UnifiedOrder(openid, orderId); * } catch (Exception ex) { * //若在调统一下单接口时抛异常,立即返回结果给微信支付后台 * WxPayData res = new WxPayData(); * res.SetValue("return_code", "FAIL"); * res.SetValue("return_msg", "统一下单失败"); * Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); * return Tuple.Create(false, res); * } * * //若下单失败,则立即返回结果给微信支付后台 * if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id")) { * WxPayData res = new WxPayData(); * res.SetValue("return_code", "FAIL"); * res.SetValue("return_msg", "统一下单失败"); * Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); * return Tuple.Create(false, res); * } * * * //统一下单成功,则返回成功结果给微信支付后台 * WxPayData data = new WxPayData(); * data.SetValue("return_code", "SUCCESS"); * data.SetValue("return_msg", "OK"); * data.SetValue("appid", WxPayConfig.APPID); * data.SetValue("mch_id", WxPayConfig.MCHID); * data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); * data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id")); * data.SetValue("result_code", "SUCCESS"); * data.SetValue("err_code_des", "OK"); * data.SetValue("sign", data.MakeSign()); * * Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml()); */ //System.IO.File.WriteAllText($"aaaaaa-{DateTime.Now.ToString("yyyyMMddHHmmssss")}.txt", result.Item2.GetValue("out_trade_no").ToString() + "\r\n" + notifyData.ToJson()); return(Tuple.Create(true, notifyData)); }
/** * * 统一下单 * @param WxPaydata inputObj 提交给统一下单API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //检测必填参数 if (!inputObj.IsSet("out_trade_no")) { throw new WxPayException("缺少统一支付接口必填参数out_trade_no!"); } else if (!inputObj.IsSet("body")) { throw new WxPayException("缺少统一支付接口必填参数body!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("缺少统一支付接口必填参数total_fee!"); } else if (!inputObj.IsSet("trade_type")) { throw new WxPayException("缺少统一支付接口必填参数trade_type!"); } //关联参数 if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid")) { throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!"); } if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id")) { throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!"); } //异步通知url未设置,则使用配置文件中的url if (!inputObj.IsSet("notify_url")) { inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url } HttpRequest requst = HttpContext.Current.Request; inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 string ip = "58.247.11.229";// GetIP();// requst.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ip)) { //ip = requst.ServerVariables["REMOTE_ADDR"]; } System.IO.File.AppendAllText(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt"), DateTime.Now.ToString() + ":ip = " + ip + Environment.NewLine); inputObj.SetValue("spbill_create_ip", requst.UserHostAddress);//WxPayConfig.IP);//终端ip requst.UserHostAddress);// inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串 //签名 inputObj.SetValue("sign", inputObj.MakeSign()); string xml = inputObj.ToXml(); System.IO.File.AppendAllText(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt"), DateTime.Now.ToString() + ":组装xml = " + xml + Environment.NewLine); var start = DateTime.Now; Log.Debug("WxPayApi", "UnfiedOrder request : " + xml); ////发起请求 string response = HttpService.Post(xml, url, false, timeOut); Log.Debug("WxPayApi", "UnfiedOrder response : " + response); System.IO.File.AppendAllText(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt"), DateTime.Now.ToString() + ":返回数据: = " + response + Environment.NewLine); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result; }
public override void ProcessNotify(int tid) { WxPayData notifyData = GetNotifyData(tid); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); page.Response.Write(res.ToXml()); page.Response.End(); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 string ordertime = notifyData.GetValue("time_end").ToString(); if (ordertime == "null") { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); page.Response.Write(res.ToXml()); page.Response.End(); } //查询订单成功 else { //商户订单号 string out_trade_no = notifyData.GetValue("out_trade_no").ToString(); //交易号 string trade_no = notifyData.GetValue("transaction_id").ToString(); //交易状态 string trade_status = notifyData.GetValue("result_code").ToString(); //买家账号 string buyer_email = notifyData.GetValue("transaction_id").ToString(); //买家付款时间 string gmt_payment = ordertime; //交易金额(单位:分转换成元) decimal o_price = decimal.Parse((decimal.Parse(notifyData.GetValue("total_fee").ToString()) / 100).ToString("f2")); if (trade_status == "SUCCESS") { try { JMP.BLL.jmp_order order = new JMP.BLL.jmp_order(); JMP.MDL.jmp_order morder = new JMP.MDL.jmp_order(); string TableName = "jmp_order"; string orderTableName = JMP.TOOL.WeekDateTime.GetOrderTableName(DateTime.ParseExact(gmt_payment, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd"));//获取订单表名 morder = order.GetModelbycode(out_trade_no, TableName); if (morder != null) { if (morder.o_price == o_price) { int payid = !string.IsNullOrEmpty(morder.o_paymode_id) ? Int32.Parse(morder.o_paymode_id) : 0; if (JMP.TOOL.OrderProportion.ddbl(morder.o_app_id, o_price, payid)) { WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); page.Response.Write(res.ToXml()); page.Response.End(); } else { if (morder.o_state != 1) { morder.o_tradeno = trade_no; morder.o_ptime = DateTime.ParseExact(gmt_payment, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture); morder.o_payuser = buyer_email; morder.o_state = 1; morder.o_noticestate = 0; morder.o_price = o_price; order.Update(morder, TableName); JMP.MDL.jmp_app app = new JMP.MDL.jmp_app(); JMP.BLL.jmp_app appbll = new JMP.BLL.jmp_app(); app = appbll.SelectId(morder.o_app_id); if (app != null) { JMP.MDL.jmp_queuelist quli = new JMP.MDL.jmp_queuelist(); JMP.BLL.jmp_queuelist bllq = new JMP.BLL.jmp_queuelist(); quli.q_address = morder.o_address; quli.q_sign = new JMP.BLL.jmp_app().GetModel(morder.o_app_id).a_secretkey; quli.q_noticestate = 0; quli.q_times = 0; quli.q_noticetimes = DateTime.Now; quli.q_tablename = orderTableName; quli.q_o_id = morder.o_id; quli.trade_type = Int32.Parse(morder.o_paymode_id); quli.trade_time = morder.o_ptime; quli.trade_price = morder.o_price; quli.trade_paycode = morder.o_tradeno; quli.trade_code = morder.o_code; quli.trade_no = morder.o_bizcode; quli.q_privateinfo = morder.o_privateinfo; quli.q_uersid = app.u_id; int cg = bllq.Add(quli); if (cg > 0) { WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); page.Response.Write(res.ToXml()); page.Response.End(); } else { //AddLocLog.AddLog(1, 4, HttpContext.Current.Request.UserHostAddress, "微信官网通知错误", "订单号:" + morder.o_code + "添加到通知队列失败");//写入报错日志 PayApiGlobalErrorLogger.Log("订单号:" + morder.o_code + "添加到通知队列失败", summary: "微信官网通知错误"); WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "FAIL"); page.Response.Write(res.ToXml()); page.Response.End(); } } else { //AddLocLog.AddLog(1, 4, HttpContext.Current.Request.UserHostAddress, "微信官网通知错误", "应用id:" + morder.o_app_id + ",获取用户id失败!");//写入报错日志 PayApiGlobalErrorLogger.Log("应用id:" + morder.o_app_id + ",获取用户id失败!", summary: "微信官网通知错误"); WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "FAIL"); page.Response.Write(res.ToXml()); page.Response.End(); } } else { //AddLocLog.AddLog(1, 4, HttpContext.Current.Request.UserHostAddress, "微信官网通知接口错误", "订单号:" + out_trade_no + ",未查询到相关信息!");//写入报错日志 PayApiGlobalErrorLogger.Log("订单号:" + out_trade_no + ",未查询到相关信息!", summary: "微信官网通知接口错误"); WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); page.Response.Write(res.ToXml()); page.Response.End(); } } } else { if (JMP.TOOL.UpdateOrder.OrderState.UpdateOrderState(morder.o_code, TableName)) { string ddsm = "订单号:" + morder.o_code + ",支付信息异常请核实!";//短信说明 JMP.TOOL.Auditor.IAuditor audit = new JMP.TOOL.Auditor.OrderAbnormalAuditor(morder.o_code, orderTableName, morder.o_app_id, ddsm, trade_no, DateTime.ParseExact(gmt_payment, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture), o_price, "成功", morder.o_price); audit.Add(); WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); page.Response.Write(res.ToXml()); page.Response.End(); } else { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "FAIL"); page.Response.Write(res.ToXml()); page.Response.End(); } } } else { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "FAIL"); page.Response.Write(res.ToXml()); page.Response.End(); } } catch { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "FAIL"); page.Response.Write(res.ToXml()); page.Response.End(); } } } }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 if (!QueryOrder(transaction_id)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //查询订单成功 else { Log.Info(this.GetType().ToString(), "订单支付成功,异步回调"); #region 支付成功,异步更新订单表2016-06-30TS Model_UserOrder model = new Model_UserOrder(); BLL_UserOrder bll = new BLL_UserOrder(); model = bll.GetModelByOrderNo(notifyData.GetValue("out_trade_no").ToString()); if (model.UserOrder_Status == (int)UOrderStatus.待付款 || string.IsNullOrEmpty(model.trade_no) || string.IsNullOrEmpty(model.trade_status)) { model.UserOrder_Paytool = UserOrder_PaytoolEnum.WXPAY.ToString(); model.UsreOrder_Buyeremail = notifyData.GetValue("openid").ToString(); model.trade_no = notifyData.GetValue("transaction_id").ToString(); model.trade_status = notifyData.GetValue("return_code").ToString(); model.UserOrder_Status = (int)UOrderStatus.完成; model.UserOrder_FinishTime = DateTime.Now; bool executeFlag = false; if (new BLL_UserBuyResources().GetRecordCount(string.Format("UserId='{0}' and Book_id='{1}' ", model.UserId, model.Book_Id)) == 0) { #region 用户购买资源表 Model_UserBuyResources buyModel = new Model_UserBuyResources(); buyModel.UserBuyResources_ID = Guid.NewGuid().ToString(); buyModel.UserId = model.UserId; buyModel.Book_id = model.Book_Id; buyModel.BookPrice = model.Book_Price; buyModel.BuyType = UserOrder_PaytoolEnum.WXPAY.ToString(); buyModel.CreateTime = DateTime.Now; buyModel.CreateUser = "******"; #endregion executeFlag = bll.UpdateAndAddUserBuyResources(model, buyModel); } else { executeFlag = bll.Update(model); } if (executeFlag) { new Rc.Cloud.BLL.BLL_clsAuth().AddLogFromBS(page.Request.Url.ToString(), string.Format("微信回调。购买资源成功,购买人:{0},资源标识:{1}" , model.UserId, model.Book_Id)); } } #endregion WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); page.Response.Write(res.ToXml()); page.Response.End(); } }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); if (!notifyData.IsSet("transaction_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); string appid = notifyData.GetValue("appid").ToString(); string mchid = notifyData.GetValue("mch_id").ToString(); if (!QueryOrder(transaction_id, appid, mchid)) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } else { /** ================out_trade_no 我们的订单号 cash_fee 支付金额分 transaction_id 微信支付单号 ========= */ if (notifyData.GetValue("return_code").ToString() == "SUCCESS") { if (notifyData.GetValue("result_code").ToString() == "SUCCESS") { if (notifyData.GetValue("out_trade_no").ToString().IndexOf("C") > -1 || notifyData.GetValue("out_trade_no").ToString().IndexOf("c") > -1) { string tsql = @"insert into WeiXin..wkn_payrecords(OrderNO,TradeNo,UserWeiXinID,AliPayAmount,OperationRecord,Channel,Mchid) values(@OrderNO,@TradeNo,@UserWeiXinID,@AliPayAmount,@OperationRecord,'微信支付回调',@Mchid); "; int Status = HotelCloud.SqlServer.SQLHelper.Run_SQL(tsql, HotelCloud.SqlServer.SQLHelper.Open_Conn(System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString.ToString()), new Dictionary <string, HotelCloud.SqlServer.DBParam> { { "OrderNO", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("out_trade_no").ToString() } }, { "TradeNo", new HotelCloud.SqlServer.DBParam { ParamValue = transaction_id } }, { "Mchid", new HotelCloud.SqlServer.DBParam { ParamValue = mchid } }, { "UserWeiXinID", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("openid").ToString() } }, { "AliPayAmount", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("cash_fee").ToString() } }, { "OperationRecord", new HotelCloud.SqlServer.DBParam { ParamValue = "[微信支付]:商户号" + mchid + "," + notifyData.GetValue("openid").ToString() + "于" + DateTime.Now.ToString() + "支付" + notifyData.GetValue("cash_fee").ToString() + "分</br>" } } }); if (Status > 0) { WeiXin.Models.Home.RechargeCard.DoUserRechargeSuccess(notifyData.GetValue("out_trade_no").ToString()); } } else if (notifyData.GetValue("out_trade_no").ToString().IndexOf("K") > -1 || notifyData.GetValue("out_trade_no").ToString().IndexOf("k") > -1) { string tsql = @"insert into WeiXin..wkn_payrecords(OrderNO,TradeNo,UserWeiXinID,AliPayAmount,OperationRecord,Channel,Mchid) values(@OrderNO,@TradeNo,@UserWeiXinID,@AliPayAmount,@OperationRecord,'微信支付回调',@Mchid); "; int Status = HotelCloud.SqlServer.SQLHelper.Run_SQL(tsql, HotelCloud.SqlServer.SQLHelper.Open_Conn(System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString.ToString()), new Dictionary <string, HotelCloud.SqlServer.DBParam> { { "OrderNO", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("out_trade_no").ToString() } }, { "TradeNo", new HotelCloud.SqlServer.DBParam { ParamValue = transaction_id } }, { "Mchid", new HotelCloud.SqlServer.DBParam { ParamValue = mchid } }, { "UserWeiXinID", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("openid").ToString() } }, { "AliPayAmount", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("cash_fee").ToString() } }, { "OperationRecord", new HotelCloud.SqlServer.DBParam { ParamValue = "[微信支付]:商户号" + mchid + "," + notifyData.GetValue("openid").ToString() + "于" + DateTime.Now.ToString() + "支付" + notifyData.GetValue("cash_fee").ToString() + "分</br>" } } }); if (Status > 0) { hotel3g.Models.Home.MemberCardBuyRecord.DoneOrderSuccess(notifyData.GetValue("out_trade_no").ToString()); } } else if (notifyData.GetValue("out_trade_no").ToString().IndexOf("D") > -1) { string tsql = @"insert into WeiXin..wkn_payrecords(OrderNO,TradeNo,UserWeiXinID,AliPayAmount,OperationRecord,Channel,Mchid) values(@OrderNO,@TradeNo,@UserWeiXinID,@AliPayAmount,@OperationRecord,'微信支付回调',@Mchid); update WeiXin..SupermarketOrder_Levi set OrderStatus=2,PayStatus=2,PayTime=getdate(),aliPayAmount=@AliPayAmount,tradeNo=@TradeNo where OrderId =@OrderNO;INSERT INTO WeiXin..SupermarketOrderLog_Levi([OrderId],[Context],[LogType],[CreateUser],[CreateTime]) VALUES(@OrderNO,'订单状态流转为:已付款',1,'用户',GETDATE());"; int Status = HotelCloud.SqlServer.SQLHelper.Run_SQL(tsql, HotelCloud.SqlServer.SQLHelper.Open_Conn(System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString.ToString()), new Dictionary <string, HotelCloud.SqlServer.DBParam> { { "OrderNO", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("out_trade_no").ToString() } }, { "TradeNo", new HotelCloud.SqlServer.DBParam { ParamValue = transaction_id } }, { "Mchid", new HotelCloud.SqlServer.DBParam { ParamValue = mchid } }, { "UserWeiXinID", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("openid").ToString() } }, { "AliPayAmount", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("cash_fee").ToString() } }, { "OperationRecord", new HotelCloud.SqlServer.DBParam { ParamValue = "[微信支付]:商户号" + mchid + "," + notifyData.GetValue("openid").ToString() + "于" + DateTime.Now.ToString() + "支付" + notifyData.GetValue("cash_fee").ToString() + "分</br>" } } }); } else if (notifyData.GetValue("out_trade_no").ToString().IndexOf("P") > -1 || notifyData.GetValue("out_trade_no").ToString().IndexOf("p") > -1) { Dictionary <string, HotelCloud.SqlServer.DBParam> dic_p = new Dictionary <string, HotelCloud.SqlServer.DBParam> { { "OrderNO", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("out_trade_no").ToString() } }, { "TradeNo", new HotelCloud.SqlServer.DBParam { ParamValue = transaction_id } }, { "Mchid", new HotelCloud.SqlServer.DBParam { ParamValue = mchid } }, { "UserWeiXinID", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("openid").ToString() } }, { "AliPayAmount", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("cash_fee").ToString() } }, { "OperationRecord", new HotelCloud.SqlServer.DBParam { ParamValue = "[微信支付]:商户号" + mchid + "," + notifyData.GetValue("openid").ToString() + "于" + DateTime.Now.ToString() + "支付" + notifyData.GetValue("cash_fee").ToString() + "分</br>" } } }; string tsql = @"insert into WeiXin..wkn_payrecords(OrderNO,TradeNo,UserWeiXinID,AliPayAmount,OperationRecord,Channel,Mchid) values(@OrderNO,@TradeNo,@UserWeiXinID,@AliPayAmount,@OperationRecord,'微信支付回调',@Mchid); "; int Status = HotelCloud.SqlServer.SQLHelper.Run_SQL(tsql, HotelCloud.SqlServer.SQLHelper.Open_Conn(System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString.ToString()), dic_p); if (Status > 0) { tsql = "update WeiXin..SaleProducts_Orders set OrderStatus=3, Remark=isnull(Remark,'')+@OperationRecord,IsPay=1,PayTime=getdate() where OrderNo=@OrderNO and IsPay=0 "; int p_rows = HotelCloud.SqlServer.SQLHelper.Run_SQL(tsql, HotelCloud.SqlServer.SQLHelper.Open_Conn(System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString.ToString()), dic_p); if (p_rows > 0) { WeiXin.Models.Home.SaleProducts_Orders.DoneOrderSuccess(notifyData.GetValue("out_trade_no").ToString()); } } } else if (notifyData.GetValue("out_trade_no").ToString().IndexOf("L") > -1) { string tsql = @"insert into WeiXin..wkn_payrecords(OrderNO,TradeNo,UserWeiXinID,AliPayAmount,OperationRecord,Channel,Mchid) values(@OrderNO,@TradeNo,@UserWeiXinID,@AliPayAmount,@OperationRecord,'微信支付回调',@Mchid); update WeiXin..T_OrderInfo set Status=9,payTime=getdate(),orderPayState=1,tradeNo=@TradeNo,aliPayAmount=@AliPayAmount,remark=isnull(remark,'')+@OperationRecord where orderCode=@OrderNO;"; int Status = HotelCloud.SqlServer.SQLHelper.Run_SQL(tsql, HotelCloud.SqlServer.SQLHelper.Open_Conn(System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString.ToString()), new Dictionary <string, HotelCloud.SqlServer.DBParam> { { "OrderNO", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("out_trade_no").ToString() } }, { "TradeNo", new HotelCloud.SqlServer.DBParam { ParamValue = transaction_id } }, { "Mchid", new HotelCloud.SqlServer.DBParam { ParamValue = mchid } }, { "UserWeiXinID", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("openid").ToString() } }, { "AliPayAmount", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("cash_fee").ToString() } }, { "OperationRecord", new HotelCloud.SqlServer.DBParam { ParamValue = "[微信支付]:商户号" + mchid + "," + notifyData.GetValue("openid").ToString() + "于" + DateTime.Now.ToString() + "支付" + notifyData.GetValue("cash_fee").ToString() + "分</br>" } } }); hotel3g.Models.DishOrderLogic.SettingOrderXuHao(notifyData.GetValue("out_trade_no").ToString()); } else if (notifyData.GetValue("out_trade_no").ToString().IndexOf("wx") > -1) { string attach = notifyData.GetValue("attach").ToString(); string tsql = @"update WeiXin..wkn_quickpayment set PaymentStatus='已支付' where orderno=@OrderNO and WeiXinID=@WeiXinID;insert into WeiXin..wkn_payrecords(OrderNO,TradeNo,UserWeiXinID,AliPayAmount,OperationRecord,Channel,Mchid,WeiXinID,Mhid) values(@OrderNO,@TradeNo,@UserWeiXinID,@AliPayAmount,@OperationRecord,@Channel,@Mchid,@WeiXinID,@Mhid);"; int Status = HotelCloud.SqlServer.SQLHelper.Run_SQL(tsql, HotelCloud.SqlServer.SQLHelper.Open_Conn(System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString.ToString()), new Dictionary <string, HotelCloud.SqlServer.DBParam> { { "OrderNO", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("out_trade_no").ToString() } }, { "TradeNo", new HotelCloud.SqlServer.DBParam { ParamValue = transaction_id } }, { "Mchid", new HotelCloud.SqlServer.DBParam { ParamValue = mchid } }, { "UserWeiXinID", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("openid").ToString() } }, { "AliPayAmount", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("cash_fee").ToString() } }, { "WeiXinID", new HotelCloud.SqlServer.DBParam { ParamValue = attach.Split('|')[1].ToString().Trim() } }, { "Mhid", new HotelCloud.SqlServer.DBParam { ParamValue = attach.Split('|')[0].ToString().Trim() } }, { "Channel", new HotelCloud.SqlServer.DBParam { ParamValue = (attach.Split('|')[2].ToString().Trim() == "0"?"收款支付回调":"押金支付回调") } }, { "OperationRecord", new HotelCloud.SqlServer.DBParam { ParamValue = "[微信支付]:商户号" + mchid + "," + notifyData.GetValue("openid").ToString() + "于" + DateTime.Now.ToString() + "支付" + notifyData.GetValue("cash_fee").ToString() + "分</br>" } } }); //异步发送微信收款成功通知 2017-10-11 16:54 System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(() => { try { WxPayAPI.Log.Info("执行异步操作,异步发送微信收款成功通知", notifyData.GetValue("out_trade_no").ToString()); var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.weikeniu.com/WeixinFeatures/sendWeiXin.aspx"); var postData = "action=shoukuan&orderId=" + notifyData.GetValue("out_trade_no").ToString() + "&weixinid=" + attach.Split('|')[1].ToString().Trim(); var data = System.Text.Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()){ stream.Write(data, 0, data.Length); } var response = (System.Net.HttpWebResponse)request.GetResponse(); var responseString = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd(); string result = responseString.ToString(); WxPayAPI.Log.Info("执行异步操作,发送结果:", result); } catch (Exception ex) { WxPayAPI.Log.Info("执行异步操作,bug:", notifyData.GetValue("out_trade_no").ToString() + "|" + ex.Message.ToString()); } finally { } }); task.Start(); } else { string tsql = @"insert into WeiXin..wkn_payrecords(OrderNO,TradeNo,UserWeiXinID,AliPayAmount,OperationRecord,Channel,Mchid) values(@OrderNO,@TradeNo,@UserWeiXinID,@AliPayAmount,@OperationRecord,'微信支付回调',@Mchid); update WeiXin..HotelOrder set Remark=isnull(Remark,'')+@OperationRecord,aliPayAmount=@AliPayAmount,aliPayTime=getdate(),tradeStatus='TRADE_FINISHED',state=24,tradeNo=@TradeNo where OrderNO=@OrderNO;"; int Status = HotelCloud.SqlServer.SQLHelper.Run_SQL(tsql, HotelCloud.SqlServer.SQLHelper.Open_Conn(System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString.ToString()), new Dictionary <string, HotelCloud.SqlServer.DBParam> { { "OrderNO", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("out_trade_no").ToString() } }, { "TradeNo", new HotelCloud.SqlServer.DBParam { ParamValue = transaction_id } }, { "Mchid", new HotelCloud.SqlServer.DBParam { ParamValue = mchid } }, { "UserWeiXinID", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("openid").ToString() } }, { "AliPayAmount", new HotelCloud.SqlServer.DBParam { ParamValue = notifyData.GetValue("cash_fee").ToString() } }, { "OperationRecord", new HotelCloud.SqlServer.DBParam { ParamValue = "[微信支付]:商户号" + mchid + "," + notifyData.GetValue("openid").ToString() + "于" + DateTime.Now.ToString() + "支付" + notifyData.GetValue("cash_fee").ToString() + "分</br>" } } }); } } } WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } }
public WXPayBack ProcessNotify(bool isApp) { WXPayBack result = new WXPayBack() { ResultCode = 0, Msg = "获取请求成功" }; SortedDictionary<string, object> paras; WxPayData notifyData = GetNotifyData(out paras); //string str = "WX支付异步返回成功"; //foreach (var item in paras) //{ // str += string.Format("{0}={1},", item.Key, item.Value); //} //str.WriteLog(); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml()); page.Response.Write(res.ToXml()); //page.Response.End(); result.SetPara(-1, "", "", "支付结果中微信订单号不存在"); return result; } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 if (!QueryOrder(transaction_id, true)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml()); page.Response.Write(res.ToXml()); //page.Response.End(); result.SetPara(-2, "", "", "订单查询失败"); } //查询订单成功 else { WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml()); page.Response.Write(res.ToXml()); //page.Response.End(); result.SetPara(1, paras["attach"].ToString(), AlipayConfig.MoneyFormatDco(paras["total_fee"].ToString()).ToString(), "查询订单成功"); string.Format("dingdanhao:{0},jine:{1} zhifuchenggon ", paras["attach"].ToString(), AlipayConfig.MoneyFormatDco(paras["total_fee"].ToString()).ToString()).WriteLog(); } return result; }
/** * * 转换短链接 * 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX), * 减小二维码数据量,提升扫描速度和精确度。 * @param WxPayData inputObj 提交给转换短连接API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData ShortUrl(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/tools/shorturl"; //检测必填参数 if(!inputObj.IsSet("long_url")) { throw new WxPayException("需要转换的URL,签名用原串,传输需URL encode!"); } inputObj.SetValue("appid",WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id",WxPayConfig.MCHID);//商户号 inputObj.SetValue("nonce_str",GenerateNonceStr());//随机字符串 inputObj.SetValue("sign",inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 Log.Debug("WxPayApi", "ShortUrl request : " + xml); string response = HttpService.Post(xml, url, false, timeOut); Log.Debug("WxPayApi", "ShortUrl response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result; }
/** * * 统一下单 * @param WxPaydata inputObj 提交给统一下单API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //检测必填参数 if (!inputObj.IsSet("out_trade_no")) { LogHelper.Error("out_trade_no 为空"); throw new WxPayException("缺少统一支付接口必填参数out_trade_no!"); } else if (!inputObj.IsSet("body")) { LogHelper.Error("body 为空"); throw new WxPayException("缺少统一支付接口必填参数body!"); } else if (!inputObj.IsSet("total_fee")) { LogHelper.Error("total_fee 为空"); throw new WxPayException("缺少统一支付接口必填参数total_fee!"); } else if (!inputObj.IsSet("trade_type")) { LogHelper.Error("trade_type 为空"); throw new WxPayException("缺少统一支付接口必填参数trade_type!"); } //LogHelper.Error("openid " + inputObj.IsSet("openid")); //关联参数 if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid")) { LogHelper.Error("openid 为空"); throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!"); } if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id")) { LogHelper.Error("trade_type 为空"); throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!"); } //异步通知url未设置,则使用配置文件中的url if (!inputObj.IsSet("notify_url")) { inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url } //LogHelper.Error("获取result"); inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 string ip = ""; System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList; for (int i = 0; i < addressList.Length; i++) { ip = addressList[i].ToString(); } inputObj.SetValue("spbill_create_ip", ip); //终端ip inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 //签名 inputObj.SetValue("sign", inputObj.MakeSign()); string xml = inputObj.ToXml(); var start = DateTime.Now; string response = HttpService.Post(xml, url, false, timeOut); //LogHelper.Error("---UnfiedOrder response : " + response + "---UnfiedOrder request : " + xml + "---获取nonce_str" + GenerateNonceStr()); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); //LogHelper.Error("UnfiedOrder request : " + result); ReportCostTime(url, timeCost, result);//测速上报 return(result); }
/** * * 测速上报接口实现 * @param WxPayData inputObj 提交给测速上报接口的参数 * @param int timeOut 测速上报接口超时时间 * @throws WxPayException * @return 成功时返回测速上报接口返回的结果,其他抛异常 */ public static WxPayData Report(WxPayData inputObj, int timeOut = 1) { string url = "https://api.mch.weixin.qq.com/payitil/report"; //检测必填参数 if(!inputObj.IsSet("interface_url")) { throw new WxPayException("接口URL,缺少必填参数interface_url!"); } if(!inputObj.IsSet("return_code")) { throw new WxPayException("返回状态码,缺少必填参数return_code!"); } if(!inputObj.IsSet("result_code")) { throw new WxPayException("业务结果,缺少必填参数result_code!"); } if(!inputObj.IsSet("user_ip")) { throw new WxPayException("访问接口IP,缺少必填参数user_ip!"); } if(!inputObj.IsSet("execute_time_")) { throw new WxPayException("接口耗时,缺少必填参数execute_time_!"); } inputObj.SetValue("appid",WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id",WxPayConfig.MCHID);//商户号 inputObj.SetValue("user_ip",WxPayConfig.IP);//终端ip inputObj.SetValue("time",DateTime.Now.ToString("yyyyMMddHHmmss"));//商户上报时间 inputObj.SetValue("nonce_str",GenerateNonceStr());//随机字符串 inputObj.SetValue("sign",inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); Log.Info("WxPayApi", "Report request : " + xml); string response = HttpService.Post(xml, url, false, timeOut); Log.Info("WxPayApi", "Report response : " + response); WxPayData result = new WxPayData(); result.FromXml(response); return result; }
/** * * 申请退款 * @param WxPayData inputObj 提交给申请退款API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回接口调用结果,其他抛异常 */ public static WxPayData Refund(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; //检测必填参数 if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) { throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!"); } else if (!inputObj.IsSet("out_refund_no")) { throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("退款申请接口中,缺少必填参数total_fee!"); } else if (!inputObj.IsSet("refund_fee")) { throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!"); } else if (!inputObj.IsSet("op_user_id")) { throw new WxPayException("退款申请接口中,缺少必填参数op_user_id!"); } inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//随机字符串 inputObj.SetValue("sign", inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); var start = DateTime.Now; Log.Debug("WxPayApi", "Refund request : " + xml); string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API Log.Debug("WxPayApi", "Refund response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result; }
/// <summary> /// 微信支付专用逻辑 /// </summary> /// <returns></returns> public ActionResult WxPay() { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; ViewBag.OrderNo = Request.QueryString["orderNo"].ToString(); ViewBag.TotalPrice = double.Parse(Request.QueryString["totalprice"].ToString()); OrderResultModel orm = new OrderResultModel(); orm.openid = System.Web.HttpContext.Current.Session["member"].ToString(); orm.total_fee = double.Parse(Request.QueryString["totalprice"].ToString()) * 100; orm.trade_type = "JSAPI"; orm.spbill_create_ip = Request.QueryString["ip"].ToString(); orm.out_trade_no = Request.QueryString["orderNo"].ToString(); orm.appid = WxPayAPI.WxPayConfig.APPID; orm.body = "捷诚宝商城"; orm.mch_id = WxPayAPI.WxPayConfig.MCHID; orm.nonce_str = WxPayAPI.WxPayApi.GenerateNonceStr(); orm.notify_url = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Host + ":" + HttpContext.Request.Url.Port + "/Pay/WxPayResult"; WxPayAPI.WxPayData data = new WxPayAPI.WxPayData(); data.SetValue("openid", orm.openid); data.SetValue("total_fee", orm.total_fee); data.SetValue("trade_type", orm.trade_type); data.SetValue("spbill_create_ip", orm.spbill_create_ip); data.SetValue("out_trade_no", orm.out_trade_no); data.SetValue("appid", orm.appid); data.SetValue("body", orm.body); data.SetValue("mch_id", orm.mch_id); data.SetValue("nonce_str", orm.nonce_str); data.SetValue("notify_url", orm.notify_url); orm.sign = data.MakeSign(); data.SetValue("sign", orm.sign); foreach (var item in data.GetValues()) { LogHelper.Log.Write(item.Key + ":" + item.Value); } string xml = data.ToXml(); string response = WxPayAPI.HttpService.Post(xml, url, false, 5); WxPayAPI.WxPayData result = new WxPayAPI.WxPayData(); result.FromXml(response); WxPayAPI.WxPayData jsApiParam = new WxPayAPI.WxPayData(); jsApiParam.SetValue("appId", result.GetValue("appid")); jsApiParam.SetValue("timeStamp", WxPayAPI.WxPayApi.GenerateTimeStamp()); jsApiParam.SetValue("nonceStr", WxPayAPI.WxPayApi.GenerateNonceStr()); jsApiParam.SetValue("package", "prepay_id=" + result.GetValue("prepay_id")); jsApiParam.SetValue("signType", "MD5"); jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); string jsonParam = jsApiParam.ToJson(); ViewData["Result"] = result; ViewData["JsonResult"] = jsonParam; return(View()); }
public ActionResult RechargePay(double money, string ip) { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; string orderNo = Guid.NewGuid().ToString().Replace("-", "").ToUpper().Substring(0, 6) + TimeManager.GetCurrentTimestamp(); ViewBag.OrderNo = orderNo; ViewBag.TotalPrice = money; OrderResultModel orm = new OrderResultModel(); orm.openid = System.Web.HttpContext.Current.Session["member"].ToString(); orm.total_fee = money * 100; orm.trade_type = "JSAPI"; orm.spbill_create_ip = ip; orm.out_trade_no = orderNo; orm.appid = WxPayAPI.WxPayConfig.APPID; orm.body = "捷诚宝个人中心充值"; orm.mch_id = WxPayAPI.WxPayConfig.MCHID; orm.nonce_str = WxPayAPI.WxPayApi.GenerateNonceStr(); orm.notify_url = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Host + ":" + HttpContext.Request.Url.Port + "/Pay/RechargePayResult"; LogHelper.Log.Write(orm.notify_url); WxPayAPI.WxPayData data = new WxPayAPI.WxPayData(); data.SetValue("openid", orm.openid); data.SetValue("total_fee", orm.total_fee); data.SetValue("trade_type", orm.trade_type); data.SetValue("spbill_create_ip", orm.spbill_create_ip); data.SetValue("out_trade_no", orm.out_trade_no); data.SetValue("appid", orm.appid); data.SetValue("body", orm.body); data.SetValue("mch_id", orm.mch_id); data.SetValue("nonce_str", orm.nonce_str); data.SetValue("notify_url", orm.notify_url); orm.sign = data.MakeSign(); data.SetValue("sign", orm.sign); //LogHelper.Log.Write("openid:" + data.GetValue("openid")); //LogHelper.Log.Write("total_fee:" + data.GetValue("total_fee")); //LogHelper.Log.Write("appid:" + data.GetValue("appid")); //LogHelper.Log.Write("notify_url:" + data.GetValue("notify_url")); string xml = data.ToXml(); string response = WxPayAPI.HttpService.Post(xml, url, false, 5); WxPayAPI.WxPayData result = new WxPayAPI.WxPayData(); result.FromXml(response); WxPayAPI.WxPayData jsApiParam = new WxPayAPI.WxPayData(); jsApiParam.SetValue("appId", result.GetValue("appid")); jsApiParam.SetValue("timeStamp", WxPayAPI.WxPayApi.GenerateTimeStamp()); jsApiParam.SetValue("nonceStr", WxPayAPI.WxPayApi.GenerateNonceStr()); jsApiParam.SetValue("package", "prepay_id=" + result.GetValue("prepay_id")); jsApiParam.SetValue("signType", "MD5"); jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); string jsonParam = jsApiParam.ToJson(); ViewData["Result"] = result; ViewData["JsonResult"] = jsonParam; return(View()); }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 if (!QueryOrder(transaction_id)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); Log.Error(this.GetType().ToString(), "订单查询失败 : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //查询订单成功 else { WxPayData res = new WxPayData(); try { Log.Debug(this.GetType().ToString(), "订单状态 : " + notifyData.GetValue("result_code").ToString()); if (notifyData.GetValue("result_code").ToString() == "SUCCESS") { string orderNo = notifyData.GetValue("out_trade_no").ToString(); Log.Debug(this.GetType().ToString(), "订单号 : " + orderNo); if (!string.IsNullOrWhiteSpace(orderNo)) { using (_databaseInstance = new DatabaseInstance(_database)) { var sql = "select * from fz_Orders where orderNo=@orderNo"; var item = new QueryObject <Ecard.Models.Order>(_databaseInstance, sql, new { orderNo = orderNo }).FirstOrDefault(); if (item != null) { #region 商城订单 if (item.payState == Ecard.Models.PayStates.non_payment && item.orderState == Ecard.Models.OrderStates.awaitPay) { decimal amount = 0; if (int.Parse(notifyData.GetValue("total_fee").ToString()) > 0) { amount = decimal.Parse(notifyData.GetValue("total_fee").ToString()) / 100; } if (item.payAmount == amount) { _databaseInstance.BeginTransaction(); item.payState = Ecard.Models.PayStates.paid; item.orderState = Ecard.Models.OrderStates.paid; item.payType = PayTypes.weChatPayment; item.submitTime = DateTime.Now; _databaseInstance.Update(item, "fz_Orders"); //var sql2 = "select * from fz_Accounts where accountId=@accountId"; //var item2 = new QueryObject<Ecard.Models.Account>(_databaseInstance, sql2, new { accountId = item.userId }).FirstOrDefault(); //if (item2 !=null) //{ // if (!string.IsNullOrWhiteSpace(item2.openID)) // { // var message = new Fz_Messages(); // message.accountId = item2.accountId; // message.openId = item2.openID; // message.state = MessagesState.staySend; // message.submitTime = DateTime.Now; // message.keyword1 = item.orderNo; // message.keyword2 = "已付款"; // message.msgType = MsgType.orderState; // _databaseInstance.Insert(message, "Fz_Messages"); // } //} _databaseInstance.Commit(); Log.Debug(this.GetType().ToString(), "开始返利 : " + orderNo); if (item.orderType == OrderType.normal) { IRebateService.Rebate3(item.orderId); } Log.Debug(this.GetType().ToString(), "返利结束 : " + orderNo); } else { res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "金额错误,支付金额于订单金额不一致"); Log.Error(this.GetType().ToString(), "订单金额失败 : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } } #endregion } else { #region payorder 订单 var sqlPayOrder = "select * from PayOrder where orderNo=@orderNo"; var payOrder = new QueryObject <Ecard.Models.PayOrder>(_databaseInstance, sqlPayOrder, new { orderNo = orderNo }).FirstOrDefault(); if (payOrder != null) { if (payOrder.orderState == PayOrderStates.awaitPay) { _databaseInstance.BeginTransaction(); payOrder.orderState = PayOrderStates.paid; payOrder.payTime = DateTime.Now; _databaseInstance.Update(payOrder, "PayOrder"); var account = IAccountService.GetByUserId(payOrder.userId); if (account != null) { int grade = -1; if (payOrder.item == PayOrderItems.member) { grade = AccountGrade.Member; } else if (payOrder.item == PayOrderItems.shopowner) { grade = AccountGrade.Manager; } else if (payOrder.item == PayOrderItems.shopkeeper) { grade = AccountGrade.GoldMedalManager; } if (account.grade < grade) { account.grade = grade; } _databaseInstance.Update(account, "fz_Accounts"); } _databaseInstance.Commit(); if (payOrder.orderType == PayOrderTypes.MmeberUp) { Log.Debug(this.GetType().ToString(), "开始推荐返利 : " + orderNo); IRebateService.Rebate4(payOrder.Id); Log.Debug(this.GetType().ToString(), "返利推荐结束 : " + orderNo); } } } #endregion } } } } res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } catch (Exception ex) { if (!(ex is System.Threading.ThreadAbortException)) { res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单状态修改失败"); Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml() + ex); page.Response.Write(res.ToXml()); page.Response.End(); } } } }
/** * * 查询退款 * 提交退款申请后,通过该接口查询退款状态。退款有一定延时, * 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。 * out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个 * @param WxPayData inputObj 提交给查询退款API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData RefundQuery(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/refundquery"; //检测必填参数 if(!inputObj.IsSet("out_refund_no") && !inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id") && !inputObj.IsSet("refund_id")) { throw new WxPayException("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个!"); } inputObj.SetValue("appid",WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id",WxPayConfig.MCHID);//商户号 inputObj.SetValue("nonce_str",GenerateNonceStr());//随机字符串 inputObj.SetValue("sign",inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 Log.Debug("WxPayApi", "RefundQuery request : " + xml); string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API Log.Debug("WxPayApi", "RefundQuery response : " + response); var end = DateTime.Now; int timeCost = (int)((end-start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result; }
public static WxPayData UnifiedTransfer(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; //检测必填参数 if (!inputObj.IsSet("partner_trade_no")) { throw new WxPayException("缺少统一支付接口必填参数partner_trade_no!"); } else if (!inputObj.IsSet("openid")) { throw new WxPayException("缺少统一支付接口必填参数openid!"); } else if (!inputObj.IsSet("amount")) { throw new WxPayException("缺少统一支付接口必填参数amount!"); } else if (!inputObj.IsSet("desc")) { throw new WxPayException("缺少统一支付接口必填参数desc!"); } //关联参数 //if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid")) //{ // throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!"); //} //if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id")) //{ // throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!"); //} //异步通知url未设置,则使用配置文件中的url //if (!inputObj.IsSet("notify_url")) //{ // inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url //} inputObj.SetValue("mch_appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mchid", WxPayConfig.MCHID); //商户号 inputObj.SetValue("spbill_create_ip", WxPayConfig.IP); //终端ip inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 /* * NO_CHECK:不校验真实姓名 * FORCE_CHECK:强校验真实姓名(未实名认证的用户会校验失败,无法转账) * OPTION_CHECK:针对已实名认证的用户才校验真实姓名(未实名认证用户不校验,可以转账成功) */ inputObj.SetValue("check_name", "NO_CHECK");//校验用户姓名选项 //签名 inputObj.SetValue("sign", inputObj.MakeSign()); string xml = inputObj.ToXml(); var start = DateTime.Now; Log.Debug("WxPayApi", "UnifiedTransfer request : " + xml); string response = HttpService.Post(xml, url, true, timeOut); Log.Debug("WxPayApi", "UnifiedTransfer response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); //ReportCostTime(url, timeCost, result);//测速上报 return(result); }
/** * * 撤销订单API接口 * @param WxPayData inputObj 提交给撤销订单API接口的参数,out_trade_no和transaction_id必填一个 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回API调用结果,其他抛异常 */ public static WxPayData Reverse(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/secapi/pay/reverse"; //检测必填参数 if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) { throw new WxPayException("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!"); } inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串 inputObj.SetValue("sign", inputObj.MakeSign());//签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 Log.Debug("WxPayApi", "Reverse request : " + xml); string response = HttpService.Post(xml, url, true, timeOut); Log.Debug("WxPayApi", "Reverse response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result; }
/** * * 统一下单 * @param WxPaydata inputObj 提交给统一下单API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //检测必填参数 if (!inputObj.IsSet("out_trade_no")) { throw new WxPayException("缺少统一支付接口必填参数out_trade_no!"); } else if (!inputObj.IsSet("body")) { throw new WxPayException("缺少统一支付接口必填参数body!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("缺少统一支付接口必填参数total_fee!"); } else if (!inputObj.IsSet("trade_type")) { throw new WxPayException("缺少统一支付接口必填参数trade_type!"); } //关联参数 if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid")) { throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!"); } if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id")) { throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!"); } //异步通知url未设置,则使用配置文件中的url if (!inputObj.IsSet("notify_url")) { inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("spbill_create_ip", WxPayConfig.IP); //终端ip inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 //签名 inputObj.SetValue("sign", inputObj.MakeSign()); string xml = inputObj.ToXml(); var start = DateTime.Now; Log.Debug("WxPayApi", "UnfiedOrder request : " + xml); string response = HttpService.Post(xml, url, false, timeOut); Log.Debug("WxPayApi", "UnfiedOrder response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return(result); }
/** * * 统一下单 * @param WxPaydata inputObj 提交给统一下单API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //检测必填参数 if (!inputObj.IsSet("out_trade_no")) { throw new WxPayException("缺少统一支付接口必填参数out_trade_no!"); } else if (!inputObj.IsSet("body")) { throw new WxPayException("缺少统一支付接口必填参数body!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("缺少统一支付接口必填参数total_fee!"); } else if (!inputObj.IsSet("trade_type")) { throw new WxPayException("缺少统一支付接口必填参数trade_type!"); } //关联参数 if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid")) { throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!"); } if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id")) { throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!"); } //异步通知url未设置,则使用配置文件中的url if (!inputObj.IsSet("notify_url")) { inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url } inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);//终端ip inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串 //签名 inputObj.SetValue("sign", inputObj.MakeSign()); string xml = inputObj.ToXml(); var start = DateTime.Now; Log.Debug("WxPayApi", "UnfiedOrder request : " + xml); string response = HttpService.Post(xml, url, false, timeOut); Log.Debug("WxPayApi", "UnfiedOrder response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return result; }
/** * 刷卡支付完整业务流程逻辑 * @param body 商品描述 * @param total_fee 总金额 * @param auth_code 支付授权码 * @param outTradeNo 商户订单号 * @throws WxPayException * @return 刷卡支付结果 */ public static WxPayData Run(string body, string total_fee, string auth_code, string outTradeNo) { Log.Info("MicroPay", "Micropay is processing..."); WxPayData data = new WxPayData(); data.SetValue("auth_code", auth_code); //授权码 data.SetValue("body", body); //商品描述 data.SetValue("total_fee", int.Parse(total_fee)); //总金额 data.SetValue("out_trade_no", outTradeNo); //产生随机的商户订单号 WxPayData result = WxPayApi.Micropay(data, 10); //提交被扫支付,接收返回结果 //如果提交被扫支付接口调用失败,则抛异常 if (!result.IsSet("return_code") || result.GetValue("return_code").ToString() == "FAIL") { string returnMsg = result.IsSet("return_msg") ? result.GetValue("return_msg").ToString() : ""; Log.Error("MicroPay", "Micropay API interface call failure, result : " + result.ToXml()); throw new WxPayException("Micropay API interface call failure, return_msg : " + returnMsg); } //签名验证 result.CheckSign(); Log.Debug("MicroPay", "Micropay response check sign success"); //刷卡支付直接成功 if (result.GetValue("return_code").ToString() == "SUCCESS" && result.GetValue("result_code").ToString() == "SUCCESS") { Log.Debug("MicroPay", "Micropay business success, result : " + result.ToXml()); return(result); } /****************************************************************** * 剩下的都是接口调用成功,业务失败的情况 * ****************************************************************/ //1)业务结果明确失败 if (result.GetValue("err_code").ToString() != "USERPAYING" && result.GetValue("err_code").ToString() != "SYSTEMERROR") { Log.Error("MicroPay", "micropay API interface call success, business failure, result : " + result.ToXml()); return(result); } //2)不能确定是否失败,需查单 //用商户订单号去查单 string out_trade_no = data.GetValue("out_trade_no").ToString(); //确认支付是否成功,每隔一段时间查询一次订单,共查询10次 int queryTimes = 10;//查询次数计数器 while (queryTimes-- > 0) { int succResult = 0;//查询结果 WxPayData queryResult = Query(out_trade_no, out succResult); //如果需要继续查询,则等待2s后继续 if (succResult == 2) { Thread.Sleep(2000); continue; } //查询成功,返回订单查询接口返回的数据 else if (succResult == 1) { Log.Debug("MicroPay", "Mircopay success, return order query result : " + queryResult.ToXml()); return(queryResult); } //订单交易失败,直接返回刷卡支付接口返回的结果,失败原因会在err_code中描述 else { Log.Error("MicroPay", "Micropay failure, return micropay result : " + result.ToXml()); return(result); } } //确认失败,则撤销订单 Log.Error("MicroPay", "Micropay failure, Reverse order is processing..."); if (!Cancel(out_trade_no)) { Log.Error("MicroPay", "Reverse order failure"); throw new WxPayException("Reverse order failure!"); } return(result); }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查openid和product_id是否返回 if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "回调数据异常"); Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //调统一下单接口,获得下单结果 string openid = notifyData.GetValue("openid").ToString(); string product_id = notifyData.GetValue("product_id").ToString(); WxPayData unifiedOrderResult = new WxPayData(); try { unifiedOrderResult = UnifiedOrder(openid, product_id); } catch (Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台 { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //若下单失败,则立即返回结果给微信支付后台 if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //统一下单成功,则返回成功结果给微信支付后台 WxPayData data = new WxPayData(); data.SetValue("return_code", "SUCCESS"); data.SetValue("return_msg", "OK"); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("mch_id", WxPayConfig.MCHID); data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id")); data.SetValue("result_code", "SUCCESS"); data.SetValue("err_code_des", "OK"); data.SetValue("sign", data.MakeSign()); Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml()); page.Response.Write(data.ToXml()); page.Response.End(); }
/*** * 申请退款完整业务流程逻辑 * @param transaction_id 微信订单号(优先使用) * @param out_trade_no 商户订单号 * @param total_fee 订单总金额 * @param refund_fee 退款金额 * @return 退款结果(xml格式) */ public static string Run(string transaction_id, string out_trade_no, string total_fee, string refund_fee, int type) { try { Log.Info("Refund", "Refund is processing..."); WxPayData data = new WxPayData(); if (!string.IsNullOrEmpty(transaction_id))//微信订单号存在的条件下,则已微信订单号为准 { data.SetValue("transaction_id", transaction_id); } else//微信订单号不存在,才根据商户订单号去退款 { data.SetValue("out_trade_no", out_trade_no); } WxPayConfig wx = new WxPayConfig(type); data.SetValue("total_fee", int.Parse(total_fee)); //订单总金额 data.SetValue("refund_fee", int.Parse(refund_fee)); //退款金额 data.SetValue("out_refund_no", out_trade_no); //随机生成商户退款单号 data.SetValue("op_user_id", WxPayConfig.MCHID); //操作员,默认为商户号 WxPayData rst = WxPayApi.Refund(data); //提交退款申请给API,接收返回数据 Log.Info("Refund", "Refund process complete, result : " + rst.ToXml()); string text = rst.ToPrintStr(); #region 屏蔽代码 //XmlDocument xmlDocument = new XmlDocument(); //try //{ // xmlDocument.LoadXml(text); //} //catch (Exception ex) //{ // text = string.Format("微信获取信息错误doc.load:{0}", ex.Message) + text; // ErrorLog.Write(text); //} //string result = string.Empty; //try //{ // if (xmlDocument == null) // { // result = text; // return result; // } // XmlNode xmlNode = xmlDocument.SelectSingleNode("xml/return_code"); // if (xmlNode == null) // { // result = text; // return result; // } // if (!(xmlNode.InnerText == "SUCCESS")) // { // text = string.Format("微信获取信息失败:{0}", text); // ErrorLog.Write(text); // result = xmlNode.InnerText; // return result; // } // XmlNode xmlNode2 = xmlDocument.SelectSingleNode("xml/result_code"); // if (!(xmlNode2.InnerText == "SUCCESS")) // { // result = xmlNode2.InnerText; // xmlNode2 = xmlDocument.SelectSingleNode("xml/err_code_des"); // return result + ":" + xmlNode2.InnerText; // } //} //catch (Exception ex) //{ // text = string.Format("微信获取信息错误node.load:{0}", ex.Message) + text; // ErrorLog.Write(text); //} #endregion return(text); } catch (Exception ee) { return(ee.Message.ToString()); } }