public Unified WxPay(string body, int price, string openId) { var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 var sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); var xmlDataInfo = new TenPayV3UnifiedorderRequestData( TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Accessor.HttpContext.UserHostAddress().ToString(), 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); return(new Unified { timeStamp = timeStamp, nonceStr = nonceStr, package = package, paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key) }); }
public ActionResult productJsApi(int?id, string host) { TelphoneLiangH5Entity entity = tlbll.GetEntity(id); var sp_billno = string.Format("{0}{1}", "LX-", DateTime.Now.ToString("yyyyMMddHHmmss")); var openId = (string)Session["OpenId"]; var nonceStr = TenPayV3Util.GetNoncestr(); var timeStamp = TenPayV3Util.GetTimestamp(); //商品Id,用户自行定义 var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2, tenPayV3Info.MchId, "JSAPI购买靓号", sp_billno, Convert.ToInt32(Convert.ToDecimal(entity.Price) * 100), Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, 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.AppID2, timeStamp = timeStamp, nonceStr = nonceStr, package = package, paySign = TenPayV3.GetJsPaySign(WeixinConfig.AppID2, timeStamp, nonceStr, package, WeixinConfig.Key), callback_url = "https://shop.jnlxsm.net/webapp/jinan2/paymentFinish/" + id }; ViewBag.WxModel = jsApiPayData; LogHelper.AddLog(JsonConvert.SerializeObject(jsApiPayData));//记录日志 } ViewBag.OrderSn = sp_billno; ViewBag.Host = host; return(View(entity)); }
public ActionResult Order(string name) { var body = name ?? "SenparcProduct"; var price = 100;//单位:分 var sp_billno = string.Format("{0}{1}{2}", "1234567890", DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); var openId = User.Identity.Name; var nonceStr = TenPayV3Util.GetNoncestr(); var timeStamp = TenPayV3Util.GetTimestamp(); var xmlDataInfo = new TenPayV3UnifiedorderRequestData( Service.Config.AppId, Service.Config.MchId, body, sp_billno, price, Request.UserHostAddress, Service.Config.TenPayV3Notify, TenPayV3Type.JSAPI, openId, Service.Config.TenPayV3_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); var paySign = TenPayV3.GetJsPaySign(Service.Config.AppId, timeStamp, nonceStr, package, Service.Config.TenPayV3_Key); var vd = new TenPayV3_Odrer() { Product = name, Package = package, PaySign = paySign }; //临时记录订单信息,留给退款申请接口测试使用 Session["BillNo"] = sp_billno;//储存在数据库 Session["BillFee"] = price; return(View(vd)); }
/// <summary> /// 微信支付下单 /// JsAPI下单部分 /// </summary> /// <param name="reqmodel"></param> /// <returns></returns> public UnifiedOrderModelForJSAPI WxPayUnifiedOrderForJSAPI(RequestUnifiedOrder reqmodel) { try { var wxPayAcc = JsonHelper.Deserialize <WxPayAccVM>(AccStr); var nonceStr = TenPayV3Util.GetNoncestr(); var timeStamp = TenPayV3Util.GetTimestamp(); //此处填入此支付附加信息 var attach = string.Empty; var xmlDataInfo = new TenPayV3UnifiedorderRequestData(wxPayAcc.AppId, wxPayAcc.MchId, reqmodel.Body, reqmodel.OutTradeNo, reqmodel.TotalFee, reqmodel.SpbillCreateIp, wxPayAcc.NotifyUrl, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, reqmodel.OpenId, wxPayAcc.MchIdKey, nonceStr, null, null, null, null, attach); var result = TenPayV3.Html5Order(xmlDataInfo); //调用统一订单接口 var package = string.Format("prepay_id={0}", result.prepay_id); var paySign = TenPayV3.GetJsPaySign(wxPayAcc.AppId, timeStamp, nonceStr, package, wxPayAcc.MchIdKey); var model = new UnifiedOrderModelForJSAPI { AppId = result.appid, NonceStr = nonceStr, TimeStamp = timeStamp, Package = package, SignType = "MD5", PaySign = paySign }; return(model); } catch (Exception ex) { throw ex; } }
public async Task <JsonResult> GetPaySign(PayInput input) { using (CurrentUnitOfWork.DisableFilter(DataFilters.MustHaveTenant, DataFilters.MayHaveTenant)) { Order order = _orderRepository.Get(input.Id); TenPayV3Info tenPayV3Info = await GetTenPayV3Info(InfrastructureSession.TenantId.Value); string timeStamp = TenPayV3Util.GetTimestamp(); string nonceStr = TenPayV3Util.GetNoncestr(); if (order.PrepayIdCreatedTime.HasValue && order.PrepayIdCreatedTime < DateTime.Now.AddHours(-2)) { throw new UserFriendlyException(L("TheOrderHasOverTime")); } if (string.IsNullOrEmpty(order.PrepayId)) { string body = order.Title; //商品或支付单简要描述 string out_trade_no = order.Number; //商户系统内部的订单号,32个字符内,可包含字母,其他说明见商户订单号 int totalFee = (int)(order.PayMoney * 100); //订单总金额,只能是整数。 string spbill_create_ip = Request.UserHostAddress; //APP和网页支付提交用户端IP,Native支付填调用微信支付API的机器IP string openid = WechatUserManager.GetOpenid(order.User.ToUserIdentifier()); TenPayV3UnifiedorderRequestData xmlDataInfo = new TenPayV3UnifiedorderRequestData( tenPayV3Info.AppId, tenPayV3Info.MchId, body, out_trade_no, totalFee, Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, //trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。必传,这里需要将去获取openid赋值上去 TenPayV3Type.JSAPI, openid, tenPayV3Info.Key, nonceStr); UnifiedorderResult unifiedorderResult = TenPayV3.Unifiedorder(xmlDataInfo, 10000); string prepay_id = unifiedorderResult.prepay_id; order.PrepayId = prepay_id; order.PrepayIdCreatedTime = DateTime.Now; _orderRepository.Update(order); } nonceStr = TenPayV3Util.GetNoncestr(); RequestHandler paysignReqHandler = new RequestHandler(null); paysignReqHandler.Init(); //设置支付参数 paysignReqHandler.SetParameter("appId", tenPayV3Info.AppId); paysignReqHandler.SetParameter("timeStamp", timeStamp); paysignReqHandler.SetParameter("nonceStr", nonceStr); string package = string.Format("prepay_id={0}", order.PrepayId); paysignReqHandler.SetParameter("package", package); string paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key); paysignReqHandler.SetParameter("paySign", paySign); return(Json(paysignReqHandler.GetAllParameters())); } }
/// <summary> /// 患者微信支付下订单 /// </summary> /// <returns></returns> public async Task <TencentJSPayRequestModel> UnifiedorderAsync(bool sharing, string spbillCreateIp, YaeherConsultation consul, YaeherUser user, ServiceMoneyList product, SystemConfigs tencentparam) { TencentJSPayRequestModel jspay = new TencentJSPayRequestModel(); try { TenPayV3Info tenPayV3Info = new TenPayV3Info(tencentparam.AppID, tencentparam.AppSecret, tencentparam.TenPayMchId, tencentparam.TenPayKey, tencentparam.TenPayNotify, tencentparam.TenPayWxOpenNotify); //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 // var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); // var sjs =;//随机数 var sjs = consul.ConsultNumber.Substring(3, consul.ConsultNumber.Length - 3) + TenPayV3Util.BuildRandomStr(6); var sp_billno = sjs; // var sp_billno = string.Format("{0}{1}", sjs, user.Id); var shortbillno = sp_billno; TenPayInfo tenPayInfo = new TenPayInfo(); // var body = product == null ? "怡芽问诊" : product.DoctorName+"医生" + product.ServiceType; var body = "怡禾健康咨询"; var price = product == null ? 100 : (int)(product.ServiceExpense * 100);//单位:分 var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(tenPayV3Info.AppId, tenPayV3Info.MchId, body, sp_billno, price, spbillCreateIp, tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, user.WecharOpenID, tenPayV3Info.Key, nonceStr); //CreateWrite("C:\\回调.txt", "订单参数:" + JsonHelper.ToJson(xmlDataInfo)); var result = await UnifiedorderAsync(xmlDataInfo, sharing? "Y" : "N"); //调用统一订单接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); if (result.IsResultCodeSuccess()) { var package = string.Format("prepay_id={0}", result.prepay_id); var paysign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key); jspay.product = product; jspay.timeStamp = timeStamp; jspay.nonceStr = nonceStr; jspay.package = package; jspay.paySign = paysign; jspay.appid = tenPayV3Info.AppId; jspay.sp_billno = shortbillno; jspay.code = result.result_code; jspay.msg = result.return_msg; } else { jspay.code = result.result_code; jspay.msg = result.return_msg; } } catch (Exception ex) { jspay.code = "FAIL"; jspay.msg = ex.Message.ToString(); } return(jspay); }
public IActionResult Index([FromQuery] string prepay_id) { var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var package = string.Format("prepay_id={0}", prepay_id); var paysign = TenPayV3.GetJsPaySign("wx40a04481d2e12c20", timeStamp, nonceStr, package, tenPyConfigRead.Key); return(Ok(new { timeStamp, nonceStr, package, paysign })); }
public object Do_Payment(object param) { PaymentParam paymentParam = JsonConvert.DeserializeObject <PaymentParam>(param.ToString()); if (paymentParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } try { SessionBag sessionBag = SessionContainer.GetSession(paymentParam.token); var openId = sessionBag.OpenId; var billId = this.createBill(openId, paymentParam); var totalPrice = this.getBillPrice(paymentParam); if (totalPrice == 0) { throw new ApiException(CodeMessage.PaymentTotalPriceZero, "PaymentTotalPriceZero"); } var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var product = paymentParam.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); 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 TenPayV3JSAPIParameters(string prepay_id) { this.AppId = WeChatInfo.AppID; this.TimeStamp = TenPayV3Util.GetTimestamp(); this.NonceStr = TenPayV3Util.GetNoncestr(); this.Package = string.Format("prepay_id={0}", prepay_id); this.SignType = "MD5"; this.PaySign = TenPayV3.GetJsPaySign(this.AppId, this.TimeStamp, this.NonceStr, this.Package, WeChatInfo.Key); }
public ActionResult GetPrepayid(string sessionId) { try { var sessionBag = SessionContainer.GetSession(sessionId); var openId = sessionBag.OpenId; //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 var sp_billno = string.Format("{0}{1}{2}", Config.SenparcWeixinSetting.TenPayV3_MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = "小程序微信支付Demo"; var price = 1;//单位:分 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WxOpenAppId, Config.SenparcWeixinSetting.TenPayV3_MchId, body, sp_billno, price, Request.UserHostAddress, Config.SenparcWeixinSetting.TenPayV3_WxOpenTenpayNotify, TenPay.TenPayV3Type.JSAPI, openId, Config.SenparcWeixinSetting.TenPayV3_Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口 WeixinTrace.SendCustomLog("统一订单接口调用结束", "请求:" + xmlDataInfo.ToJson() + "\r\n\r\n返回结果:" + result.ToJson()); var packageStr = "prepay_id=" + result.prepay_id; //记录到缓存 var cacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance(); cacheStrategy.Set($"WxOpenUnifiedorderRequestData-{openId}", xmlDataInfo, TimeSpan.FromDays(4));//3天内可以发送模板消息 cacheStrategy.Set($"WxOpenUnifiedorderResultData-{openId}", result, TimeSpan.FromDays(4));//3天内可以发送模板消息 return Json(new { success = true, prepay_id = result.prepay_id, appId = Config.SenparcWeixinSetting.WxOpenAppId, timeStamp, nonceStr, package = packageStr, //signType = "MD5", paySign = TenPayV3.GetJsPaySign(WxOpenAppId, timeStamp, nonceStr, packageStr, Config.SenparcWeixinSetting.TenPayV3_Key) }); } catch (Exception ex) { return Json(new { success = false, msg = ex.Message }); } }
public ActionResult WxPayOrder(Guid orderid, Guid payid) { try { var openId = HttpContext.Session.GetString("OpenId"); var order = _orderSrv.GetProductOrderById(orderid); var pay = _paySrv.GetPaymentOrderById(payid); if (order == null) { return(NotFound()); } string sp_billno = GuidEncoder.Encode(pay.Id); var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = payid.ToString(); var price = (int)(order.Amount * 100); 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); //调用统一订单接口 //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); ViewData["successUrl"] = Url.Action("WxPayOrder", "WxPay", new { orderid = orderid, payid = payid }); // //临时记录订单信息,留给退款申请接口测试使用 // HttpContext.Session.SetString("BillNo", sp_billno); // HttpContext.Session.SetString("BillFee", price.ToString()); ViewData["order"] = order; ViewData["pay"] = pay; 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)); } }
static void Main(string[] args) { string orderNo = "123456789"; int amount = 360; string body = "abcdefg"; string ip = null;// "127.0.0.1"; string openId = "openId"; string attach = "充值订单"; WxPay pay = new WxPay(); var payParam = pay.GetAppPayParameter(orderNo, amount, body, ip, attach); Console.WriteLine(payParam.ToJson()); //IWxPay pay2 = new WxJsApiPay(); //var payParam2 = pay2.GetPayParameter(orderNo, amount, body, ip, openId); return; string appId = "wx2428e34e0e7dc6ef"; string key = "e10adc3849ba56abbe56e056f20f883e"; string stamp = "1525663034"; string nonceStr = "3669A032E96C56D111292833CB51F79F"; string package = "prepay_id=wx1234567890"; string signType = "MD5"; string sign = TenPayV3.GetJsPaySign(appId, stamp, nonceStr, package, key, signType); //D8B716043EC84E0503EA9D303B017336 //string sign2 = new WxJsApiPay().GetPaySign(appId, package, nonceStr, stamp, signType, key); //Console.WriteLine(sign); //Console.WriteLine(sign2); string s = Guid.NewGuid().ToString();//.Replace("-", ""); string s2 = Guid.NewGuid().ToString("N"); string s3 = String2.GetGuid(); Console.WriteLine(s); Console.WriteLine(s2); Console.WriteLine(s3); Console.Read(); }
public ActionResult GetPrepayid(string sessionId) { try { var sessionBag = SessionContainer.GetSession(sessionId); var openId = sessionBag.OpenId; //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 var sp_billno = string.Format("{0}{1}{2}", Service.Config.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"), Guid.NewGuid().ToString("n").Substring(0, 6)); //生成订单信息并保存到数据库 var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = "小程序微信支付Demo"; var price = 1;//单位:分 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(Service.Config.WxOpenAppId, Service.Config.MchId, body, sp_billno, price, Request.UserHostAddress, Service.Config.TenPayV3Notify, TenPayV3Type.JSAPI, openId, Service.Config.TenPayV3_Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口 var packageStr = "prepay_id=" + result.prepay_id; return(Json(new { success = true, prepay_id = result.prepay_id, appId = Service.Config.WxOpenAppId, timeStamp, nonceStr, package = packageStr, //signType = "MD5", paySign = TenPayV3.GetJsPaySign(Service.Config.WxOpenAppId, timeStamp, nonceStr, packageStr, Service.Config.TenPayV3_Key) })); } catch (Exception ex) { return(Json(new { success = false, msg = ex.Message })); } }
public async Task <(bool, GetH5PaymentBeforeResponseDto)> GetH5PaymentBeforeAsync(GetH5PaymentBeforeResquestDto requstDto) { //微信下单 //随机字符串参数 string nonceStr = WeChatUtils.GetRandomString(16, false, true, true, false, string.Empty); var unifiedOrderRequestDto = new UnifiedOrderRequestDto { AppId = PlatformSettings.CDClientAppId, MerchantId = requstDto.MerchantId, Body = requstDto.Body, OutTradeNo = requstDto.OutTradeNo, TotalFee = requstDto.TotalFee, //支付金额,单位分 NotifyUrl = requstDto.NotifyUrl, //支付通知回调 OpenId = requstDto.OpenId, MerchantSecret = requstDto.MerchantSecret, NonceStr = nonceStr }; var unifiedRes = await UnifiedOrderAsync(unifiedOrderRequestDto); if (!unifiedRes.IsReturnCodeSuccess() || !unifiedRes.IsResultCodeSuccess()) { var errMsg = new StringBuilder(); errMsg.Append($"微信支付下单失败:return_msg-{unifiedRes.return_msg}|err_code-{unifiedRes.err_code}|err_code_des-{unifiedRes.err_code_des}"); errMsg.Append($"{Environment.NewLine}at SenparcPayBiz.GetH5PaymentBeforeAsync({JsonConvert.SerializeObject(requstDto)})"); Logger.Error(errMsg.ToString()); return(false, null); } var result = new GetH5PaymentBeforeResponseDto { AppId = unifiedOrderRequestDto.AppId, TimeStamp = WeChatUtils.GetTimestamp(), NonceStr = unifiedOrderRequestDto.NonceStr, Package = $"prepay_id={unifiedRes.prepay_id}", SignType = "MD5" }; result.Sign = TenPayV3.GetJsPaySign( unifiedOrderRequestDto.AppId, result.TimeStamp, result.NonceStr, result.Package, unifiedOrderRequestDto.MerchantSecret, "MD5"); return(true, result); }
public ActionResult JsApi(int?id, string Tel, string Price, string host) { OrdersEntity ordersEntity = new OrdersEntity() { TelphoneID = id, Tel = Tel, Price = Convert.ToDecimal(Price), Host = host, PayType = "JsApi" }; //创建订单表 ordersEntity = ordersbll.SaveForm(ordersEntity); var openId = (string)Session["OpenId"]; var sp_billno = ordersEntity.OrderSn; var nonceStr = TenPayV3Util.GetNoncestr(); var timeStamp = TenPayV3Util.GetTimestamp(); //商品Id,用户自行定义 var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2, tenPayV3Info.MchId, "JSAPI购买靓号", sp_billno, Convert.ToInt32(ordersEntity.Price * 100), Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, 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.AppID2, timeStamp = timeStamp, nonceStr = nonceStr, package = package, paySign = TenPayV3.GetJsPaySign(WeixinConfig.AppID2, timeStamp, nonceStr, package, WeixinConfig.Key), callback_url = "https://shop.jnlxsm.net/webapp/jinan2/paymentFinish/" + ordersEntity.Id }; ViewBag.WxModel = jsApiPayData; LogHelper.AddLog(JsonConvert.SerializeObject(jsApiPayData));//记录日志 } return(View(ordersEntity)); }
/// <summary> /// 支付前调用方法 /// </summary> /// <param name="requestDto"></param> /// <returns></returns> public async Task <GetWeiXinPaymentBeforeResponseDto> GetPaymentBeforeAsync(string userId, GetWeiXinPaymentBeforeRequestDto requestDto) { //商品订单 string outTradeNo = $"GDSPDD_{GetRandomString(10, false, false, true, false, "")}{DateTime.Now.ToString("yyyyMMddHHmmss")}"; //交易流水 string TransactionNumber = $"GDJYLS_{GetRandomString(10, false, false, true, false, "")}{DateTime.Now.ToString("yyyyMMddHHmmss")}"; //随机字符串 string nonceStr = GetRandomString(16, false, true, true, false, string.Empty); TransactionFlowingModel model = new TransactionFlowingModel(); model.Amount = 1; model.OrgGuid = string.Empty; model.CreatedBy = userId; model.LastUpdatedBy = userId; model.TransactionFlowingGuid = Guid.NewGuid().ToString("N"); model.OutTradeNo = outTradeNo; model.TransactionNumber = TransactionNumber; model.TransactionStatus = "WaitForPayment"; model.Channel = "微信支付"; UnifiedorderResult unifie = await UnifiedorderAsync(outTradeNo, nonceStr, requestDto); if (unifie.IsReturnCodeSuccess()) { model.ChannelNumber = unifie.prepay_id; model.Insert(); GetWeiXinPaymentBeforeResponseDto result = new GetWeiXinPaymentBeforeResponseDto { appId = this.AppID, nonceStr = nonceStr, timeStamp = Convert.ToInt32(GetTimeSpan().TotalSeconds), package = $"prepay_id={unifie.prepay_id}" }; string sign = TenPayV3.GetJsPaySign(result.appId, result.timeStamp.ToString(), result.nonceStr, result.package, MerchantSecret, "MD5"); result.sign = sign; result.signType = "MD5"; return(result); } else { } return(null); }
public ActionResult pay(string orderno) { var ordersEntity = ordersbll.GetEntityByOrderSn(orderno); if (ordersEntity != null) { var nonceStr = TenPayV3Util.GetNoncestr(); var timeStamp = TenPayV3Util.GetTimestamp(); //商品Id,用户自行定义 var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID, tenPayV3Info.MchId, ordersEntity.Tel, ordersEntity.OrderSn, Convert.ToInt32(Convert.ToDecimal(ordersEntity.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.id = ordersEntity.Id; ViewBag.WxModel = jsApiPayData; LogHelper.AddLog(JsonConvert.SerializeObject(jsApiPayData));//记录日志 } return(View()); } else { ReturnJson root = new ReturnJson { code = 400, msg = "订单号不存在!" }; return(Json(root)); } }
public static PayRequestData GetPayData(Vip model, string hostAddress) { //var _payInfo = TenPayV3InfoCollection.Data[System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]]; var _payInfo = GetTenPayInfo(); _payInfo.TenPayV3Notify = AppConfig.Instance.PayNotify; var orderCode = string.Format("{0}{1}{2}", _payInfo.MchId, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); var productInfo = "中捷足球-教练培训费"; //var mpconfig = GetMpConfigModel(); var price = 5000 * 100; //(int)((mpconfig == null || mpconfig.VipFee == 0 ? 50 : mpconfig.VipFee) * 100); var timeStamp = TenPayV3Util.GetTimestamp(); var nonestr = TenPayV3Util.GetNoncestr(); var data = new TenPayV3UnifiedorderRequestData(_payInfo.AppId, _payInfo.MchId, productInfo, orderCode, price, hostAddress, _payInfo.TenPayV3Notify, Senparc.Weixin.MP.TenPayV3Type.JSAPI, model.WeChatId, _payInfo.Key, nonestr); Senparc.Weixin.WeixinTrace.SendCustomLog("支付请求日志1", Newtonsoft.Json.JsonConvert.SerializeObject(data)); var result = TenPayV3.Unifiedorder(data); var package = string.Format("prepay_id={0}", result.prepay_id); var reqData = new PayRequestData { OrderCode = orderCode, Fee = price, AppId = _payInfo.AppId, TimeStamp = timeStamp, NonceStr = nonestr, Package = package, PaySign = TenPayV3.GetJsPaySign(_payInfo.AppId, timeStamp, nonestr, package, _payInfo.Key), VipName = model.VipName }; Senparc.Weixin.WeixinTrace.SendCustomLog("支付请求日志1", Newtonsoft.Json.JsonConvert.SerializeObject(reqData)); return(reqData); }
#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 public WeChatUnifiedorderResult Pay(WeChatUnifiedorderParamter paramter) #pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释 { string nonceStr = GetNonceStr(paramter); string timeStamp = TenPayV3Util.GetTimestamp(); TenPayV3UnifiedorderRequestData tenPayV3UnifiedorderRequestData = new TenPayV3UnifiedorderRequestData( Options.WeChatBaseOptions.AppId, Options.WeChatBaseOptions.MchId, paramter.Body, paramter.OutTradeNo, paramter.TotalFee, Options.WeChatBaseOptions.UserHostAddress, GetNotifyUrl(Options.WeChatBaseOptions.PayNotifyUrl, WeChatNotifyType.Pay), paramter.TradeType, paramter.OpenId, Options.WeChatBaseOptions.Key, nonceStr, paramter.DeviceInfo, paramter.TimeStart, paramter.TimeExpire, GetDetail(paramter), paramter.Attach, paramter.FeeType, paramter.GoodsTag, paramter.ProductId, paramter.LimitPay, GetSceneInfo(paramter), paramter.ProfitSharing); UnifiedorderResult unfortifiedResult = TenPayV3.Unifiedorder(tenPayV3UnifiedorderRequestData); if (unfortifiedResult.return_code != Model.ReturnCode.SUCCESS) { throw new WeChatServiceException($"微信统一下单失败, return_code: {unfortifiedResult.return_code}, return_msg: {unfortifiedResult.return_msg}.", unfortifiedResult, typeof(UnifiedorderResult)); } string package = $"prepay_id={unfortifiedResult.prepay_id}"; return(new WeChatUnifiedorderResult { ResultXml = unfortifiedResult.ResultXml, DeviceInfo = unfortifiedResult.device_info, TradeType = unfortifiedResult.trade_type, MWebUrl = unfortifiedResult.mweb_url, PrepayId = unfortifiedResult.prepay_id, TimeStamp = timeStamp, NonceStr = nonceStr, Package = package, CodeUrl = unfortifiedResult.code_url, JsPaySign = TenPayV3.GetJsPaySign(Options.WeChatBaseOptions.AppId, timeStamp, nonceStr, package, Options.WeChatBaseOptions.Key) }); }
/// <summary> /// H5支付 /// </summary> /// <param name="productId"></param> /// <param name="hc"></param> /// <returns></returns> public ActionResult H5Pay(int orderId = 0) { { try { string openId = null;//此时在外部浏览器,无法或得到OpenId string sp_billno = Request["order_no"]; if (string.IsNullOrEmpty(sp_billno)) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = string.Format("{0}{1}{2}", "1234567890", DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); } else { sp_billno = Request["order_no"]; } var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = "SenparcProduct"; //产品名称 var price = 100; //单位:分 //var ip = Request.Params["REMOTE_ADDR"]; var xmlDataInfo = new TenPayV3UnifiedorderRequestData(Service.Config.AppId, Service.Config.MchId, body, sp_billno, price, Request.UserHostAddress, Service.Config.TenPayV3Notify, TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, openId, Service.Config.TenPayV3_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"] = Service.Config.AppId; ViewData["timeStamp"] = timeStamp; ViewData["nonceStr"] = nonceStr; ViewData["package"] = package; ViewData["paySign"] = TenPayV3.GetJsPaySign(Service.Config.AppId, timeStamp, nonceStr, package, Service.Config.TenPayV3_Key); //设置成功页面(也可以不设置,支付成功后默认返回来源地址) var returnUrl = string.Format("https://sdk.weixin.senparc.com/TenpayV3/H5PaySuccess?orderId={0}", orderId); 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> /// 获取微信 JSSDK 预支付接口参数,支付的有效时间为 1分钟; /// </summary> /// <param name="openId">用户的OpenId</param> /// <param name="orderNumber">订单号</param> /// <param name="orderDesc">订单描述信息;长度为 String(128),但字符串长度为72时也说信息错误;</param> /// <param name="clientIp">用户Ip地址;</param> /// <param name="money">订单金额;注意,元为单位;</param> /// <param name="orderGuid"></param> /// <param name="payResultCallbackApi">支付成功时的回调接口,默认下使用配置中的回调接口</param> /// <param name="expireMinuts">1分钟失效</param> /// <returns></returns> public PayInfoForWeixinJsBridge GetPayInfoForWeixinJsBridge(string openId, string orderNumber, string orderDesc, string clientIp, decimal money, string orderGuid = null, string payResultCallbackApi = null, int expireMinuts = 1) { var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); if (!string.IsNullOrEmpty(orderDesc) && orderDesc.Length > 40) { orderDesc = orderDesc.Substring(0, 40); } if (string.IsNullOrEmpty(payResultCallbackApi)) { payResultCallbackApi = Config.TenPayNotify; } var expirePayTime = DateTime.Now.AddMinutes(expireMinuts); //.. var xmlDataInfo = new TenPayV3UnifiedorderRequestData( Config.AppId, Config.MchId, orderDesc, orderNumber, (int)(money * 100), //订单金额,以元为单位;传到微信那儿需要以分为单位; clientIp, Config.TenPayNotify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openId, Config.TenPayKey, nonceStr, timeExpire: expirePayTime, attach: orderGuid); //https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); if (!result.IsReturnCodeSuccess()) { return(new PayInfoForWeixinJsBridge { Error = true, ErrorCode = result.err_code, ErrorDesc = result.err_code_des, ReturnMsg = result.return_msg }); } var package = string.Format("prepay_id={0}", result.prepay_id); return(new PayInfoForWeixinJsBridge { AppId = Config.AppId, Noncestr = nonceStr, Timestamp = timeStamp, Package = package, PaySign = TenPayV3.GetJsPaySign(Config.AppId, timeStamp, nonceStr, package, Config.TenPayKey), SignType = "MD5", ExpirePayDateTime = expirePayTime }); }
public ActionResult JsApi(string code, string state) { if (string.IsNullOrEmpty(code)) { return(Content("您拒绝了授权!")); } if (!state.Contains("|")) { //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下 //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证 return(Content("验证失败!请从正规途径进入!1001")); } try { //通过,用code换取access_token var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code); if (openIdResult.errcode != ReturnCode.请求成功) { return(Content("错误:" + openIdResult.errmsg)); } //获取产品信息 var stateData = state.Split('|'); int buyid = 0; DbBuy buy = null; if (int.TryParse(stateData[0], out buyid)) { buy = Config.Helper.SingleOrDefaultById <DbBuy>(buyid); if (buy == null || buy.OpenID != openIdResult.openid || buy.PayTime != null) { return(Content("商品信息不存在,或非法进入!1002")); } ViewData["product"] = buy; } 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 = buy == null ? "test" : buy.Product.ProductName; var price = buy == null ? 100 : (int)buy.ActualCost * 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); buy.OrderNo = sp_billno; Config.Helper.Save(buy); ViewData["appId"] = TenPayV3Info.AppId; ViewData["timeStamp"] = timeStamp; ViewData["nonceStr"] = nonceStr; ViewData["package"] = package; ViewData["paySign"] = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key); return(View(buy)); } 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> public RequestPayment Prepay(string openid, string appid, string title, int total_fee) { bool isMock = !Cat.Foundation.ConfigManager.BookSettings.OpenWxPay.ToBoolean(true); //注释下面这个判断,就是一个正常的微信支付流程了。 或配置OpenWxPay的值为false if (isMock) { var user = AllServices.BookUserService.GetSingle(openid); if (user == null) { throw new Exception("找不到用户"); } var MM_Currency_Ratio = Foundation.ConfigManager.BookSettings.Currency_Ratio; var MM_Currency = total_fee * 0.01 * MM_Currency_Ratio; //新增充值记录 AllServices.BookUserRechargeService.Add(user.Openid, (int)Cat.Enums.Book.RechargeType.微信支付充值, (int)MM_Currency, "模拟充值"); //调整用户账户余额 user.Currency = user.Currency + (int)MM_Currency; AllServices.BookUserService.Update(user); // throw new Exception("充值成功!惊不惊喜?意不意外?"); } else { //string openid = "o0LDq4njwCCuQuj3FOIZeLFDrc9o"; string key = WechatAppConfig.Mch_id_secret; //商户平台设置的密钥key //int price = 120; //int total_fee = price * 100; string outTradeNo = StringHelper.GetUUID().ToString(); //商户订单号 TenPayV3UnifiedorderRequestData requestData = new TenPayV3UnifiedorderRequestData( appid, WechatAppConfig.Mch_id, title, outTradeNo, total_fee, IPHelper.GetClientIP(), CatContext.HttpContext.Request.Scheme + "://" + CatContext.HttpContext.Request.Host + "/Book/WechatPay/Notify", TenPayV3Type.JSAPI, openid, key, TenPayV3Util.GetNoncestr() ); var result = TenPayV3.Unifiedorder(requestData); AllLogService.SysActionLogService.AddLog(Log.Services.Enum.LogLevel.INFO, requestData.ToJson(), "微信支付统一下单"); //接口请求失败 if (result.return_code != "SUCCESS") { throw new Exception(result.return_msg); } //业务失败 else if (result.result_code != "SUCCESS") { throw new Exception(string.Format("[{0}]{1}", result.err_code, result.err_code_des)); } //成功 else if (result.IsResultCodeSuccess()) { //再次签名接口,返回支付数据 string timeStamp = TenPayV3Util.GetTimestamp(); string nonceStr = TenPayV3Util.GetNoncestr(); string package = "prepay_id=" + result.prepay_id; string paySign = TenPayV3.GetJsPaySign(result.appid, timeStamp, nonceStr, package, key); var data = new RequestPayment() { AppId = result.appid, NonceStr = nonceStr, Package = package, SignType = "MD5", TimeStamp = timeStamp, PaySign = paySign }; //数据库记录订单信息 AllPublicService.WechatPayOrderService.Add(Enums.Wechat.AppKey.喵喵看书, appid, openid, WechatAppConfig.Mch_id, outTradeNo, title, requestData.ToJson(), total_fee, false, "预支付", result.prepay_id); return(data); } } if (isMock) { throw new Exception("充值成功!惊不惊喜?意不意外?"); } throw new Exception("微信预支付失败"); }
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, DateTime.Now.ToString("yyyyMMdd"), TenPayV3Util.BuildRandomStr(10)); } 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 : product.Price * 100; var xmlDataInfo = new TenPayV3RequestData(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); 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 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)); } }
/// <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.Query["order_no"]; if (string.IsNullOrEmpty(sp_billno)) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); } else { sp_billno = Request.Query["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, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPay.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; //临时记录订单信息,留给退款申请接口测试使用 HttpContext.Session.SetString("BillNo", sp_billno); HttpContext.Session.SetString("BillFee", price.ToString()); 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 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 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 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 = HttpContext.Session.GetString("OpenId"); string sp_billno = Request.Query["order_no"]; if (string.IsNullOrEmpty(sp_billno)) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); } else { sp_billno = Request.Query["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, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPay.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); //临时记录订单信息,留给退款申请接口测试使用 HttpContext.Session.SetString("BillNo", sp_billno); HttpContext.Session.SetString("BillFee", price.ToString()); 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>微信支付-获取微信支付签名</summary> public static string GetPaySign(string nonceStr, string timeStamp, string package) { return(TenPayV3.GetJsPaySign(AppID, timeStamp, nonceStr, package, MchKey)); }