/// <summary> /// H5支付预付单 /// </summary> /// <param name="clientId">客户端ID</param> /// <param name="title">商品标题</param> /// <param name="totalAmount">支付金额(单位分)</param> /// <param name="attach">附加数据</param> /// <param name="orderId">订单id</param> /// <param name="openId">用户openid</param> /// <param name="clientIp">客户端ip(微信安全校验)</param> /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param> /// <param name="redirect_url">前端跳转地址</param> /// <returns></returns> public async Task <PrePayResult <H5PayResult> > BuildH5(string appId, string mchId, string mchKey, string title, int totalAmount, string attach, string orderId, string localTradeNo, string clientIp, string notifyUrl, string redirect_url, TimeSpan?expire = null) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException("支付标题不能为空", nameof(title)); } if (string.IsNullOrWhiteSpace(orderId)) { throw new ArgumentException("订单id不能为空", nameof(orderId)); } if (totalAmount < 1) { throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount)); } string nonceStr = TenPayV3Util.GetNoncestr(); // 微信支付统一订单 api调用,生成预付单 var requestData = new TenPayV3UnifiedorderRequestData( appId, mchId, title, localTradeNo, totalAmount, clientIp, notifyUrl, TenPayV3Type.MWEB, null, mchKey, nonceStr, attach: attach, productId: orderId, timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1)) ); var result = await TenPayV3.UnifiedorderAsync(requestData); Logger.LogInformation($"MWEB支付预付单结果:{result.ResultXml}"); if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess()) { throw new Exception( $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}"); } string mWebUrl = result.mweb_url; if (redirect_url.IsNullOrWhiteSpace()) { if (!HttpUtility.UrlDecode(redirect_url).IsMatch(Consts.Regexs.Url)) { throw new ArgumentException("跳转参数错误", nameof(redirect_url)); } mWebUrl += string.Format("&redirect_url={0}", redirect_url); } return(new PrePayResult <H5PayResult> { Result = new H5PayResult { MwebUrl = mWebUrl }, LocalTradeNo = localTradeNo, UnifiedorderResult = result }); }
public ActionResult JsApi(int productId, int hc) { try { //获取订单信息 dynamic job = new OrderService().GetOrderByOrderID(productId); if (job == null) { return(Content("商品信息不存在,或非法进入!1002")); } //var openId = User.Identity.Name; var openId = (string)Session["OpenId"]; string sp_billno = job[0].ChannelOrderID; var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); string body = job[0].PayInfo; int price = Convert.ToInt32(job[0].PayMoney * 100); price = 1; #if DEBUG price = 1; #else Console.WriteLine("Release:222222222222"); #endif string productInfo = job[0].ChannelOrderID.ToString(); string attach = TenPayV3Info.AppId + "," + openId + "," + productInfo; var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr, null, null, null, null, attach); var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); var package = string.Format("prepay_id={0}", result.prepay_id); ViewData["product"] = job; ViewData["appId"] = TenPayV3Info.AppId; ViewData["timeStamp"] = timeStamp; ViewData["nonceStr"] = nonceStr; ViewData["package"] = package; ViewData["paySign"] = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key); //临时记录订单信息,留给退款申请接口测试使用 Session["BillNo"] = sp_billno; Session["BillFee"] = price; return(View()); } catch (Exception ex) { var msg = ex.Message; msg += "<br>" + ex.StackTrace; msg += "<br>==Source==<br>" + ex.Source; if (ex.InnerException != null) { msg += "<br>===InnerException===<br>" + ex.InnerException.Message; } return(Content(msg)); } }
public HttpResponseMessage CreatePayment(string orderCode) { LogHelper.Payment(orderCode, "准备请求微信支付接口..."); var orderEntity = _repositoryFactory.IOrders.Single(x => x.OrderCode == orderCode); if (orderEntity == null) { LogHelper.Payment(orderCode, "订单不存在"); return(ApiResponse(ResultStatus.ParamError, "订单不存在")); } if (orderEntity.OrderStatus != (int)EnumHepler.OrderStatus.Created || orderEntity.PayStatus != (int)EnumHepler.OrderPayStatus.Unpay) { LogHelper.Payment(orderCode, "订单非待支付状态"); return(ApiResponse(ResultStatus.ParamError, "订单非待支付状态")); } TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, notifyUrl, notifyUrl); TenPayV3Info.TenPayV3Notify = notifyUrl; //创建支付应答对象 //RequestHandler packageReqHandler = new RequestHandler(null); var sp_billno = DateTime.Today.ToString("yyMMdd") + TenPayV3Util.BuildDailyRandomStr(4);//最多32位 var nonceStr = TenPayV3Util.GetNoncestr(); string clientIp = CommonTools.GetIpAddress(); //创建请求统一订单接口参数 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "订单支付", orderCode, (int)(orderEntity.ActualPrice * 100), clientIp, TenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, orderEntity.OpenId, TenPayV3Info.Key, nonceStr); //返回给微信的请求 //RequestHandler res = new RequestHandler(null); try { //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); LogHelper.Payment(orderCode, $"微信支付接口返回:{JsonConvert.SerializeObject(result)}"); if (result != null && result.return_code == "SUCCESS") { //return_code是通信标识,非交易标识,交易是否成功需要查看result_code来判断 if (result.result_code == "SUCCESS") { LogHelper.Payment(orderCode, $"请求微信支付成功,预支付单号:{result.prepay_id}"); string rtimeStamp = CommonTools.GetTimeStamp(); //string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key); string paySign = SecurityHelper.MD5($"appId={TenPayV3Info.AppId}&nonceStr={nonceStr}&package=prepay_id={result.prepay_id}&signType=MD5&timeStamp={rtimeStamp}&key={TenPayV3Info.Key}").ToUpper(); //返回前端唤起微信支付收银台的参数 var detail = new { timeStamp = rtimeStamp, nonceStr = nonceStr, package = $"prepay_id={result.prepay_id}", signType = "MD5", paySign = paySign }; return(ApiResponse(ResultStatus.Success, "下单成功", detail)); } else { LogHelper.Payment(orderCode, $"请求微信支付失败,err_code:{result.err_code},err_code_des:{result.err_code_des}"); } } return(ApiResponse(ResultStatus.Failed, result.return_msg)); } catch (Exception ex) { //res.SetParameter("return_code", "FAIL"); //res.SetParameter("return_msg", "统一下单失败"); LogHelper.Payment(orderCode, $"创建微信支付异常:{ex.Message}"); LogHelper.Exception(ex); return(ApiResponse(ResultStatus.Failed, "创建微信支付请求失败,请联系管理员!")); } }
public ActionResult JsPay(string code, string state) { try { Logger.LogDebug("进来啦"); var openIdResult = OAuthApi.GetAccessToken(this.weChatOptions.AppId, this.weChatOptions.AppSecret, code); if (openIdResult.errcode != Senparc.Weixin.ReturnCode.请求成功) { throw new Exception($"微信支付申请失败,Erro:{openIdResult.errmsg}"); } Logger.LogDebug("获取AccessToken成功"); if (this.memoryCache.TryGetValue <WeChatPayRequest>(state, out WeChatPayRequest request)) { Logger.LogDebug(Newtonsoft.Json.JsonConvert.SerializeObject(request)); } else { Logger.LogDebug($"未找到对应的付款请求,state:{state}"); } var array = state.Split('|'); var bcTradeNo = array[0]; var money = decimal.Parse(array[1]); var SuccessUrl = array[2].ToString(); //成功跳转地址 var FailedUrl = array[3].ToString(); //失败跳转地址 var notifyUrl = "https://bcl.baocailang.com:8995/api/Payment/WeChatPayNotify"; //回调地址 var nonceStr = TenPayUtil.GetNoncestr(); var timeStamp = TenPayUtil.GetTimestamp(); string billBody = "商城--订单支付"; var xmlDataInfo = new TenPayV3UnifiedorderRequestData( this.weChatOptions.AppId, this.weChatOptions.MchId, billBody, request.PaymentId, (int)(request.TotalFee * 100), "192.168.2.1", notifyUrl, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openIdResult.openid, this.weChatOptions.ApiKey, nonceStr ); Logger.LogDebug($"申请支付结果:{0}", Newtonsoft.Json.JsonConvert.SerializeObject(xmlDataInfo)); var result = TenPayV3.Unifiedorder(xmlDataInfo); Logger.LogDebug($"申请JsPay支付返回code:{result.result_code}"); Logger.LogDebug($"申请JsPay支付返回:{result.ResultXml}"); Logger.LogDebug($"申请JsPay支付返回结果:{result.return_msg}"); var package = string.Format("prepay_id={0}", result.prepay_id); Logger.LogDebug($"Package={package}"); var jsPayParam = new WeChatPayParameter { AppId = result.appid, MchId = result.mch_id, NonceStr = result.nonce_str, PaySign = TenPayV3.GetJsPaySign(this.weChatOptions.AppId, timeStamp, nonceStr, package, this.weChatOptions.ApiKey), SuccessUrl = request.SuccessUrl, FailedUrl = request.FailedUrl, Package = package, TimeStamp = timeStamp }; return(View(jsPayParam)); } catch (Exception ex) { Logger.LogDebug("启动微信支付失败--{0}", ex.Message); throw new Exception(ex.Message); } }
public ActionResult JsApi(int productId, int hc) { try { //获取产品信息 var products = ProductModel.GetFakeProductList(); var product = products.FirstOrDefault(z => z.Id == productId); if (product == null || product.GetHashCode() != hc) { return(Content("商品信息不存在,或非法进入!1002")); } //var openId = User.Identity.Name; var openId = (string)Session["OpenId"]; string sp_billno = Request["order_no"]; if (string.IsNullOrEmpty(sp_billno)) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); } else { sp_billno = Request["order_no"]; } var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = product == null ? "test" : product.Name; var price = product == null ? 100 : (int)product.Price * 100; var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); var package = string.Format("prepay_id={0}", result.prepay_id); ViewData["product"] = product; ViewData["appId"] = TenPayV3Info.AppId; ViewData["timeStamp"] = timeStamp; ViewData["nonceStr"] = nonceStr; ViewData["package"] = package; ViewData["paySign"] = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key); //临时记录订单信息,留给退款申请接口测试使用 Session["BillNo"] = sp_billno; Session["BillFee"] = price; return(View()); } catch (Exception ex) { var msg = ex.Message; msg += "<br>" + ex.StackTrace; msg += "<br>==Source==<br>" + ex.Source; if (ex.InnerException != null) { msg += "<br>===InnerException===<br>" + ex.InnerException.Message; } return(Content(msg)); } }
public async Task <IActionResult> Unifiedorder(UnifiedorderModel unifiedorder) { string appid = TenPyConfigRead.AppId; string scret = TenPyConfigRead.AppSecret; DateTimeOffset?timestart = null; DateTime? timeexpire = null; string feetype = "CNY"; // var result = await WxLogin.SendCodeForOpenId(appid, scret, code); // WxLoginModel loginModel= JsonSerializer.Deserialize<WxLoginModel>(result); if (string.IsNullOrWhiteSpace(unifiedorder.NotifyUrl)) { unifiedorder.NotifyUrl = TenPyConfigRead.TenPayV3_WxOpenNotify; } if (string.IsNullOrWhiteSpace(unifiedorder.NonceStr)) { unifiedorder.NonceStr = TenPayV3Util.GetNoncestr(); } if (!string.IsNullOrWhiteSpace(unifiedorder.TimeStart)) { timestart = DateTimeOffset.Parse(unifiedorder.TimeStart); } if (!string.IsNullOrWhiteSpace(unifiedorder.TimeExpire)) { timeexpire = DateTime.Parse(unifiedorder.TimeExpire); } if (!string.IsNullOrWhiteSpace(unifiedorder.FeeType)) { feetype = unifiedorder.FeeType; } var xmlDataInfo = new TenPayV3UnifiedorderRequestData(appId: TenPyConfigRead.AppId, mchId: TenPyConfigRead.MchId, body: unifiedorder.Body, outTradeNo: unifiedorder.OutTradeNo, totalFee: unifiedorder.TotalFee, spbillCreateIp: unifiedorder.SpbillCreateIP, notifyUrl: unifiedorder.NotifyUrl, tradeType: TenPayV3Type.JSAPI, openid: unifiedorder.OpenId, key: TenPyConfigRead.Key, nonceStr: unifiedorder.NonceStr, deviceInfo: unifiedorder.DeviceInfo, timeStart: timestart, timeExpire: timeexpire, detail: unifiedorder.Detail, attach: unifiedorder.Attach, feeType: feetype, goodsTag: unifiedorder.GoodsTag, productId: unifiedorder.ProductId, limitPay: unifiedorder.LimitPay); var result = await TenPayV3.UnifiedorderAsync(xmlDataInfo);//调用统一订单接口 var log = _logger.CreateLogger("统一下单"); if (result.return_code == "FAIL") { log.LogError($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo} 通讯标记(return_code):{result.return_code} {result.return_msg}"); } if (result.result_code == "FAIL") { log.LogError($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo} 业务结果(result_code):{result.result_code}\n{result.err_code}:{result.err_code_des}"); } else if (result.result_code == "SUCCESS") { log.LogInformation($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo} 业务结果(result_code):{result.result_code}"); } var timeStamp = TenPayV3Util.GetTimestamp(); var package = string.Format("prepay_id={0}", result.prepay_id); var paysign = TenPayV3.GetJsPaySign(TenPyConfigRead.AppId, timeStamp, unifiedorder.NonceStr, package, TenPyConfigRead.Key); // return Ok(new { timeStamp, nonceStr, package, paysign }); return(Ok(new { client = new { timeStamp, unifiedorder.NonceStr, package, paysign, sign = "MD5" }, respond = result, request = unifiedorder })); }
/// <summary> /// 原生支付 模式二 /// 根据统一订单返回的code_url生成支付二维码。该模式链接较短,生成的二维码打印到结账小票上的识别率较高。 /// 注意:code_url有效期为2小时,过期后扫码不能再发起支付 /// </summary> /// <returns></returns> public ActionResult NativeByCodeUrl() { //创建支付应答对象 //RequestHandler packageReqHandler = new RequestHandler(null); var sp_billno = SystemTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26); var nonceStr = TenPayV3Util.GetNoncestr(); //商品Id,用户自行定义 string productId = SystemTime.Now.ToString("yyyyMMddHHmmss"); //创建请求统一订单接口参数 //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId); //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId); //packageReqHandler.SetParameter("nonce_str", nonceStr); //packageReqHandler.SetParameter("body", "test"); //packageReqHandler.SetParameter("out_trade_no", sp_billno); //packageReqHandler.SetParameter("total_fee", "1"); //packageReqHandler.SetParameter("spbill_create_ip", HttpContext.UserHostAddress()?.ToString()); //packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify); //packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString()); //packageReqHandler.SetParameter("product_id", productId); //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); //packageReqHandler.SetParameter("sign", sign); //string data = packageReqHandler.ParseXML(); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "test", sp_billno, 1, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.NATIVE, null, TenPayV3Info.Key, nonceStr, productId: productId); //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); //var unifiedorderRes = XDocument.Parse(result); //string codeUrl = unifiedorderRes.Element("xml").Element("code_url").Value; string codeUrl = result.code_url; BitMatrix bitMatrix; bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 600, 600); var bw = new ZXing.BarcodeWriterPixelData(); var pixelData = bw.Write(bitMatrix); using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) { using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return(File(ms, "image/png")); } } }
public ReJson DoPayOrder(string ordernum, string random = "", string timeStamp = "", string signature = "") { //获取订单 Order entity = Order.Find(Order._.OrderNum == ordernum); if (entity == null) { //reJson.code = 40000; //reJson.message = "系统找不到本订单!"; //return reJson; return(new ReJson(40000, "系统找不到本订单!")); } //判断订单状态 if (entity.OrderStatus == Utils.OrdersState[3]) { //reJson.code = 40000; //reJson.message = "已完成订单不允许支付!"; //return reJson; return(new ReJson(40000, "已完成订单不允许支付!")); } if (entity.PaymentStatus != Utils.PaymentState[0]) { //reJson.code = 40000; //reJson.message = "当前订单支付状态不允许支付!"; //return reJson; return(new ReJson(40000, "当前订单支付状态不允许支付!")); } //获取用户并判断是否是已经注册用户 Member my = Member.FindById(entity.UId); if (my == null || string.IsNullOrEmpty(my.WeixinAppOpenId)) { //reJson.code = 40000; //reJson.message = "用户状态错误,无法使用本功能!"; //return reJson; return(new ReJson(40000, "用户状态错误,无法使用本功能!")); } //开始生成支付订单 OnlinePayOrder model = new OnlinePayOrder(); model.OrderId = entity.Id; model.OrderNum = entity.OrderNum; model.PayId = 1; model.PaymentNotes = "微信支付"; model.PaymentStatus = Utils.PaymentState[0]; model.PayOrderNum = Utils.GetOrderNum();//在线支付订单的订单号 model.PayType = "微信支付"; model.TotalPrice = entity.TotalPay; model.TotalQty = entity.TotalQty; model.UId = entity.UId; model.IP = Utils.GetIP(); model.IsOK = 0; model.AddTime = DateTime.Now; model.Insert(); //写入日志 OrderLog log = new OrderLog(); log.AddTime = DateTime.Now; log.OrderId = entity.Id; log.OrderNum = entity.OrderNum; log.UId = entity.UId; log.Actions = "用户使用微信支付;支付订单号:" + model.PayOrderNum; log.Insert(); Core.Config cfg = Core.Config.GetSystemConfig(); string appId = cfg.WXAppId; // ConfigurationManager.AppSettings["WeixinAppId"]; string appSecrect = cfg.WXAppSecret; // ConfigurationManager.AppSettings["WeixinAppSecrect"]; string wxmchId = cfg.MCHId; // ConfigurationManager.AppSettings["WeixinMCHId"]; string wxmchKey = cfg.MCHKey; // ConfigurationManager.AppSettings["WeixinMCHKey"]; TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, Utils.GetServerUrl() + "/wxpayment/notify", Utils.GetServerUrl() + "/wxpayment/notify"); TenPayV3Info.TenPayV3Notify = Utils.GetServerUrl() + "/wxpayment/notify"; XTrace.WriteLine("微信支付异步通知地址:" + TenPayV3Info.TenPayV3Notify); //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(null); var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26);//最多32位 var nonceStr = TenPayV3Util.GetNoncestr(); string rtimeStamp = Utils.GetTimeStamp(); //创建请求统一订单接口参数 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, entity.Title, model.PayOrderNum, (int)(entity.TotalPay * 100), Utils.GetIP(), TenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, my.WeixinAppOpenId, TenPayV3Info.Key, nonceStr); //返回给微信的请求 RequestHandler res = new RequestHandler(null); try { //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); XTrace.WriteLine("微信支付统一下单返回:" + JsonConvert.SerializeObject(result)); if (result.return_code == "FAIL") { //reJson.code = 40005; //reJson.message = result.return_msg; //return reJson; return(new ReJson(40005, result.return_msg)); } string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key); //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3 //paySign = MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111) string paySign = Utils.MD5($"appId={TenPayV3Info.AppId}&nonceStr={nonceStr}&package=prepay_id={result.prepay_id}&signType=MD5&timeStamp={rtimeStamp}&key={TenPayV3Info.Key}").ToUpper(); string package = $"prepay_id={result.prepay_id}"; dynamic detail = new { timeStamp = rtimeStamp, nonceStr = nonceStr, package = package, signType = "MD5", paySign = paySign }; //reJson.code = 0; //reJson.message = "下单成功!"; //reJson.detail = detail; //return reJson; return(new ReJson(40000, "下单成功!", detail)); } catch (Exception ex) { res.SetParameter("return_code", "FAIL"); res.SetParameter("return_msg", "统一下单失败"); XTrace.WriteLine($"统一下单失败:{ex.Message}"); //reJson.code = 40005; //reJson.message = "统一下单失败,请联系管理员!"; return(new ReJson(40005, "统一下单失败,请联系管理员!")); } }
public async Task <ApiResult <WeixinJsPaySignature> > Pay([FromBody] PayModelInput model, CancellationToken cancelToken) { /* * 接口根据订单id和小程序Code * 获取支付调起参数 */ if (string.IsNullOrWhiteSpace(model.Id)) { throw new NotImplementedException("订单Id信息为空!"); } //查询订单 var data = await _orderRepository.GetIncludeAsync(model.Id, cancelToken); ApiResult <WeixinJsPaySignature> apiResult = new ApiResult <WeixinJsPaySignature>(); _ = new ApiResult(); string timeStamp = TenPayV3Util.GetTimestamp(); AppLogger.Debug(JsonConvert.SerializeObject("1" + timeStamp), JsonConvert.SerializeObject(timeStamp)); string nonceStr = TenPayV3Util.GetNoncestr(); AppLogger.Debug(JsonConvert.SerializeObject("2" + nonceStr), JsonConvert.SerializeObject(nonceStr)); string PayV3_TenpayNotify = ConfigurationManager.AppSettings["PayV3_TenpayNotify"]; TenPayV3Info tenPayV3Info = new TenPayV3Info(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, PayV3_MchId, PayV3_Key, string.Empty, string.Empty, PayV3_TenpayNotify, string.Empty); AppLogger.Debug(JsonConvert.SerializeObject(tenPayV3Info), JsonConvert.SerializeObject(tenPayV3Info)); var openIdResult = SnsApi.JsCode2Json(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, model.Code); AppLogger.Debug(JsonConvert.SerializeObject(openIdResult), JsonConvert.SerializeObject(openIdResult)); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(tenPayV3Info.AppId, tenPayV3Info.MchId, "呙呙社区购物", data.Number, Convert.ToInt32(data.PaymentPrice * 100), GetClientIpAddress(Request), tenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openIdResult.openid, tenPayV3Info.Key, nonceStr, attach: data.Id.ToString()); AppLogger.Debug(DateTime.Now.ToString("yyyyMMddHHmmss") + "****TenPayV3UnifiedorderRequestData对象" + JsonConvert.SerializeObject(xmlDataInfo), "****TenPayV3UnifiedorderRequestData对象" + JsonConvert.SerializeObject(xmlDataInfo)); var resultPay = await TenPayV3.UnifiedorderAsync(xmlDataInfo); AppLogger.Debug("****TenPayV3.Unifiedorder返回对象" + JsonConvert.SerializeObject(resultPay), "****TenPayV3.Unifiedorder返回对象" + JsonConvert.SerializeObject(resultPay)); if (resultPay.return_code.ToUpper() == "SUCCESS") { if (resultPay.result_code.ToUpper() == "SUCCESS") { //设置支付参数 RequestHandler paySignReqHandler = new RequestHandler(null); paySignReqHandler.SetParameter("appId", tenPayV3Info.AppId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", resultPay.prepay_id)); paySignReqHandler.SetParameter("signType", "MD5"); paySignReqHandler.SetParameter("nonceStr", nonceStr); string paySign = paySignReqHandler.CreateMd5Sign("key", tenPayV3Info.Key); var jsmodel = new WeixinJsPaySignature { AppId = tenPayV3Info.AppId, Timestamp = timeStamp, NonceStr = nonceStr, Package = string.Format("prepay_id={0}", resultPay.prepay_id), PaySign = paySign, OrderId = data.Number, SignType = "MD5" }; apiResult.Data = jsmodel; return(apiResult); } else { } } else { throw new NotImplementedException(JsonConvert.SerializeObject(resultPay)); } return(apiResult); }
public ComplexResponse <object> PayOrder(string tradeNo, string token) { try { var msg = Enums.PayErrorMsg.失败; object data = null; if (!string.IsNullOrEmpty(tradeNo)) { // 校验 token(3rd_session)是否过期 var flag = _userService.CheckToken(token); if (flag) { // 查取订单数据(实付费用、openId) var payOrderInfo = _orderService.GetPayOrderInfoByTradeNo(tradeNo); if (!string.IsNullOrEmpty(payOrderInfo.TradeNo) && !string.IsNullOrEmpty(payOrderInfo.OpenId)) { // 调起支付接口 var test = ConfigurationManager.AppSettings["test"]; var appId = ConfigurationManager.AppSettings["appId"]; var mchId = ConfigurationManager.AppSettings["mchId"]; var body = ConfigurationManager.AppSettings["siteName"]; var totalFee = (!string.IsNullOrEmpty(test) && test.Equals("true")) ? 1 : payOrderInfo.TotalFee; var spbillCreateIp = HttpContext.Current.Request.UserHostAddress; var notifyUrl = ConfigurationManager.AppSettings["notifyUrl"] ?? "https://wxapi.xzpfood.com/api/pay/notify"; var openId = payOrderInfo.OpenId; var key = ConfigurationManager.AppSettings["appKey"]; var requestData = new TenPayV3UnifiedorderRequestData(appId, mchId, body, tradeNo, totalFee, spbillCreateIp, notifyUrl, TenPayV3Type.JSAPI, openId, key, TenPayV3Util.GetNoncestr()); UnifiedorderResult result = TenPayV3.Unifiedorder(requestData); LogHelper.Info("\n\n统一下单结果:\n" + JsonHelper.Serialize(result)); if (result.IsResultCodeSuccess()) { string package = "prepay_id=" + result.prepay_id; string timeStamp = TenPayV3Util.GetTimestamp(); string nonceStr = TenPayV3Util.GetNoncestr(); string paySign = TenPayV3.GetJsPaySign(appId, timeStamp, nonceStr, package, key); string signType = "MD5"; data = new { timeStamp, nonceStr, package, paySign, signType }; msg = Enums.PayErrorMsg.成功; } } } else { msg = Enums.PayErrorMsg.用户登录信息过期; } } else { msg = Enums.PayErrorMsg.参数错误; } return(new ComplexResponse <dynamic>((int)msg, msg.ToString(), data)); } catch (Exception ex) { LogHelper.Debug("\n\n支付异常:\n", ex); return(new ComplexResponse <object>((int)Enums.PayErrorMsg.失败, ex.ToString())); } }
public ActionResult JsApi(string code, string state) { if (string.IsNullOrEmpty(code)) { return(Content("您拒绝了授权!")); } if (!state.Contains("|")) { //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下 //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证 return(Content("验证失败!请从正规途径进入!1001")); } try { //获取产品信息 var stateData = state.Split('|'); int productId = 0; ProductModel product = null; if (int.TryParse(stateData[0], out productId)) { int hc = 0; if (int.TryParse(stateData[1], out hc)) { var products = ProductModel.GetFakeProductList(); product = products.FirstOrDefault(z => z.Id == productId); if (product == null || product.GetHashCode() != hc) { return(Content("商品信息不存在,或非法进入!1002")); } ViewData["product"] = product; } } //通过,用code换取access_token var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code); if (openIdResult.errcode != ReturnCode.请求成功) { return(Content("错误:" + openIdResult.errmsg)); } string sp_billno = Request["order_no"]; if (string.IsNullOrEmpty(sp_billno)) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); } //else //{ // sp_billno = Request["order_no"]; //} var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = product == null ? "test" : product.Name; var price = product == null ? 100 : (int)product.Price * 100; var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openIdResult.openid, TenPayV3Info.Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); var package = string.Format("prepay_id={0}", result.prepay_id); ViewData["appId"] = TenPayV3Info.AppId; ViewData["timeStamp"] = timeStamp; ViewData["nonceStr"] = nonceStr; ViewData["package"] = package; ViewData["paySign"] = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key); //临时记录订单信息,留给退款申请接口测试使用 Session["BillNo"] = sp_billno; Session["BillFee"] = price; return(View()); } catch (Exception ex) { var msg = ex.Message; msg += "<br>" + ex.StackTrace; msg += "<br>==Source==<br>" + ex.Source; if (ex.InnerException != null) { msg += "<br>===InnerException===<br>" + ex.InnerException.Message; } return(Content(msg)); } }
/// <summary> /// 调起微信支付JSAPI /// </summary> /// <param name="openId"></param> /// <param name="orderNo">订单号</param> /// <param name="body"></param> /// <param name="price">金额 单位分</param> /// <param name="hostAddress">请求地址ip</param> /// <param name="notifyUrl">回调地址</param> /// <param name="payType">默认0 公众号支付,1小程序支付</param> /// <returns></returns> public static object TenPayByJsapi(string openId, string orderNo, string body, int price, string hostAddress, string notifyUrl, int payType = 0) { string code = ""; try { string spBillno = orderNo; int totalFee = price; string ip = hostAddress; string payAppid = WxOpenId, parSecret = WxOpenId;// 公众号配置 string payMchId = "", payMchIdkey = ""; if (payType != 0) { //小程序配置 payMchId = "1482472582"; payMchIdkey = "679E465F44514F46A05F881997E6631A"; payAppid = WxOpenId; parSecret = WxOpenSecret; } TenPayV3Info payInfo = new TenPayV3Info(payAppid, parSecret, payMchId, payMchIdkey, notifyUrl); Log.WriteLogToTxt("PAYV3Info" + JsonHelper.ToJson(payInfo), LogType.Debug); var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(payInfo.AppId, payInfo.MchId, body, spBillno, totalFee, ip, payInfo.TenPayV3Notify, TenPayV3Type.JSAPI, openId, payInfo.Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口 Log.WriteLogToTxt("统一下单结果:" + JsonHelper.ToJson(result), LogType.Debug); //参数生成 var package = string.Format("prepay_id={0}", result.prepay_id); var paySign = TenPayV3.GetJsPaySign(payInfo.AppId, timeStamp, nonceStr, package, payInfo.Key); #region 原支付返回参数,2018-06-23修改 /* * h5唤起支付 */ code = "{ appId: '" + payAppid + "',timeStamp: '" + timeStamp + "', nonceStr: '" + nonceStr + "',package: '" + package + "',paySign:'" + paySign + "',signType:'" + "MD5" + "'}"; #endregion //WxJSAPIPayDTO payPara = new WxJSAPIPayDTO() //{ // appId = payAppid, // timeStamp = timeStamp, // nonceStr = nonceStr, // package = package, // paySign = paySign, // signType = "MD5" //}; return(code); } catch (Exception ex) { WxWriteLogError(ex, "异常调起统一下单"); } return(null); //return code; }
public ActionResult JsApi(string topupItemId = "2", string bodytext = "微信充值") { try { //RCLog.Info(this, "进入JsApi"); var topupItem = _context.TopupItems.FirstOrDefault(z => z.Id == topupItemId); if (topupItem == null) { return(Content("商品信息不存在,或非法进入!1002")); } //var openId = User.Identity.Name; var openId = HttpContext.Session.GetString("OpenId"); string sp_billno = DateTime.Now.Ticks.ToString(); var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = bodytext; var price = topupItem.Price;//单位:分 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WeiXinConfig.appId, WeiXinConfig.MchId, body, sp_billno, price, HttpContext.UserHostAddress()?.ToString(), WeiXinConfig.TenPayV3Notify, TenPayV3Type.JSAPI, openId, WeiXinConfig.Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口 RCLog.Info(this, "订单号:" + result.prepay_id); //JsSdkUiPackage jsPackage = new JsSdkUiPackage(WeiXinConfig.appId, timeStamp, nonceStr,); var package = string.Format("prepay_id={0}", result.prepay_id); RCLog.Info(this, $"sp_billno={sp_billno}"); RCLog.Info(this, $"price={price}"); //临时记录订单信息,留给退款申请接口测试使用 //HttpContext.Session.SetString("BillNo", sp_billno); //HttpContext.Session.SetString("BillFee", price.ToString()); AccountInfo accountinfo = new AccountInfo(); accountinfo.CreateTime = DateTime.Now; accountinfo.TradeNo = sp_billno; accountinfo.TradeName = package; _context.Add(accountinfo); _context.SaveChanges(); return(Json(new { appId = WeiXinConfig.appId, timeStamp = timeStamp, nonceStr = nonceStr, package = package, paySign = TenPayV3.GetJsPaySign(WeiXinConfig.appId, timeStamp, nonceStr, package, WeiXinConfig.Key) })); } catch (Exception ex) { var msg = ex.Message; msg += "<br>" + ex.StackTrace; msg += "<br>==Source==<br>" + ex.Source; if (ex.InnerException != null) { msg += "<br>===InnerException===<br>" + ex.InnerException.Message; } return(Content(msg)); } }
/// <summary> /// 订单支付操作 /// </summary> /// <param name="orderNo">加密后的订单号</param> /// <returns></returns> public ActionResult JsApi(string orderNo) { int order_id = ChangeId(orderNo); if (order_id <= 0) { return(Json(new { result = -1, msg = "订单号错误" }, JsonRequestBehavior.AllowGet)); } var order_item = OrderService.LoadEntities(n => n.id == order_id).FirstOrDefault(); if (order_item == null) { return(Json(new { result = -1, msg = "未找到该订单" }, JsonRequestBehavior.AllowGet)); } if (order_item.pay_state == (int)Pay_state.已支付) { return(Json(new { result = -1, msg = "该订单已支付过" }, JsonRequestBehavior.AllowGet)); } string body = $"感谢您购买{order_item.product.name}"; if (order_item.product.name.Length > 20) { body = $"感谢您购买{order_item.product.name.Substring(0, 17)}"; } int price = (int)(order_item.order_money * 100); var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var openId = order_item.user.wx_user.gzh_openid; TenPayV3UnifiedorderRequestData xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, order_item.order_number, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr, "WEB", DateTime.Now, null, ""); var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口 if (result.return_code.Equals("SUCCESS") && result.result_code.Equals("SUCCESS")) { //var package = $"prepay_id={result.prepay_id}"; var package = string.Format("prepay_id={0}", result.prepay_id); string paySign = string.Empty; paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key); PayEntity payEntity = new PayEntity() { goodsId = order_item.product_id.ToString(), category = "0", userId = openId, appId = TenPayV3Info.AppId, timeStamp = timeStamp, nonceStr = nonceStr, package = package, paySign = paySign, prepay_id = result.prepay_id, orderNo = orderNo //加密后的orderid }; order_item.wx_order_num = result.prepay_id; OrderService.EditEntity(order_item); return(Json(new { result = 0, msg = "下单成功", data = payEntity }, JsonRequestBehavior.AllowGet)); } SaveSyslog("用户微信下单发送错误:" + SerializeHelper.SerializeToString(result), SysLogType.前台日志, "支付系统"); return(Json(new { result = -1, msg = "微信下单时发生错误,请联系客服~!", data = "??" }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 调用微信支付,生成预支付交易ID:prepay_id /// </summary> /// <param name="param">微信支付参数</param> /// <returns></returns> public WxPayReturn Pay(WxPayParam param) { string nonceStr = TenPayV3Util.GetNoncestr(); string notifyUrl = string.Format(param.Domain + param.NotifyUrl);//通知地址,接收微信支付异步通知回调地址 int totalFee = (int)(param.TotalFee * 100); TenPayV3Type tradeType = TenPayV3Type.JSAPI; switch (param.TradeType) { case TradeType.App: tradeType = TenPayV3Type.APP; break; case TradeType.JsApi: tradeType = TenPayV3Type.JSAPI; break; case TradeType.Native: tradeType = TenPayV3Type.NATIVE; break; } DateTime timeStart = DateTime.Now; DateTime timeExpire = DateTime.Now.AddHours(0.5); //设置参数 TenPayV3UnifiedorderRequestData requestData = new TenPayV3UnifiedorderRequestData( param.AppId, param.MchId, param.Body, param.OutTradeNo, totalFee, param.ServiceIpAddress, notifyUrl, tradeType, param.Openid, param.Key, nonceStr, param.DeviceInfo, timeStart, timeExpire, param.Detail, param.Attach, param.FeeType); var result = TenPayV3.Unifiedorder(requestData); LogHelper.Info(string.Format("生成预支付ID:{0}", JsonConvert.SerializeObject(result))); if (!result.IsReturnCodeSuccess()) { throw new BaseException(result.return_msg); } if (!result.IsResultCodeSuccess()) { throw new BaseException(result.err_code_des); } WxPayReturn wxPayReturn = new WxPayReturn(); wxPayReturn.ReturnCode = WxPayState.Success; if (param.TradeType == TradeType.Native) { wxPayReturn.CodeUrl = result.code_url; } wxPayReturn.PrepayId = result.prepay_id; wxPayReturn.DeviceInfo = result.device_info; return(wxPayReturn); }
public object Do_Payment(BaseApi baseApi) { PaymentParam paymentParam = JsonConvert.DeserializeObject <PaymentParam>(baseApi.param.ToString()); if (paymentParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } if (paymentParam.billId == null || paymentParam.billId == "") { throw new ApiException(CodeMessage.InterfaceValueError, "InterfaceValueError"); } string openId = Utils.GetOpenID(baseApi.token); OpenDao openDao = new OpenDao(); //处理10分取消未支付订单 openDao.UpdateBookingStatusBy10Minute(openId); BILLLIST billList = openDao.getBillListById(paymentParam.billId, openId); if (billList == null) { throw new ApiException(CodeMessage.PaymentBillError, "PaymentBillError"); } if (billList.bookingState != "1") { throw new ApiException(CodeMessage.PaymentStateError, "PaymentStateError"); } var billId = paymentParam.billId; int totalPrice = Convert.ToInt32(billList.billPrice * 100); if (totalPrice <= 0) { throw new ApiException(CodeMessage.PaymentTotalPriceZero, "PaymentTotalPriceZero"); } //if (billList.prePayId!=null && billList.prePayId!="" && billList.prePayTime != null && billList.prePayTime != "") //{ // try // { // DateTime preDateTime = Convert.ToDateTime(billList.prePayTime); // if (DateTime.Now.AddHours(-2)< preDateTime) // { // var timeStamp = TenPayV3Util.GetTimestamp(); // var nonceStr = TenPayV3Util.GetNoncestr(); // var product = "船票"; // var package = string.Format("prepay_id={0}", billList.prePayId); // var paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key); // PaymentResults paymentResults = new PaymentResults(); // paymentResults.appId = tenPayV3Info.AppId; // paymentResults.nonceStr = nonceStr; // paymentResults.package = package; // paymentResults.paySign = paySign; // paymentResults.timeStamp = timeStamp; // paymentResults.product = product; // paymentResults.billId = billId; // return paymentResults; // } // } // catch (Exception) // { // } //} try { var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var product = "船票"; var xmlDataInfo = new TenPayV3UnifiedorderRequestData( tenPayV3Info.AppId, tenPayV3Info.MchId, product, billId, totalPrice, "127.0.0.1", tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, tenPayV3Info.Key, nonceStr); var result = TenPayV3.Html5Order(xmlDataInfo); if (result.return_msg != "") { openDao.writeLog(Global.POSCODE, "", "pay", result.return_msg); } pDao.writePrePayId(billId, result.prepay_id); var package = string.Format("prepay_id={0}", result.prepay_id); var paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key); PaymentResults paymentResults = new PaymentResults(); paymentResults.appId = tenPayV3Info.AppId; paymentResults.nonceStr = nonceStr; paymentResults.package = package; paymentResults.paySign = paySign; paymentResults.timeStamp = timeStamp; paymentResults.product = product; paymentResults.billId = billId; return(paymentResults); } catch (Exception ex) { throw new ApiException(CodeMessage.PaymentError, "PaymentError"); } }
public ActionResult ajaxorder(int?id) { //return Content("{\"code\":true,\"status\":true,\"msg\":\"提交成功!\",\"data\":{\"appid\":\"wx288f944166a4bdc6\",\"code_url\":\"weixin://wxpay/bizpayurl?pr=K9tQFgw\",\"mch_id\":\"1582948931\",\"nonce_str\":\"gelx5Eej34TWkYjL\",\"prepay_id\":\"wx18152655644502b82539bf421260374600\",\"result_code\":\"SUCCESS\",\"return_code\":\"SUCCESS\",\"return_msg\":null,\"sign\":\"4D19F96F050056C904DBD7371D974905\",\"trade_type\":\"NATIVE\",\"trade_no\":\"LX-20200418151928103008\",\"payid\":\"11\",\"wx_query_href\":\"http://localhost:4066/WeChatManage/user_order/queryWx/11\",\"wx_query_over\":\"http://localhost:4066/WeChatManage/user_order/paymentFinish/11\"}}"); try { OrdersEntity ordersEntity = ordersbll.GetEntity(id); var sp_billno = ordersEntity.OrderSn; var nonceStr = TenPayV3Util.GetNoncestr(); //商品Id,用户自行定义 string productId = ordersEntity.TelphoneID.ToString(); //创建请求统一订单接口参数 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2, tenPayV3Info.MchId, "支付靓号", sp_billno, Convert.ToInt32(ordersEntity.Price * 100), Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.NATIVE, null, tenPayV3Info.Key, nonceStr, productId: productId); //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); LogHelper.AddLog(result.ResultXml);//记录日志 H5Response root = null; if (result.return_code == "SUCCESS") { H5PayData h5PayData = new H5PayData() { appid = WeixinConfig.AppID2, code_url = result.code_url,//weixin://wxpay/bizpayurl?pr=lixpXgt mch_id = WeixinConfig.MchId, nonce_str = result.nonce_str, prepay_id = result.prepay_id, result_code = result.result_code, return_code = result.return_code, return_msg = result.return_msg, sign = result.sign, trade_type = "NATIVE", trade_no = sp_billno, payid = id.ToString(), wx_query_href = Config.GetValue("Domain2") + "/WeChatManage/user_order/queryWx/" + id, wx_query_over = Config.GetValue("Domain2") + "/WeChatManage/user_order/paymentFinish/" + id }; root = new H5Response { code = true, status = true, msg = "\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData }; } else { root = new H5Response { code = false, status = false, msg = result.return_msg }; } LogHelper.AddLog(JsonConvert.SerializeObject(root));//记录日志 return(Content(JsonConvert.SerializeObject(root))); } catch (Exception ex) { LogHelper.AddLog(ex.Message);//记录日志 throw; } }
public IActionResult JsApi([FromRoute] string orderid) { IActionResult actionResult = NoContent(); try { var _order = _context.Order.FirstOrDefault(z => z.OrderID == orderid); if (_order == null || _order.OrderStatus != 0) { _logger.LogInformation($"订单不存在{orderid}"); actionResult = Ok(new { code = 1010, msg = $"商品信息不存在,或已支付{_order.OrderStatus}" }); } else { var items = from bi in _context.BuyItem where bi.OrderID == orderid select bi; var body = string.Join('_', (from bi in items select bi.GoodsName).Take(3).ToArray()); var sessionBag = SessionContainer.GetSession(Request.GetJwtSecurityToken()?.GetUserId()); var openId = sessionBag.OpenId; string sp_billno = orderid; var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); int willpay = (int)(_order.Payable * 100); int minipay = (int)(((int)(_order.TotalPrice * 100)) * 0.8); int price = (_order.Payable != 0 && willpay >= minipay) ? willpay : minipay;//单位:分 _logger.LogInformation($"body:{body},openId={openId},orderid={orderid},timeStamp={timeStamp},nonceStr={nonceStr},_order.Payable={_order.Payable};_order.TotalPrice={_order.TotalPrice},willpay={willpay};minipay={minipay},price={price}"); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo); if (result.return_code == "SUCCESS") { _logger.LogInformation($"= {result.prepay_id} "); var package = string.Format("prepay_id={0}", result.prepay_id); var data = new { out_trade_no = orderid, TenPayV3Info.AppId, timeStamp, nonceStr, package, signType = "MD5", paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key) }; _order.PrepayId = result.prepay_id; _order.OrderStatus = TradeState.USERPAYING; _context.SaveChanges(); actionResult = Ok(new { code = 0, msg = "OK", data }); } else { actionResult = Ok(new { code = 1013, msg = result.return_msg, result.result_code, result.err_code, result.err_code_des }); _logger.LogInformation($"msg ={ result.return_msg},result_code= {result.result_code} ,err_code={result.err_code},err_code_des={result.err_code_des}"); } } } catch (Exception ex) { var msg = ex.Message; msg += $"\r\n{ex.StackTrace}\r\n==Source==\r\n{ex.Source}"; if (ex.InnerException != null) { msg += $"\r\n ===InnerException===\r\n{ex.InnerException.Message}"; } actionResult = Ok(new { code = 1012, msg = msg }); } return(actionResult); }
public HttpResult JsApi(int productId) { string errorMessage = string.Empty; try { //获取产品信息 var products = ProductModel.GetFakeProductList(); var product = products.FirstOrDefault(z => z.Id == productId); if (product == null) { return(HttpResult.WeChatError("商品信息不存在!", null)); } var openId = Commons.Current.WxOpenId; //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 string sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmssfff"), TenPayV3Util.BuildRandomStr(6)); //注意:以上订单号仅作为演示使用,如果访问量比较大,建议增加订单流水号的去重检查。 var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = product.Name; var price = (int)(product.Price * 100);//单位:分 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr); xmlDataInfo.NotifyUrl = "https://yufaquan.cn/wx/PayV3/PayNotifyUrl"; var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); var package = string.Format("prepay_id={0}", result.prepay_id); //TO DO //记录订单信息,留给退款申请接口测试使用 //HttpContext.Session.SetString("BillNo", sp_billno); //HttpContext.Session.SetString("BillFee", price.ToString()); var res = new { product, appId = TenPayV3Info.AppId, timeStamp, nonceStr, package, paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key) }; return(HttpResult.Success(res)); } catch (Exception ex) { //var msg = ex.Message; //msg += "<br>" + ex.StackTrace; //msg += "<br>==Source==<br>" + ex.Source; //if (ex.InnerException != null) //{ // msg += "<br>===InnerException===<br>" + ex.InnerException.Message; //} return(HttpResult.WeChatError(ex.Message, null)); } }
public ActionResult upgradeLevel(int?tid) { var agentEntity = agentBll.GetEntityByOpenId(CurrentWxUser.OpenId); if (agentEntity != null) { //var ordersEntityOld = ordersJMBll.GetList("{\"AgentId\":\"" + agentEntity.Id + "\",\"PayStatus\":\"" + 0 + "\"}"); //if (ordersEntityOld.Count()>0) //{ // //存在未付款的升级订单 //} LogHelper.AddLog("upgradeLevel tid=" + tid);//记录日志 decimal price = 0; string LV = ""; if (tid == 2) { price = 399; LV = "黄金代理"; } else if (tid == 3) { price = 1999; LV = "钻石代理"; } var sp_billno = string.Format("{0}{1}", "JM-", DateTime.Now.ToString("yyyyMMddHHmmss")); OrdersJMEntity ordersEntity = new OrdersJMEntity() { Price = price, LV = LV, OrderSn = sp_billno, OpenId = CurrentWxUser.OpenId, NickName = CurrentWxUser.NickName, AgentId = agentEntity.Id, Pid = agentEntity.Pid, Tid = agentEntity.Tid }; ordersEntity = ordersJMBll.SaveForm(null, ordersEntity);//创建JM升级订单表 var nonceStr = TenPayV3Util.GetNoncestr(); var timeStamp = TenPayV3Util.GetTimestamp(); //商品Id,用户自行定义 var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID, tenPayV3Info.MchId, LV, sp_billno, Convert.ToInt32(Convert.ToDecimal(price) * 100), //1 Request.UserHostAddress, WeixinConfig.TenPayV3Notify, TenPayV3Type.JSAPI, CurrentWxUser.OpenId, tenPayV3Info.Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfoH5); //调用统一订单接口 LogHelper.AddLog(result.ResultXml); //记录日志 var package = string.Format("prepay_id={0}", result.prepay_id); if (result.return_code == "SUCCESS") { WFTWxModel jsApiPayData = new WFTWxModel() { appId = WeixinConfig.AppID, timeStamp = timeStamp, nonceStr = nonceStr, package = package, paySign = TenPayV3.GetJsPaySign(WeixinConfig.AppID, timeStamp, nonceStr, package, WeixinConfig.Key) }; ViewBag.WxModel = jsApiPayData; LogHelper.AddLog(JsonConvert.SerializeObject(jsApiPayData));//记录日志 } } return(View()); }
public async Task <ActionResult> Index(FormCollection collection) { ModelForOrder order = null; int totalfee = 0; object objResult = ""; string strTotal_fee = Request.Form["totalfee"]; if (int.TryParse(strTotal_fee, out totalfee)) { totalfee = totalfee * 100; OAuthAccessTokenResult tokenResult = Session["AccessToken"] as OAuthAccessTokenResult; string body = "瑞雪管理系统充值"; string timeStamp = TenPayV3Util.GetTimestamp(); string nonceStr = TenPayV3Util.GetNoncestr(); string openid = tokenResult.openid; string tenPayV3Notify = "http://w.roccode.cn/pay/ResultNotify"; string key = "8f75e82b6f1b7d82f7952121a6801b4a"; string billNo = string.Format("{0}{1}{2}", WeixinData.MchId, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WeixinData.AppId, WeixinData.MchId, body, billNo, totalfee, Request.UserHostAddress, tenPayV3Notify, Senparc.Weixin.MP.TenPayV3Type.JSAPI, openid, key, nonceStr); UnifiedorderResult result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口 if (result.result_code == "SUCCESS") { order = new ModelForOrder(); order.appId = result.appid; order.nonceStr = result.nonce_str; order.packageValue = "prepay_id=" + result.prepay_id; order.paySign = TenPayV3.GetJsPaySign(result.appid, timeStamp, result.nonce_str, order.packageValue, key); order.timeStamp = timeStamp; order.msg = "预支付订单生成成功"; // 保存预支付订单信息 string id = Session["readerId"] as string; //OAuthUserInfo userInfo = Session["UserInfo"] as OAuthUserInfo; if (!string.IsNullOrEmpty(id)) { string groundCode = id.Substring(0, 6); string gameCode = id.Substring(6, 2); string readerCode = id.Substring(8, 3); //string sn = id.Substring(11, 5); db.Orders.Add(new Order() { GroundCode = groundCode, GameCode = gameCode, ReaderCode = readerCode, Amt = totalfee / 100, BillNo = billNo, //WeiXinCode = userInfo.nickname, //Openid = userInfo.openid, //Unionid = userInfo.unionid }); db.SaveChanges(); } } } else { order = new ModelForOrder(); order.msg = "输入充值数量异常"; } if (order == null) { order = new ModelForOrder(); order.msg = "预支付订单生成失败,请重试!"; } objResult = order; return(Json(objResult)); }
public ActionResult ajaxorder(OrdersEntity ordersEntity) { try { string city = ordersEntity.City; if (city.Contains("-")) { string[] area = ordersEntity.City.Split('-'); if (area.Length > 0) { ordersEntity.Province = area[0]; //省 ordersEntity.City = area[1]; //市 ordersEntity.Country = area[2]; //市 } } else { string[] area = ordersEntity.City.Split(' '); if (area.Length > 0) { ordersEntity.Province = area[0]; //省 ordersEntity.City = area[1]; //市 } } string payType = ordersEntity.PayType; if (payType == "alipay") { payType = "支付宝"; } else { if (ordersEntity.PC == 1) { payType = "微信扫码"; } else { payType = "微信H5"; } } ordersEntity.PayType = payType; ordersEntity = ordersbll.SaveForm(ordersEntity); var sp_billno = ordersEntity.OrderSn; var nonceStr = TenPayV3Util.GetNoncestr(); //商品Id,用户自行定义 string productId = ordersEntity.TelphoneID.ToString(); H5Response root = null; if (payType == "支付宝") { try { DefaultAopClient client = new DefaultAopClient(WeixinConfig.serviceUrl, WeixinConfig.aliAppId, WeixinConfig.privateKey, "json", "1.0", WeixinConfig.signType, WeixinConfig.payKey, WeixinConfig.charset, false); // 组装业务参数model AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); model.Body = "支付宝购买靓号"; // 商品描述 model.Subject = productId; // 订单名称 model.TotalAmount = ordersEntity.Price.ToString(); // 付款金额"0.01" model.OutTradeNo = sp_billno; // 外部订单号,商户网站订单系统中唯一的订单号 model.ProductCode = "QUICK_WAP_WAY"; model.QuitUrl = "https://ghdh.digitdance.cn:8069/webapp/jntt/Index"; // 支付中途退出返回商户网站地址 model.TimeoutExpress = "90m"; AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest(); //设置支付完成同步回调地址 request.SetReturnUrl(WeixinConfig.return_url); //设置支付完成异步通知接收地址 request.SetNotifyUrl(WeixinConfig.notify_url); // 将业务model载入到request request.SetBizModel(model); AlipayTradeWapPayResponse response = null; try { response = client.pageExecute(request, null, "post"); //Response.Write(response.Body); H5PayData h5PayData = new H5PayData(); h5PayData.form = response.Body; root = new H5Response { code = true, status = true, msg = "\u652f\u4ed8\u5b9d\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData }; } catch (Exception exp) { throw exp; } } catch (Exception ex) { //return Json(new { Result = false, msg = "缺少参数" }); } } else { //pc端返回二维码,否则H5 if (payType == "微信扫码") { //创建请求统一订单接口参数 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2, tenPayV3Info.MchId, "扫码支付靓号", sp_billno, Convert.ToInt32(ordersEntity.Price * 100), //1, Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.NATIVE, null, tenPayV3Info.Key, nonceStr, productId: productId); //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); if (result.return_code == "SUCCESS") { H5PayData h5PayData = new H5PayData() { appid = WeixinConfig.AppID2, code_url = result.code_url,//weixin://wxpay/bizpayurl?pr=lixpXgt-----------扫码支付 mch_id = WeixinConfig.MchId, nonce_str = result.nonce_str, prepay_id = result.prepay_id, result_code = result.result_code, return_code = result.return_code, return_msg = result.return_msg, sign = result.sign, trade_type = "NATIVE", trade_no = sp_billno, payid = ordersEntity.Id.ToString(), wx_query_href = "https://shop.jnlxsm.net/webapp/jntt/queryWx/" + ordersEntity.Id, wx_query_over = "https://shop.jnlxsm.net/webapp/jntt/paymentFinish/" + ordersEntity.Id }; root = new H5Response { code = true, status = true, msg = "\u5fae\u4fe1\u626b\u7801\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData }; } else { root = new H5Response { code = false, status = false, msg = result.return_msg }; } } else { var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2, tenPayV3Info.MchId, "H5购买靓号", sp_billno, // 1, Convert.ToInt32(ordersEntity.Price * 100), Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, null, tenPayV3Info.Key, nonceStr); var resultH5 = TenPayV3.Html5Order(xmlDataInfoH5); //调用统一订单接口 LogHelper.AddLog(resultH5.ResultXml); //记录日志 if (resultH5.return_code == "SUCCESS") { H5PayData h5PayData = new H5PayData() { appid = WeixinConfig.AppID2, mweb_url = resultH5.mweb_url,//H5访问链接 mch_id = WeixinConfig.MchId, nonce_str = resultH5.nonce_str, prepay_id = resultH5.prepay_id, result_code = resultH5.result_code, return_code = resultH5.return_code, return_msg = resultH5.return_msg, sign = resultH5.sign, trade_type = "H5", trade_no = sp_billno, payid = ordersEntity.Id.ToString(), wx_query_href = "https://shop.jnlxsm.net/webapp/jntt/queryWx/" + ordersEntity.Id, wx_query_over = "https://shop.jnlxsm.net/webapp/jntt/paymentFinish/" + ordersEntity.Id }; root = new H5Response { code = true, status = true, msg = "\u5fae\u4fe1\u0048\u0035\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData }; } else { root = new H5Response { code = false, status = false, msg = resultH5.return_msg }; } } } LogHelper.AddLog(JsonConvert.SerializeObject(root));//记录日志 return(Content(JsonConvert.SerializeObject(root))); } catch (Exception ex) { LogHelper.AddLog(ex.Message);//记录日志 throw; } }
public ActionResult ajaxorder(string orderno) { try { ReturnJson root = null; var ordersEntity = ordersbll.GetEntityByOrderSn(orderno); if (ordersEntity != null) { var sp_billno = ordersEntity.OrderSn; var nonceStr = TenPayV3Util.GetNoncestr(); //商品Id,用户自行定义 string productId = ordersEntity.TelphoneID.ToString(); decimal?Amount = ordersEntity.Price;//0.01M 测试 if (Amount < 0) { root = new ReturnJson { code = 200, msg = "付款金额小于0" }; } else { if (ordersEntity.PayType == "支付宝") { try { DefaultAopClient client = new DefaultAopClient(WeixinConfig.serviceUrl, WeixinConfig.aliAppId, WeixinConfig.privateKey, "json", "1.0", WeixinConfig.signType, WeixinConfig.payKey, WeixinConfig.charset, false); // 组装业务参数model AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); model.Body = "支付宝购买靓号"; // 商品描述 model.Subject = productId; // 订单名称 model.TotalAmount = Amount.ToString(); // 付款金额"0.01"ordersEntity.Price.ToString() model.OutTradeNo = sp_billno; // 外部订单号,商户网站订单系统中唯一的订单号 model.ProductCode = "QUICK_WAP_WAY"; model.QuitUrl = "http://www.1650539.com/webapp/agentshop/index"; // 支付中途退出返回商户网站地址 model.TimeoutExpress = "90m"; AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest(); //设置支付完成同步回调地址 request.SetReturnUrl(WeixinConfig.return_url); //设置支付完成异步通知接收地址 request.SetNotifyUrl(WeixinConfig.notify_url); // 将业务model载入到request request.SetBizModel(model); AlipayTradeWapPayResponse response = null; try { response = client.pageExecute(request, null, "post"); //Response.Write(response.Body); H5PayData h5PayData = new H5PayData(); h5PayData.form = response.Body; root = new ReturnJson { code = 200, msg = "\u652f\u4ed8\u5b9d\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData }; } catch (Exception exp) { throw exp; } } catch (Exception ex) { //return Json(new { Result = false, msg = "缺少参数" }); } } else { //0 手机(H5支付) 1 电脑(扫码Native支付),2微信浏览器(JSAPI) //pc端返回二维码,否则H5 if (ordersEntity.PayType == "微信扫码") { //创建请求统一订单接口参数 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID, tenPayV3Info.MchId, "扫码支付靓号", sp_billno, Convert.ToInt32(Amount * 100), //1, Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.NATIVE, null, tenPayV3Info.Key, nonceStr, productId: productId); //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); if (result.return_code == "SUCCESS") { H5PayData h5PayData = new H5PayData() { appid = WeixinConfig.AppID, code_url = result.code_url,//weixin://wxpay/bizpayurl?pr=lixpXgt-----------扫码支付 mch_id = WeixinConfig.MchId, nonce_str = result.nonce_str, prepay_id = result.prepay_id, result_code = result.result_code, return_code = result.return_code, return_msg = result.return_msg, sign = result.sign, trade_type = "NATIVE", trade_no = sp_billno, payid = ordersEntity.Id.ToString(), wx_query_href = "http://www.1650539.com/webapp/agentshop/queryWx/" + ordersEntity.Id, wx_query_over = "http://www.1650539.com/webapp/agentshop/paymentFinish/" + ordersEntity.Id }; root = new ReturnJson { code = 200, msg = "\u5fae\u4fe1\u626b\u7801\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData }; } else { root = new ReturnJson { code = 400, msg = result.return_msg }; } } else { var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID, tenPayV3Info.MchId, "H5购买靓号", sp_billno, // 1, Convert.ToInt32(Amount * 100), Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, null, tenPayV3Info.Key, nonceStr); var resultH5 = TenPayV3.Html5Order(xmlDataInfoH5); //调用统一订单接口 LogHelper.AddLog(resultH5.ResultXml); //记录日志 if (resultH5.return_code == "SUCCESS") { H5PayData h5PayData = new H5PayData() { appid = WeixinConfig.AppID, mweb_url = resultH5.mweb_url,//H5访问链接 mch_id = WeixinConfig.MchId, nonce_str = resultH5.nonce_str, prepay_id = resultH5.prepay_id, result_code = resultH5.result_code, return_code = resultH5.return_code, return_msg = resultH5.return_msg, sign = resultH5.sign, trade_type = "H5", trade_no = sp_billno, payid = ordersEntity.Id.ToString(), wx_query_href = "http://www.1650539.com/webapp/agentshop/queryWx/" + ordersEntity.Id, wx_query_over = "http://www.1650539.com/webapp/agentshop/paymentFinish/" + ordersEntity.Id }; root = new ReturnJson { code = 200, msg = "\u5fae\u4fe1\u0048\u0035\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData }; } else { root = new ReturnJson { code = 400, msg = resultH5.return_msg }; } } } } } else { root = new ReturnJson { code = 400, msg = "订单号不存在!" }; } LogHelper.AddLog(JsonConvert.SerializeObject(root));//记录日志 return(Json(root)); } catch (Exception ex) { LogHelper.AddLog(ex.Message);//记录日志 throw; } }
/// <summary> /// 生成jsapi支付预付单(JASPI) /// </summary> /// <param name="clientId">客户端ID</param> /// <param name="title">商品标题</param> /// <param name="totalAmount">支付金额(单位分)</param> /// <param name="attach">附加数据</param> /// <param name="orderId">订单id</param> /// <param name="openId">用户openid</param> /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param> /// <returns></returns> public async Task <PrePayResult <JsApiResult> > BuildJsApi(string appId, string mchId, string mchKey, string title, int totalAmount, string attach, string orderId, string localTradeNo, string openId, string notifyUrl, TimeSpan?expire = null) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException("支付标题不能为空", nameof(title)); } if (string.IsNullOrWhiteSpace(orderId)) { throw new ArgumentException("订单id不能为空", nameof(orderId)); } if (totalAmount < 1) { throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount)); } string nonceStr = TenPayV3Util.GetNoncestr(); // 微信支付统一订单 api调用,生成预付单 var requestData = new TenPayV3UnifiedorderRequestData( appId, mchId, title, localTradeNo, totalAmount, null, notifyUrl, TenPayV3Type.JSAPI, openId, mchKey, nonceStr, attach: attach, productId: orderId, timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1)) ); var result = await TenPayV3.UnifiedorderAsync(requestData); Logger.LogInformation($"JASPI支付预付单结果:{result.ResultXml}"); if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess()) { throw new Exception( $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}"); } // 返回前端支付jaapi支付数据 var timeStamp = TenPayV3Util.GetTimestamp(); string nonceStrSign = TenPayV3Util.GetNoncestr(); var package = $"prepay_id={result.prepay_id}"; var sign = TenPayV3.GetJsPaySign(appId, timeStamp, nonceStrSign, package, mchKey); return(new PrePayResult <JsApiResult> { Result = new JsApiResult { AppId = appId, NonceStr = nonceStrSign, Package = package, PaySign = sign, SignType = "MD5", TimeStamp = timeStamp }, UnifiedorderResult = result, LocalTradeNo = localTradeNo }); }
/// <summary> /// H5支付 /// </summary> /// <param name="productId"></param> /// <param name="hc"></param> /// <returns></returns> public ActionResult H5Pay(int productId, int hc) { { try { //获取产品信息 var products = ProductModel.GetFakeProductList(); var product = products.FirstOrDefault(z => z.Id == productId); if (product == null || product.GetHashCode() != hc) { return(Content("商品信息不存在,或非法进入!1002")); } string openId = null;//此时在外部浏览器,无法或得到OpenId string sp_billno = Request["order_no"]; if (string.IsNullOrEmpty(sp_billno)) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); } else { sp_billno = Request["order_no"]; } var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = product == null ? "test" : product.Name; var price = product == null ? 100 : (int)product.Price * 100; //var ip = Request.Params["REMOTE_ADDR"]; var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, openId, TenPayV3Info.Key, nonceStr); var result = TenPayV3.Html5Order(xmlDataInfo); //调用统一订单接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); /* * result:{"device_info":"","trade_type":"MWEB","prepay_id":"wx20170810143223420ae5b0dd0537136306","code_url":"","mweb_url":"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20170810143223420ae5b0dd0537136306\u0026package=1505175207","appid":"wx669ef95216eef885","mch_id":"1241385402","sub_appid":"","sub_mch_id":"","nonce_str":"juTchIZyhXvZ2Rfy","sign":"5A37D55A897C854F64CCCC4C94CDAFE3","result_code":"SUCCESS","err_code":"","err_code_des":"","return_code":"SUCCESS","return_msg":null} */ //return Json(result, JsonRequestBehavior.AllowGet); var package = string.Format("prepay_id={0}", result.prepay_id); ViewData["product"] = product; ViewData["appId"] = TenPayV3Info.AppId; ViewData["timeStamp"] = timeStamp; ViewData["nonceStr"] = nonceStr; ViewData["package"] = package; ViewData["paySign"] = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key); //设置成功页面(也可以不设置,支付成功后默认返回来源地址) var returnUrl = string.Format("https://sdk.weixin.senparc.com/TenpayV3/H5PaySuccess?productId={0}&hc={1}", productId, hc); var mwebUrl = result.mweb_url; if (!string.IsNullOrEmpty(returnUrl)) { mwebUrl += string.Format("&redirect_url={0}", returnUrl.AsUrlData()); } ViewData["MWebUrl"] = mwebUrl; //临时记录订单信息,留给退款申请接口测试使用 Session["BillNo"] = sp_billno; Session["BillFee"] = price; return(View()); } catch (Exception ex) { var msg = ex.Message; msg += "<br>" + ex.StackTrace; msg += "<br>==Source==<br>" + ex.Source; if (ex.InnerException != null) { msg += "<br>===InnerException===<br>" + ex.InnerException.Message; } return(Content(msg)); } } }
/// <summary> /// app支付预付单 /// </summary> /// <param name="clientId">客户端ID</param> /// <param name="title">商品标题</param> /// <param name="totalAmount">支付金额(单位分)</param> /// <param name="attach">附加数据</param> /// <param name="orderId">订单id</param> /// <param name="clientIp">客户端ip</param> /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param> /// <returns></returns> public async Task <PrePayResult <AppPayResult> > BuildApp(string appId, string mchId, string mchKey, string title, int totalAmount, string attach, string orderId, string localTradeNo, string clientIp, string notifyUrl, TimeSpan?expire = null) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException("支付标题不能为空", nameof(title)); } if (string.IsNullOrWhiteSpace(orderId)) { throw new ArgumentException("订单id不能为空", nameof(orderId)); } if (totalAmount < 1) { throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount)); } string nonceStr = TenPayV3Util.GetNoncestr(); // 微信支付统一订单 api调用,生成预付单 var requestData = new TenPayV3UnifiedorderRequestData( appId, mchId, title, localTradeNo, totalAmount, clientIp, notifyUrl, TenPayV3Type.APP, null, mchKey, nonceStr, attach: attach, productId: orderId, timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1)) ); var result = await TenPayV3.UnifiedorderAsync(requestData); Logger.LogInformation($"APP支付预付单结果:{result.ResultXml}"); if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess()) { throw new Exception( $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}"); } var timeStamp = TenPayV3Util.GetTimestamp(); string nonceStrSign = TenPayV3Util.GetNoncestr(); ; var package = $"Sign=WXPay"; // 生成签名sign RequestHandler paySignReqHandler = new RequestHandler(null); paySignReqHandler.SetParameter("appid", appId); paySignReqHandler.SetParameter("timestamp", timeStamp); paySignReqHandler.SetParameter("noncestr", nonceStrSign); paySignReqHandler.SetParameter("package", package); paySignReqHandler.SetParameter("prepayid", result.prepay_id); paySignReqHandler.SetParameter("partnerid", mchId); var paySign = paySignReqHandler.CreateMd5Sign("key", mchKey); return(new PrePayResult <AppPayResult> { Result = new AppPayResult { Appid = appId, Noncestr = nonceStrSign, Prepayid = result.prepay_id, Package = package, Partnerid = mchId, Sign = paySign, Timestamp = timeStamp }, UnifiedorderResult = result, LocalTradeNo = localTradeNo }); }
public ActionResult NativeNotifyUrl() { ResponseHandler resHandler = new ResponseHandler(null); //返回给微信的请求 RequestHandler res = new RequestHandler(null); string openId = resHandler.GetParameter("openid"); string productId = resHandler.GetParameter("product_id"); if (openId == null || productId == null) { res.SetParameter("return_code", "FAIL"); res.SetParameter("return_msg", "回调数据异常"); } //创建支付应答对象 //RequestHandler packageReqHandler = new RequestHandler(null); var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26);//最多32位 var nonceStr = TenPayV3Util.GetNoncestr(); //创建请求统一订单接口参数 //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId); //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId); //packageReqHandler.SetParameter("nonce_str", nonceStr); //packageReqHandler.SetParameter("body", "test"); //packageReqHandler.SetParameter("out_trade_no", sp_billno); //packageReqHandler.SetParameter("total_fee", "1"); //packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify); //packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString()); //packageReqHandler.SetParameter("openid", openId); //packageReqHandler.SetParameter("product_id", productId); //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); //packageReqHandler.SetParameter("sign", sign); //string data = packageReqHandler.ParseXML(); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "test", sp_billno, 1, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr); try { //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); //var unifiedorderRes = XDocument.Parse(result); //string prepayId = unifiedorderRes.Element("xml").Element("prepay_id").Value; //创建应答信息返回给微信 res.SetParameter("return_code", result.return_code); res.SetParameter("return_msg", result.return_msg ?? "OK"); res.SetParameter("appid", result.appid); res.SetParameter("mch_id", result.mch_id); res.SetParameter("nonce_str", result.nonce_str); res.SetParameter("prepay_id", result.prepay_id); res.SetParameter("result_code", result.result_code); res.SetParameter("err_code_des", "OK"); string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key); res.SetParameter("sign", result.sign); } catch (Exception) { res.SetParameter("return_code", "FAIL"); res.SetParameter("return_msg", "统一下单失败"); } return(Content(res.ParseXML())); }
public IActionResult Unifiedorder(UnidiedorderData udata) { using (_dbContext) { var response = ResponseModelFactory.CreateResultInstance; var stu = _dbContext.StudentBill.FirstOrDefault(x => x.StudentBillUuid == udata.BillGuid); if (stu == null) { response.SetFailed("未查找到对应缴费信息"); return(Ok(response)); } if (stu.OrderMoney >= stu.AmountPayable) { response.SetFailed("已缴费"); return(Ok(response)); } //时间戳 string timeStamp = TenPayV3Util.GetTimestamp(); //随机字符串 string nonceStr = TenPayV3Util.GetNoncestr(); string appid = "wx0bf342f51437ca67"; //获取学校绑定商户信息 var school = _dbContext.School.FirstOrDefault(x => x.SchoolUuid == udata.Guid); if (school == null) { response.SetFailed("未查找到对应学校"); return(Ok(response)); } if (school.Yard == null || school.Secretkey == null) { response.SetFailed("未查找到对应学校商户信息"); return(Ok(response)); } //商户号 string mch_id = school.Yard; //"1600884893"; //商户支付秘钥 string partnerKey = AES.AesDecrypt(school.Secretkey, HaiKan3.Utils.AES.Key); //"ew6QCdWiDfcif902EbC07dh0icTuM5le"; //签名 string sign = ""; string sign_type = "MD5"; //商品描述 string body = udata.Body; //商户订单号 string out_trade_no = ""; //标价金额(单位:分) int total_fee = udata.Totalfee; //终端IP //string spbill_create_ip = "183.158.56.51"; //Request.HttpContext.Connection.RemoteIpAddress.ToString(); string spbill_create_ip = Request.HttpContext.Connection.RemoteIpAddress.ToString(); _logger.LogInformation("ip:" + spbill_create_ip); //通知地址 string notify_url = "http://msz-b.jiulong.yoruan.com/test/PayCallBack"; //string notify_url = "http://msz-b.jiulong.yoruan.com/api/v1/student/StudentBill/PayCallBack"; //交易类型 string trade_type = "JSAPI"; //预支付id string prepayId = ""; //微信调用支付的签名 string paySign = ""; //用户openid string openid = udata.Openid; Store_Info info = new Store_Info() { address = "xxxxxx", area_code = "330185", id = "MSZzf" + appid, name = "码上知支付商城", }; TenPayV3UnifiedorderRequestData_SceneInfo sceneInfo = new TenPayV3UnifiedorderRequestData_SceneInfo(false); sceneInfo.store_info = info; //生成订单号 out_trade_no = DateTime.Now.ToString("yyyyMMddHHmmss") + TenPayV3Util.BuildRandomStr(14); _logger.LogInformation("订单号:" + out_trade_no); TenPayV3UnifiedorderRequestData requestData = new TenPayV3UnifiedorderRequestData(appid, mch_id, body, out_trade_no, total_fee, spbill_create_ip, notify_url, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openid, partnerKey, nonceStr, null, DateTime.Now, DateTime.Now.AddHours(2), null, null, "CNY", null, null, false, sceneInfo, null); var urlFormat = ReurnPayApiUrl("https://api.mch.weixin.qq.com/{0}pay/unifiedorder"); var data = requestData.PackageRequestHandler.ParseXML();//获取XML _logger.LogInformation("xml:" + data); var str = PostXmlMethod.PostXmla(urlFormat, data); _logger.LogInformation("postxml:" + str); DataSet ds = new DataSet(); StringReader stream = new StringReader(str); //读取字符串为数据量 XmlTextReader reader = new XmlTextReader(stream); //对XML的数据流的只进只读访问 ds.ReadXml(reader); //把数据读入DataSet if (ds.Tables[0].Rows.Count > 0) { if (ds.Tables[0].Rows[0]["return_code"].ToString() == "SUCCESS") { _logger.LogInformation("成功"); _logger.LogInformation("timeStamp:" + timeStamp + "; nonceStr:" + nonceStr + "; prepayId:" + ds.Tables[0].Rows[0]["prepay_id"].ToString() + "; paySign:" + ds.Tables[0].Rows[0]["sign"].ToString() + "; partnerKey:" + partnerKey); response.SetData(new { appid = ds.Tables[0].Rows[0]["appid"].ToString(), timeStamp, nonceStr, prepayId = ds.Tables[0].Rows[0]["prepay_id"].ToString(), sign_type, paySign = ds.Tables[0].Rows[0]["sign"].ToString(), sjcode = Electroniccode.getString(32), key = partnerKey, outtradeno = out_trade_no }); BillState bill = new BillState() { BillUuid = Guid.NewGuid(), BillNum = out_trade_no, Appid = appid, MchId = mch_id, Money = total_fee, Key = partnerKey, SbillUuid = udata.BillGuid, }; _logger.LogInformation("订单记录:" + JsonConvert.SerializeObject(bill)); _dbContext.BillState.Add(bill); _dbContext.SaveChanges(); return(Ok(response)); } else { response.SetFailed(ds.Tables[0].Rows[0]["return_msg"].ToString()); _logger.LogInformation("异常"); _logger.LogInformation(ds.Tables[0].Rows[0]["return_msg"].ToString()); return(Ok(response)); } } else { response.SetFailed("订单信息为空"); return(Ok(response)); } } }