/// <summary> /// 统一下单接口 /// </summary> /// <param name="request"></param> /// <param name="response"></param> public void CreateOrders(CreateOrder request, CreateOrderResponse response) { DateTime dt = DateTime.Now; string timeStart = string.Format("{0:yyyyMMddHHmmss}", dt); string timeExpire = string.Format("{0:yyyyMMddHHmmss}", dt.AddSeconds(300)); SortedDictionary <string, string> ht = new SortedDictionary <string, string> { { "appid", ConfigurationManager.AppSettings["APPID"] }, { "mch_id", ConfigurationManager.AppSettings["MCHID"] }, { "device_info", "WEB" }, { "nonce_str", RandomHelper.GenerateString(32) }, { "sign_type", "MD5" }, { "body", request.Body }, { "detail", request.Detail }, { "attach", request.Attach }, { "out_trade_no", request.OutTradeNo }, { "fee_type", "CNY" }, { "total_fee", "" + request.TotalFee }, { "spbill_create_ip", request.SpbillCreateIp }, { "time_start", timeStart }, { "time_expire", timeExpire }, { "goods_tag", request.GoodsTag }, { "notify_url", ConfigurationManager.AppSettings["NOTIFYURL"] }, { "trade_type", "JSAPI" }, { "openid", request.Openid }, { "product_id", request.ProductId } }; if (string.IsNullOrEmpty(request.LimitPay)) { if (request.LimitPay == "no_credit") { ht.Add("limit_pay", "no_credit"); } } string sign = Md5Helper.UserMd5(WxPayHelper.CreateSign(ht)); ht.Add("sign", sign); string postXml = WxPayHelper.CreateXmlRequest(ht); string wxResult = HttpRequestUtil.HttpPost(UrlUnifiedorder, postXml); Hashtable htt = XmlAndJsonToHash.XmlToHashTable(wxResult); wxResult = JsonHelper.ToJson(htt); CoResponse tr = JsonHelper.Deserialize <CoResponse>(wxResult); response.ResponseStatus.ErrorCode = tr.return_code; response.ResponseStatus.Message = tr.return_msg; if (tr.return_code == "SUCCESS" && tr.result_code == "SUCCESS") { response.PrepayId = tr.prepay_id; } else { response.ResponseStatus.ErrorCode = tr.err_code; response.ResponseStatus.Message = tr.err_code_des; } }
private string CreateQRCodeUrl() { Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("appid", helper.GetAppId); dic.Add("mch_id", helper.GetMch_Id); dic.Add("nonce_str", WpPCHelper.TenpayUtil.getNoncestr().ToLower());//TenpayUtil.getNoncestr() dic.Add("product_id", nID); dic.Add("time_stamp", WpPCHelper.TenpayUtil.getTimestamp()); #region sign=============================== Sign = helper.GetSign(dic); LogUtil.WriteLog("sign:" + Sign); dic.Add("sign", Sign); #endregion string urlce = WxPayHelper.FormatBizQueryParaMap(dic, false);//这里不要url编码 LogUtil.WriteLog("urlce:" + urlce); string url = string.Format(@"sign={0}&appid={1}&mch_id={2}&product_id={3}&time_stamp={4}&nonce_str={5}" , Sign, helper.GetAppId, helper.GetMch_Id, nID, WpPCHelper.TenpayUtil.getTimestamp(), WpPCHelper.TenpayUtil.getNoncestr().ToLower()); LogUtil.WriteLog("二维码地址生成" + url); return("weixin://wxpay/bizpayurl?" + urlce); /*------另一种方式--------*/ //var packageReqHandler = new RequestHandler(Context); ////初始化 //packageReqHandler.init(); ////设置package订单参数 具体参数列表请参考官方pdf文档,请勿随意设置 //packageReqHandler.setParameter("appid", PayConfig.AppId); //packageReqHandler.setParameter("mch_id", PayConfig.MchId); //packageReqHandler.setParameter("nonce_str", WeiPay.TenpayUtil.getNoncestr().ToLower()); //packageReqHandler.setParameter("product_id", nID); //packageReqHandler.setParameter("time_stamp", WeiPay.TenpayUtil.getTimestamp()); //#region sign=============================== //Sign = packageReqHandler.CreateMd5Sign("key", PayConfig.AppKey); //LogUtil.WriteLog("WeiPay 页面 sign:" + Sign); //packageReqHandler.setParameter("sign", Sign); //#endregion //string data = packageReqHandler.parseXML(); //LogUtil.WriteLog("WeiPay 页面 package(XML):" + data); //string url = string.Format(@"sign={0}&appid={1}&mch_id={2}&product_id={3}&time_stamp={4}&nonce_str={5}" // , Sign, PayConfig.AppId, PayConfig.MchId, nID, WeiPay.TenpayUtil.getTimestamp(), WeiPay.TenpayUtil.getNoncestr().ToLower()); //LogUtil.WriteLog("WeiPay 页面 package(XML):" + url); //return "weixin://wxpay/bizpayurl?" + url; }
/// <summary> /// 发货 /// </summary> /// <param name="paymentInfo"></param> /// <param name="orderEntity"></param> /// <returns></returns> public Dictionary<string, object> fahuomgr(Model.wx_payment_wxpay paymentInfo, Model.orders orderEntity) { BLL.wx_logs logBll = new BLL.wx_logs(); string funName = "发货"; logBll.AddLog(paymentInfo.wid.Value, "微支付", funName, "开始执行fahuomgr方法[otid:" + orderEntity.id + "]"); WxPayHelper wxPayHelper = new WxPayHelper(); wx_payment_wxpay payBll = new wx_payment_wxpay(); //先设置基本信息 string partnerId = paymentInfo.partnerId; //"1218574001"; string appId = paymentInfo.appId;// "wxa9b8e33e48ac5e0f"; string partnerKey = paymentInfo.partnerKey;// "huyuxianghuyuxianghuyuxiang12345"; //paysignkey(非appkey) string appKey = paymentInfo.paySignKey;// "nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp"; wxPayHelper.SetAppId(appId); wxPayHelper.SetAppKey(appKey); wxPayHelper.SetPartnerKey(partnerKey); wxPayHelper.SetSignType("sha1"); //设置请求package信息 WeiXinCRMComm wxComm = new WeiXinCRMComm(); string err=""; string access_token = wxComm.getAccessToken(paymentInfo.wid.Value, out err); string param = wxPayHelper.CreateFaHuoPackage(orderEntity.openid, orderEntity.trade_no, orderEntity.order_no); string url = "https://api.weixin.qq.com/pay/delivernotify?access_token=" + access_token; string ret = Utils.HttpPost(url, param); logBll.AddLog(paymentInfo.wid.Value, "微支付", funName, "ret=" + ret); Dictionary<string, object> dict = JsonToDictionary(ret); logBll.AddLog(paymentInfo.wid.Value, "微支付", funName, "[otid:" + orderEntity.id + "]发货成功"); //string errcode = dict["errcode"].ToString(); //string errmsg = dict["errmsg"].ToString(); //mxAuthFrame.BLL.wxOrderTmpBLL wot = new mxAuthFrame.BLL.wxOrderTmpBLL(); //ordertmp.fahuoCode = errcode; //ordertmp.fahuoMsg = errmsg; //wot.Update(ordertmp); //Dictionary<string, string> ret_d = new Dictionary<string, string>(); //ret_d.Add(errcode, errmsg); return dict; }
/// <summary> /// 页面加载 /// </summary> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { WxPayHelper wx = new WxPayHelper(); string returnMsg = "<xml> <return_code><![CDATA[{0}]]></return_code> <return_msg><![CDATA[{1}]]></return_msg> </xml>"; SortedDictionary <string, object> dic = wx.GetReturnData(); Log4Net.WriteInfoLog("收到微信App支付回调:" + new JavaScriptSerializer().Serialize(dic)); string sign = dic["sign"].ToString(); if (dic["return_code"].ToString() == "SUCCESS") { string signLocal = wx.MakeSign(dic, ApplicationSettings.Get("WXAPPKEY")); if (sign == signLocal) { decimal amount = Convert.ToDecimal(dic["total_fee"]) / 100M; if (dic["result_code"].ToString() == "SUCCESS") { OnLinePayOrder order = new OnLinePayOrder { OrderID = dic["out_trade_no"].ToString(), PayAddress = GameRequest.GetUserIP(), Amount = amount }; FacadeManage.aideTreasureFacade.FinishOnLineOrder(order); Response.Write(string.Format(returnMsg, "SUCCESS", "支付成功!")); } else { Response.Write(string.Format(returnMsg, "FAIL", "微信交易失败!")); } } else { Response.Write(string.Format(returnMsg, "FAIL", "签名错误!")); } } else { Response.Write(string.Format(returnMsg, "FAIL", "微信交易失败!")); } } }
/// <summary> /// 获取微信预支付信息包 /// </summary> /// <returns></returns> private static string GetWxPayPackage(OnLinePayOrder orderReturn, string paytype, string openid, string authority) { string domain = string.IsNullOrEmpty(AppConfig.FrontSiteDomain) ? authority : AppConfig.FrontSiteDomain; WxPayInfo wx = new WxPayInfo { AppID = ApplicationSettings.Get(paytype == "wx" ? "WXAPPID" : "WXNATIVEAPPID"), AppSecret = ApplicationSettings.Get(paytype == "wx" ? "WXAPPSECRET" : "WXNATIVESECRET"), // ReSharper disable once SpecifyACultureInStringConversionExplicitly Body = orderReturn.Amount.ToString(), Key = ApplicationSettings.Get(paytype == "wx" ? "WXAPPKEY" : "WXNATIVEKEY"), Mchid = ApplicationSettings.Get(paytype == "wx" ? "WXAPPMCHID" : "WXNATIVEMCHID"), NotifyUrl = "http://" + domain + "/Notify/" + (paytype == "wx" ? "WxApp.aspx" : "WxWeb.aspx"), OpenId = openid, OutTradeNo = orderReturn.OrderID, TotalFee = (orderReturn.Amount * 100).ToString("F0"), TradeType = paytype == "wx" ? "APP" : "JSAPI" }; WxPayHelper helper = new WxPayHelper(wx); return(helper.GetPrepayIDSign()); }
/// <summary> /// 微信支付:生成请求数据 /// </summary> /// <param name="openid">微信用户id</openid> /// <param name="ttFee">商品总价格</param> /// <param name="busiBody"></param> /// <returns></returns> protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no) { WxPayHelper wxPayHelper = new WxPayHelper(); BLL.wx_payment_wxpay wxPayBll = new BLL.wx_payment_wxpay(); Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid); //先设置基本信息 string partnerId = paymentInfo.partnerId;// "1218574001";// string appId = paymentInfo.appId;// "wxa9b8e33e48ac5e0f";// string partnerKey = paymentInfo.partnerKey;// "huyuxianghuyuxianghuyuxiang12345";// //paysignkey(非appkey) string appKey = paymentInfo.paySignKey; //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";// wxPayHelper.SetAppId(appId); wxPayHelper.SetAppKey(appKey); wxPayHelper.SetPartnerKey(partnerKey); wxPayHelper.SetSignType("SHA1"); //设置请求package信息 wxPayHelper.SetParameter("bank_type", "WX"); wxPayHelper.SetParameter("body", busiBody); wxPayHelper.SetParameter("attach",wid+"|"+busiBody); wxPayHelper.SetParameter("partner", partnerId); wxPayHelper.SetParameter("out_trade_no", out_trade_no); wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); wxPayHelper.SetParameter("fee_type", "1"); // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid); wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数 wxPayHelper.SetParameter("spbill_create_ip", MXRequest.GetIP()); wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); //---------有效期截至日期------ wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss")); wxPayHelper.SetParameter("input_charset", "UTF-8"); packageValue = wxPayHelper.CreateBizPackage(); }
public static void Main(String[] args) { try { WxPayHelper wxPayHelper = new WxPayHelper(); //先设置基本信息 wxPayHelper.SetAppId("wxf8b4f85f3a794e77"); wxPayHelper.SetAppKey("2Wozy2aksie1puXUBpWD8oZxiD1DfQuEaiC7KcRATv1Ino3mdopKaPGQQ7TtkNySuAmCaDCrw4xhPY5qKTBl7Fzm0RgR3c0WaVYIXZARsxzHV2x7iwPPzOz94dnwPWSn"); wxPayHelper.SetPartnerKey("8934e7d15453e97507ef794cf7b0519d"); wxPayHelper.SetSignType("sha1"); //设置请求package信息 wxPayHelper.SetParameter("bank_type", "WX"); wxPayHelper.SetParameter("body", "test"); wxPayHelper.SetParameter("partner", "1900000109"); wxPayHelper.SetParameter("out_trade_no", CommonUtil.CreateNoncestr()); wxPayHelper.SetParameter("total_fee", "1"); wxPayHelper.SetParameter("fee_type", "1"); wxPayHelper.SetParameter("notify_url", "htttp://www.baidu.com"); wxPayHelper.SetParameter("spbill_create_ip", "127.0.0.1"); wxPayHelper.SetParameter("input_charset", "GBK"); System.Console.Out.WriteLine("生成app支付package:"); System.Console.Out.WriteLine(wxPayHelper.CreateAppPackage("test")); System.Console.Out.WriteLine("生成jsapi支付package:"); System.Console.Out.WriteLine(wxPayHelper.CreateBizPackage()); System.Console.Out.WriteLine("生成原生支付url:"); System.Console.Out.WriteLine(wxPayHelper.CreateNativeUrl("abc")); System.Console.Out.WriteLine("生成原生支付package:"); System.Console.Out.WriteLine(wxPayHelper.CreateNativePackage("0", "ok")); } catch (Exception e) { System.Console.Out.WriteLine(e.Message); } }
/// <summary> /// 微信支付:生成请求数据 /// </summary> /// <param name="openid">微信用户id</openid> /// <param name="ttFee">商品总价格</param> /// <param name="busiBody"></param> /// <returns></returns> protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no) { WxPayHelper wxPayHelper = new WxPayHelper(); BLL.wx_payment_wxpay wxPayBll = new BLL.wx_payment_wxpay(); Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid); //先设置基本信息 string partnerId = paymentInfo.partnerId; // "1218574001";// string appId = paymentInfo.appId; // "wxa9b8e33e48ac5e0f";// string partnerKey = paymentInfo.partnerKey; // "huyuxianghuyuxianghuyuxiang12345";// //paysignkey(非appkey) string appKey = paymentInfo.paySignKey; //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";// wxPayHelper.SetAppId(appId); wxPayHelper.SetAppKey(appKey); wxPayHelper.SetPartnerKey(partnerKey); wxPayHelper.SetSignType("SHA1"); //设置请求package信息 wxPayHelper.SetParameter("bank_type", "WX"); wxPayHelper.SetParameter("body", busiBody); wxPayHelper.SetParameter("attach", wid + "|" + busiBody); wxPayHelper.SetParameter("partner", partnerId); wxPayHelper.SetParameter("out_trade_no", out_trade_no); wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); wxPayHelper.SetParameter("fee_type", "1"); // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid); wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数 wxPayHelper.SetParameter("spbill_create_ip", MXRequest.GetIP()); wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); //---------有效期截至日期------ wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss")); wxPayHelper.SetParameter("input_charset", "UTF-8"); packageValue = wxPayHelper.CreateBizPackage(); }
/// <summary> /// 微信支付:生成请求数据 /// </summary> /// <param name="openid">微信用户id</openid> /// <param name="ttFee">商品总价格</param> /// <param name="busiBody"></param> /// <returns></returns> protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no) { WxPayHelper wxPayHelper = new WxPayHelper(); //BLL.wx_payment_wxpay wxPayBll = new BLL.wx_payment_wxpay(); //Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid); //先设置基本信息 string partnerId = "1220201501"; // "1220201501";// string appId = "wxe5d8d2c5589f5ffb"; // "wxe5d8d2c5589f5ffb";// string partnerKey = "19ace89a7acd6e14ac3c66b2852f14d6"; // "19ace89a7acd6e14ac3c66b2852f14d6";// //paysignkey(非appkey) string appKey = "YOFbXGzn0i8ZH8UlfqH7D7LpHHCXd4CxNqZgLffI8v58GSpxntqnVOx5zJFrsM2efT6XH89Nr0WDpfZjcfYCHD05uteWUfHq6BG8zuyTAe4uQ39yKOKqwYwl6yhgKueb"; //"YOFbXGzn0i8ZH8UlfqH7D7LpHHCXd4CxNqZgLffI8v58GSpxntqnVOx5zJFrsM2efT6XH89Nr0WDpfZjcfYCHD05uteWUfHq6BG8zuyTAe4uQ39yKOKqwYwl6yhgKueb";// wxPayHelper.SetAppId(appId); wxPayHelper.SetAppKey(appKey); wxPayHelper.SetPartnerKey(partnerKey); wxPayHelper.SetSignType("SHA1"); //设置请求package信息 wxPayHelper.SetParameter("bank_type", "WX"); wxPayHelper.SetParameter("body", busiBody); wxPayHelper.SetParameter("attach", wid + "|" + busiBody); wxPayHelper.SetParameter("partner", partnerId); wxPayHelper.SetParameter("out_trade_no", out_trade_no); wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); wxPayHelper.SetParameter("fee_type", "1"); // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid); wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数 wxPayHelper.SetParameter("spbill_create_ip", DTRequest.GetIP()); wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); //---------有效期截至日期------ wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss")); wxPayHelper.SetParameter("input_charset", "UTF-8"); packageValue = wxPayHelper.CreateBizPackage(); }
//public static TenPayInfo TenPayInfo //{ // get // { // if (_tenPayInfo == null) // { // _tenPayInfo = // TenPayInfoCollection.Data[System.Configuration.ConfigurationManager.AppSettings["WeixinPay_PartnerId"]]; // } // return _tenPayInfo; // } //} /// <summary> /// 微信支付:生成请求数据 /// </summary> /// <param name="openid">微信用户id</openid> /// <param name="ttFee">商品总价格</param> /// <param name="busiBody"></param> /// <returns></returns> protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no) { WxPayHelper wxPayHelper = new WxPayHelper(); BLL.wx_payment_wxpay wxPayBll = new BLL.wx_payment_wxpay(); Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid); // //先设置基本信息 // string partnerId = paymentInfo.partnerId;// "1218574001";// // string appId = paymentInfo.appId;// "wxa9b8e33e48ac5e0f";// // string partnerKey = paymentInfo.partnerKey;// "huyuxianghuyuxianghuyuxiang12345";// // //paysignkey(非appkey) // string appKey = paymentInfo.paySignKey; //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";// // wxPayHelper.SetAppId(appId); // wxPayHelper.SetAppKey(appKey); // wxPayHelper.SetPartnerKey(partnerKey); // wxPayHelper.SetSignType("SHA1"); // //设置请求package信息 // wxPayHelper.SetParameter("bank_type", "WX"); // wxPayHelper.SetParameter("body", busiBody); // wxPayHelper.SetParameter("attach",wid+"|"+busiBody); // wxPayHelper.SetParameter("partner", partnerId); // wxPayHelper.SetParameter("out_trade_no", out_trade_no); // wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); // wxPayHelper.SetParameter("fee_type", "1"); //// wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid); // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数 // wxPayHelper.SetParameter("spbill_create_ip", MXRequest.GetIP()); // wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); // //---------有效期截至日期------ // wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss")); // wxPayHelper.SetParameter("input_charset", "UTF-8"); // packageValue = wxPayHelper.CreateBizPackage(); /////////////////////////////////////////////////////////////////////////// //通过,用code换取access_token //var openIdResult = OAuthApi.GetAccessToken(paymentInfo.appId, "a891edd957f2aede546f9256096bf95a", code); //if (openIdResult.errcode != ReturnCode.请求成功) //{ // return Content("错误:" + openIdResult.errmsg); //} string timeStamp = ""; string nonceStr = ""; string paySign = ""; string sp_billno = Request["order_no"]; //当前时间 yyyyMMdd string date = DateTime.Now.ToString("yyyyMMdd"); if (null == sp_billno) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28); } else { sp_billno = Request["order_no"].ToString(); } //创建支付应答对象 Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null); //初始化 packageReqHandler.Init(); timeStamp = TenPayV3Util.GetTimestamp(); nonceStr = TenPayV3Util.GetNoncestr(); //设置package订单参数 packageReqHandler.SetParameter("appid", paymentInfo.appId); //公众账号ID packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", "aaa"); //商品信息 packageReqHandler.SetParameter("out_trade_no", sp_billno); //商家订单号 packageReqHandler.SetParameter("total_fee", "100"); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", "http://ddd.com"); //接收财付通通知的URL packageReqHandler.SetParameter("trade_type", Senparc.Weixin.MP.TenPayV3Type.JSAPI.ToString()); //交易类型 packageReqHandler.SetParameter("openid", "oFo2Hjq6_yMhyz6cQ2MZtmxODOVU"); //用户的openId string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.partnerKey); packageReqHandler.SetParameter("sign", sign); //签名 string data = packageReqHandler.ParseXML(); var result = TenPayV3.Unifiedorder(data); var res = XDocument.Parse(result); string prepayId = res.Element("xml").Element("prepay_id").Value; //设置支付参数 Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null); paySignReqHandler.SetParameter("appId", paymentInfo.appId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId)); paySignReqHandler.SetParameter("signType", "MD5"); paySign = paySignReqHandler.CreateMd5Sign("key", paymentInfo.partnerKey); payaddid = paymentInfo.appId; paytimeStamp = timeStamp; paynonceStr = nonceStr; paypackageValue = packageValue; paypaySign = paySign; }
public async Task <string> WxPayNotify() { var logger = _loggerFactory.CreateLogger <NotifyController>(); try { var wxPayConfig = _orderService.GetWxPayConfig(); WxPayData notifyData = await WxPayApi.GetNotifyData(wxPayConfig, HttpContext.Request.Body); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); logger.LogError("The Pay result is error : " + res.ToXml()); return(res.ToXml()); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 if (!WxPayHelper.QueryOrder(wxPayConfig, transaction_id)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); logger.LogError("Order query failure : " + res.ToXml()); return(res.ToXml()); } //查询订单成功 else { var result_code = notifyData.GetValue("result_code").ToString(); var total_fee = int.Parse(notifyData.GetValue("total_fee").ToString()); var out_trade_no = notifyData.GetValue("out_trade_no").ToString(); var time_end = notifyData.GetValue("time_end").ToString(); WxPayData res = new WxPayData(); //处理已支付 var order = _orderService.GetPayOrder(out_trade_no); if (order == null || order.PayStatus == 2) { res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); return(res.ToXml()); } ////设置成功或失败 var status = result_code == "SUCCESS" ? 2 : 3; if (status == 1 && total_fee != (int)(order.Amount * 100)) { res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单金额不正确"); logger.LogError("Order query failure[订单金额不正确] : " + res.ToXml()); return(res.ToXml()); } _orderService.SetPay(order.Id, status, DateTime.ParseExact(time_end, "yyyyMMddHHmmss", CultureInfo.CurrentCulture)); //成功后根据订单类型处理不同的逻辑 _orderService.DealPayOK(order); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); logger.LogInformation("order query success : " + res.ToXml()); return(res.ToXml()); } } catch (Exception exp) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", exp.Message); logger.LogError("order query success : " + res.ToXml()); return(res.ToXml()); } }