/// <summary> /// 获取微信支付二维码 /// </summary> private void get_WX_QRCode(System.Web.HttpContext context) { string result = "{\"success\":false,\"msg\":\"获取微信支付二维码,请稍后再试!\"}"; context.Response.ContentType = "application/json"; context.Response.AddHeader("Access-Control-Allow-Origin", "*"); //这行代码就告诉浏览器,只有来自www.XXX.com源下的脚本才可以进行访问。 string str_productId = context.Request["productId"]; string str_productDescribe = context.Request["productDescribe"]; string str_total_fee = context.Request["total_fee"]; string str_orderid = context.Request["orderid"]; Uri prevUri = HttpContext.Current.Request.UrlReferrer; string strDomainName = (prevUri != null) ? prevUri.Host : Globals.DomainName; if (!string.IsNullOrEmpty(str_productId) && !string.IsNullOrEmpty(str_productDescribe) && !string.IsNullOrEmpty(str_total_fee)) { NativePay nativePay = new NativePay(); //支付url,有效期为10小时 string strQRCodeUrl = nativePay.GetPayUrl(str_productId, str_productDescribe, int.Parse(str_total_fee) , string.Format(WxPayConfig.NOTIFY_URL_Custom, strDomainName), str_orderid); if (!string.IsNullOrEmpty(strQRCodeUrl)) { string t = "支付成功回调地址:" + string.Format(WxPayConfig.NOTIFY_URL_Custom, strDomainName); strQRCodeUrl = "http://" + Globals.DomainName + "/API/MakeQRCode.aspx?data=" + HttpUtility.UrlEncode(strQRCodeUrl); result = "{\"success\":true,\"msg\":\"" + strQRCodeUrl + "\",\"remark\":\"" + t + "\"}"; } } context.Response.Write(result); context.Response.End(); }
//扫码支付 public ActionResult Payment(int orederId) { var order = _payMeentDbService.GetOrderById(orederId); if (string.IsNullOrEmpty(order.TradeNumber)) { order.TradeNumber = WxPayApi.GenerateOutTradeNo(); } if (order.OrderState == OrderState.Success) { //Success("已经支付"); return(RedirectToAction("PaidSuccess", new { tradeno = order.TradeNumber })); } var user = new User() { UserGuid = Guid.NewGuid(), Username = "******" }; NativePay nativePay = new NativePay(); string url2 = nativePay.GetPayUrl(order, user.LastIpAddress); ViewBag.QRCode = "/Checkout/MakeQRCode?data=" + HttpUtility.UrlEncode(url2); ViewBag.Order = order; return(View()); }
public async Task <Tuple <bool, string> > PagePay(string body, string outTradeNo, int totalFee, string productId) { try { var nativePay = new NativePay(); //生成扫码支付模式二url var url2 = await nativePay.GetPayUrl(body, outTradeNo, totalFee, productId); //将url生成二维码图片 var writerSvg = new BarcodeWriterSvg { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { ErrorCorrection = ErrorCorrectionLevel.H } }; var svgImageData = writerSvg.Write(url2); return(svgImageData == null ? new Tuple <bool, string>(false, "返回数据为空!") : new Tuple <bool, string>(true, svgImageData.ToString())); } catch (Exception e) { return(new Tuple <bool, string>(false, e.Message)); } }
//跳转至微信支付页面 public ActionResult wechat(int id) { OrderResponse response = _orderService.OrderDetail(id); var userContext = UserContext.WebUserContext; ViewBag.UserContext = userContext; if (response == null || response.MemberId != userContext.Id) { return(RedirectToAction("index", "player", new { area = "player" })); } else if (response.OrderStatus == OrderStatusEm.支付成功) { return(RedirectToAction("paysuccess", "playerpay", new { area = "player", orderId = id })); } else if (response.OrderStatus != OrderStatusEm.等待支付 && response.OrderStatus != OrderStatusEm.支付失败) { return(RedirectToAction("index", "player", new { area = "player" })); } else { _orderService.PayLog(id, response.Money, PayTypeEm.微信, userContext.Id);//插入支付流水信息 NativePay nativePay = new NativePay(); string url = nativePay.GetPayUrl(response); ViewBag.QRCode = "/commondata/makeqrcode?data=" + HttpUtility.UrlEncode(url); ViewBag.Order = response; return(View()); } }
public ActionResult WeiXin() { if (Globals.IsWeiXinDevice()) { //是微信客户端走这边 string wechatcode = QueryString.SafeQ("wechatcode"); if (string.IsNullOrEmpty(wechatcode)) { string url = Request.Url.ToString(); string redirecturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(url), "0"); return(Redirect(redirecturl)); } else { MemWeChatMsgEntity msg = WeiXinJsSdk.Instance.GetWeChatShortInfo(wechatcode); string _paycode = QueryString.SafeQ("paycode"); VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(_paycode); string redirecturl = string.Format(WeiXinConfig.URL_Pay_InWeiXin, msg.OpenId, _payen.NeedPayPrice); Response.Redirect(redirecturl); } } else { //网站类调出微信端支付通道 string _paycode = QueryString.SafeQ("paycode"); VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(_paycode); DateTime dtnow = DateTime.Now; NativePay nativePay = new NativePay(); WxPayData data = nativePay.GetPayUrl(_payen, "MWEB");//得到调用微信接口的路径 string url = data.GetValue("mweb_url").ToString(); return(Redirect(url)); } return(View()); }
public static byte[] qrcode(string orderId, string body, string total_fee) { NativePay nativePay = new NativePay(); //生成扫码支付模式二url string url = nativePay.GetPayUrl(orderId, body, total_fee); //string str = HttpUtility.UrlEncode(url); string str = url; //初始化二维码生成工具 QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; qrCodeEncoder.QRCodeVersion = 0; qrCodeEncoder.QRCodeScale = 4; //将字符串生成二维码图片 Bitmap image = qrCodeEncoder.Encode(str, Encoding.Default); //保存为PNG到内存流 MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Png); //输出二维码图片 //Response.BinaryWrite(ms.GetBuffer()); //Response.End(); return(ms.GetBuffer()); //return ms; }
//二维码支付 public ActionResult NativePay(string OrderId) { Log.Info(this.GetType().ToString(), "page load"); int totalPrice = 0; string OrderNum = OrderId; if (string.IsNullOrEmpty(OrderNum)) { if (Session["orderId"] != null) { OrderNum = Session["orderId"].ToString(); } else { return(Content("暂无订单!")); } } var models = OSer.GetOrderDetail(OrderNum);//正常订单 if (models.TotalPrice != null && models.TotalPrice > 0) { totalPrice = Convert.ToInt32(models.TotalPrice * 100); } if (models.SubtractPrice != null && models.SubtractPrice > 0) { totalPrice = Convert.ToInt32((models.TotalPrice - models.SubtractPrice) * 100); } NativePay nativePay = new NativePay(); //生成扫码支付模式一url //string url1 = nativePay.GetPrePayUrl("123456789"); //生成扫码支付模式二url string url2 = nativePay.GetPayUrl(OrderNum, totalPrice); //初始化二维码生成工具 QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; qrCodeEncoder.QRCodeVersion = 0; qrCodeEncoder.QRCodeScale = 4; //将字符串生成二维码图片 Bitmap image = qrCodeEncoder.Encode(url2, Encoding.Default); //保存为PNG到内存流 MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Png); return(File(ms.GetBuffer(), @"image/Png")); //输出二维码图片 //Response.BinaryWrite(ms.GetBuffer()); }
public ActionResult Pay(string productCode, string productName, string productDesc, float price, int num, int paytype /*1-支付宝,2-微信,3-银联*/) { string orderno = wxPayService.generate_orderno(1, 1); #region 保存订单记录,以便接收支付成功消息时更新订单的状态 /// insert 到order表 //orders o = new orders(); //o.orderno = generate_orderno(1, 1); //o.product_code = cpcode; //o.product_name = cpname; //o.product_desc = cpdesc; //o.price = price; //o.num = num; //switch (paytype) //{ // case 1: // o.paytype = "支付宝"; // break; // case 2: // o.paytype = "微信支付"; // break; // case 3: // o.paytype = "银联支付"; // break; //} //o.sumittime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //o.Insert(); #endregion float f = price * 100.0F * num; int total_fee = (int)f; ////LogService.LOG_LEVENL = 3; ////LogService.Debug(this.GetType().ToString(), "total_fee=" + f); switch (paytype) { case 1: //支付宝 //Response.Redirect(Url.Action("Index", "aliPay") + "?productCode=" + cpcode + "&productName=" + cpname + "&productDesc=" + cpdesc + "&orderno=" + o.orderno + "&total_fee=" + total_fee); break; case 2: // 微信支付 // Response.Redirect(Url.Action("Index", "Weixin") + "?productCode=" + cpcode + "&productName=" + cpname + "&productDesc=" + cpdesc + "&orderno=" + orderno + "&total_fee=" + total_fee); NativePay nativePay = new NativePay(); //生成扫码支付模式二url string url = StringService.ToHexString(nativePay.GetPayUrl(productCode, productName, productDesc, orderno, total_fee)); Response.Redirect(Url.Action("ScanQRCodeImage", "Home") + "?url=" + HttpUtility.UrlEncode(url) + "&orderno=" + orderno); break; case 3: // 银联 //Response.Redirect(Url.Action("Index", "Bank") + "?productCode=" + cpcode + "&productName=" + cpname + "&productDesc=" + cpdesc + "&orderno=" + o.orderno + "&total_fee=" + total_fee); break; } return(Content("")); }
public async Task <IActionResult> NativePay() { Log.Info(GetType().ToString(), "page load"); var nativePay = new NativePay(); var url = await nativePay.GetPayUrl("123456789"); var imageUrl = "MakeQrCode?data=" + UrlEncoder.Default.Encode(url); return(View("NativePay", imageUrl)); }
public BusinessPayCode() { InitializeComponent(); TextBox.Text = Properties.Resources.Note_text.ToString(); //初始化支付页面说明 NativePay nativePay = new NativePay(); string url2 = nativePay.GetPayUrl("Test"); //生成扫码支付模式二url //将url生成二维码图片 WxPayCode.ImageLocation = "MakeQRCode.aspx?data=" + HttpUtility.UrlEncode(url2); }
protected void Page_Load(object sender, EventArgs e) { NativePay nativePay = new NativePay(); //生成扫码支付模式二url string url2 = nativePay.GetPayUrl("123456789"); Image2.ImageUrl = "MakeQRCode.aspx?data=" + HttpUtility.UrlEncode(url2); }
public string PrintColor; //彩色黑白 protected void Page_Load(object sender, EventArgs e) { //接收从WebUi.aspx传过来的pages参数 int pages = int.Parse(Request.QueryString["pages"]); Label3.Text = pages.ToString(); //本地文件的路径 path = Request.QueryString["path"]; //获取传递过来的单/双 PrintType = Request.QueryString["PrintType"]; //获取黑白/彩色 PrintColor = Request.QueryString["PrintColor"]; NativePay nativePay = new NativePay(); //生成扫码支付模式二url //传递到微信后台的参数 int price = 1; //显示价格的参数 double showprice = 0; if (PrintColor.Equals("0")) { price = pages * 15; showprice = pages * 0.15; } else { price = pages * 100; showprice = pages * 1; } //显示页数 lb_page.Text = pages.ToString(); //显示价格 lb_Money.Text = showprice.ToString(); //price 为了测试改成1 WxPayData wx = nativePay.GetPayUrl(1, "123456789", "商品名称", "商品标记", "商品描述"); WxPayData result = new WxPayData(); result.SetValue("appid", wx.GetValue("appid")); result.SetValue("mch_id", wx.GetValue("mch_id")); result.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); result.SetValue("out_trade_no", wx.GetValue("out_trade_no")); result.SetValue("sign", wx.MakeSign()); //为了测试,把下单后的信息输出到控制台 System.Diagnostics.Debug.Write(result.ToXml()); //把下单后WxPayData的对象result存到Session Session["result"] = result; //获得统一下单接口返回的二维码链接 string url2 = wx.GetValue("code_url").ToString(); //生成二维码 CreateQRImg(url2); }
// GET: Weixin public ActionResult Index(string productCode, string productName, string productDesc, string orderno, int total_fee) { LogService.LOG_LEVENL = 2; NativePay nativePay = new NativePay(); //生成扫码支付模式二url string url = StringService.StringToHexString(nativePay.GetPayUrl(productCode, productName, productDesc, orderno, total_fee)); Response.Redirect(Url.Action("ScanQRCodeImage", "weixin") + "?url=" + HttpUtility.UrlEncode(url) + "&orderno=" + orderno); return(View()); }
public ActionResult WeiXin() { string _paycode = QueryString.SafeQ("paycode"); VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(_paycode); DateTime dtnow = DateTime.Now; NativePay nativePay = new NativePay(); WxPayData data = nativePay.GetPayUrl(_payen); string url = data.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接 ViewBag.Url = url; return(View()); }
//转到支付页面 public ActionResult Payment(string orderId) { if (string.IsNullOrEmpty(orderId)) { throw new ArgumentException("guide"); } NativePay nativePay = new NativePay(); string outTradeNo; string url2 = nativePay.GetPayUrl(orderId, out outTradeNo); ViewBag.QRCode = "/Home/MakeQrCode?data=" + HttpUtility.UrlEncode(url2); //ViewBag.Order = order; ViewBag.outTradeNo = outTradeNo; return(View()); }
/// <summary> /// 微信支付 /// </summary> /// <returns></returns> public ViewResultBase WeiXinPcPay() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var nativePay = new NativePay(); //订单号 var code = "XXXX"; //提示内容 var body = "支付"; //价格 var realPrice = (Convert.ToDecimal(0.1 * 100).ToString("#.##")); var url2 = nativePay.GetPayUrl(code, realPrice, body); //将url生成二维码图片 ViewData["imgUrl"] = "/Demo/Pay/MakeQrCode?data=" + HttpUtility.UrlEncode(url2); return(View()); }
protected void Page_Load(object sender, EventArgs e) { Log.Info(this.GetType().ToString(), "page load"); NativePay nativePay = new NativePay(); //生成扫码支付模式一url string url1 = nativePay.GetPrePayUrl("123456789"); //生成扫码支付模式二url string url2 = nativePay.GetPayUrl("123456789", 100); //将url生成二维码图片 Image1.ImageUrl = "MakeQRCode.aspx?data=" + HttpUtility.UrlEncode(url1); Image2.ImageUrl = "MakeQRCode.aspx?data=" + HttpUtility.UrlEncode(url2); }
public JsonResult WXPayUrl(PaperInfo paperInfo) { if (Session["user"] == null) { return(Json(new { success = false, data = "请您先登录,才能购买商品哦!" }, JsonRequestBehavior.AllowGet)); } else { string userId = string.Empty; List <UserRecord> list = (List <UserRecord>)Session["user"]; userId = list[0].UserId; NativePay nativePay = new NativePay(); PaperBLL paperBLL = new PaperBLL(); PaperDetailViewModel paperDetailViewModel = paperBLL.PaperDetailById(paperInfo.Id.ToString(), userId); string _outTradeNo = string.Empty; string url = nativePay.GetPayUrl(paperDetailViewModel.detail[0], out _outTradeNo); if (string.IsNullOrEmpty(url)) { return(Json(new { success = false, data = "微信生成订单时出现错误,请您重新支付!" }, JsonRequestBehavior.AllowGet)); } else { Business business = new Business(); List <UserRecord> rows = (List <UserRecord>)Session["user"]; business.UserId = rows[0].UserId; business.Name = rows[0].Name; business.CreateTime = DateTime.Now; business.OutTradeNo = _outTradeNo; business.PaperCode = paperDetailViewModel.detail[0].Code; business.PaperId = paperDetailViewModel.detail[0].Id; business.Title = paperDetailViewModel.detail[0].Title; business.Version = paperDetailViewModel.detail[0].Version; business.Price = paperDetailViewModel.detail[0].Price; business.PayState = 0; bool result = paperBLL.CreateBusiness(business); if (result == true) { return(Json(new { success = true, data = url, orderNumber = _outTradeNo }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { success = false, data = "微信生成订单时出现错误,请您重新支付!" }, JsonRequestBehavior.AllowGet)); } } } }
public ActionResult <string> GetMakeQRCode(string productId, int type) { NativePay nativePay = new NativePay(); string url = string.Empty; if (type == 1) { //生成扫码支付模式一url url = nativePay.GetPrePayUrl(productId); } else if (type == 2) { //生成扫码支付模式二url url = nativePay.GetPayUrl(productId); } //将url生成二维码图片 return(MakeQRCode.GetMakeQRCodeBase64String(HttpUtility.UrlEncode(url))); }
public (Stream, string) NativeCreateOrder(string openId, IOrderBase order, string notifyUrl) { NativePay nativePay = new NativePay(); var outTradeNo = WxPayApi.GenerateOutTradeNo(); var orderDict = new Dictionary <string, string>(); orderDict.Add("fee", order.Fee.ToString()); orderDict.Add("name", order.Name); orderDict.Add("notify_url", notifyUrl); orderDict.Add("tag", order.Tag ?? String.Empty); orderDict.Add("desc", order.Desc ?? String.Empty); orderDict.Add("out_trade_no", outTradeNo); orderDict.Add("productId", order.Id.ToString()); var payUrl = nativePay.GetPayUrl(orderDict); return(MakeQRCode(payUrl), outTradeNo); }
public ActionResult WeiXin() { string _paycode = QueryString.SafeQ("paycode"); VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(_paycode); DateTime dtnow = DateTime.Now; NativePay nativePay = new NativePay(); WxPayData data = nativePay.GetPayUrl(_payen); if (data.GetValue("result_code").ToString().ToLower() == "success") { string url = data.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接 ViewBag.Url = url; } else { string error = data.GetValue("err_code_des").ToString(); ViewBag.ErrorMsg = error; } ViewBag.PayEntity = _payen; return(View()); }
public ActionResult OrderConfirm() { string paycode = QueryString.SafeQ("code"); int success = QueryString.IntSafeQ("s"); //是否需要订单成功提醒 int freshnum = QueryString.IntSafeQ("fn"); //循环次数,超过10次自动关闭 if (freshnum > 10) { return(null); } VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(paycode); if (_payen.PayMethod == (int)PayType.WeChat)//微信支付 { if (Globals.IsWeiXinDevice()) { string wechatcode = ""; wechatcode = QueryString.SafeQ("wechatcode"); //是微信客户端走这边 if (string.IsNullOrEmpty(wechatcode)) { //没有获取微信授权码 string url = Request.Url.ToString(); string redirecturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(url), "0"); return(Redirect(redirecturl)); } else { //有微信授权码 JsApiPay jsApiPay = new JsApiPay(); try { jsApiPay.GetOpenidAndAccessTokenFromCode(wechatcode); } catch (Exception ex) { //授权码过期 string baseurl; Dictionary <string, string> nvc = new Dictionary <string, string>(); string oldurl = Request.Url.ToString(); StringUtils.ParseUrl(oldurl, out baseurl, out nvc); nvc.Remove("wechatcode"); if (nvc.ContainsKey("fn")) { nvc["fn"] = (StringUtils.GetDbInt(nvc["fn"]) + 1).ToString(); } else { nvc.Add("fn", "1"); } string url = baseurl + "?"; foreach (string key in nvc.Keys) { url += "&" + key + "=" + nvc[key]; } string redirecturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(url), "0"); return(Redirect(redirecturl)); } WxPayData paydata = jsApiPay.GetUnifiedOrderResult(_payen); string wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数 ViewBag.WeiXinJsApiParam = wxJsApiParam; } } else { //网站类调出微信端支付通道 DateTime dtnow = DateTime.Now; NativePay nativePay = new NativePay(); WxPayData data = nativePay.GetPayUrl(_payen, "MWEB");//得到调用微信接口的路径 string url = data.GetValue("mweb_url").ToString(); return(Redirect(url)); } } ViewBag.PayOrderEntity = _payen; ViewBag.Success = success; return(View()); }
/// <summary> /// 创建订单 /// </summary> /// <param name="setid"></param> /// <param name="paytype"></param> /// <returns></returns> public string createOrder(int setid, int paytype) { if (paytype > 2) { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = "支付方式不正确" })); } int userid = User.userid; //创建订单 using (shhouseEntities ent = new shhouseEntities()) { ObjectParameter ordernum = new ObjectParameter("ordernum", typeof(string)); ObjectParameter setname = new ObjectParameter("setname", typeof(string)); ObjectParameter state = new ObjectParameter("state", typeof(int)); ObjectParameter totals = new ObjectParameter("totals", typeof(int)); ObjectParameter msg = new ObjectParameter("msg", typeof(string)); ent.order_create_jjr2018(userid, DateTime.Now, DateTime.Now.AddHours(2), setid, 1, paytype, ordernum, setname, totals, state, msg); int _state = (int)state.Value; if (_state == 1) { if (paytype == 1) { IAopClient client = new DefaultAopClient( "https://openapi.alipay.com/gateway.do", "APPID", "APP_PRIVATE_KEY", "json", "1.0", "RSA2", "ALIPAY_PUBLIC_KEY", "UTF-8", false ); //支付宝支付 AlipayTradePagePayModel model = new AlipayTradePagePayModel { Body = (string)setname.Value, Subject = (string)setname.Value, TotalAmount = Math.Round((decimal)totals.Value / 100m, 2).ToString(), OutTradeNo = (string)ordernum.Value, ProductCode = "FAST_INSTANT_TRADE_PAY" }; AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl(""); // 设置异步通知接收地址 request.SetNotifyUrl(""); // 将业务model载入到request request.SetBizModel(model); try { AlipayTradePagePayResponse response = client.SdkExecute(request); //支付宝支付地址 string url = "https://openapi.alipay.com/gateway.do?" + response.Body; //Response.Write(response.Body); return(JsonConvert.SerializeObject(new repmsg { state = 1, msg = "", data = new { tradeno = (string)ordernum.Value, total = (int)totals.Value, paytype = paytype, url = url } })); } catch (Exception exp) { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = exp.Message })); } } else if (paytype == 2) { try { //微信支付 NativePay nativePay = new NativePay(); string url = nativePay.GetPayUrl(setid.ToString(), (string)setname.Value, (string)ordernum.Value, (int)totals.Value); if (string.IsNullOrEmpty(url)) { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = "订单创建失败" })); } QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; qrCodeEncoder.QRCodeVersion = 0; qrCodeEncoder.QRCodeScale = 8; //将字符串生成二维码图片 Bitmap image = qrCodeEncoder.Encode(url, Encoding.Default); string _root = Server.MapPath($"~/wxpaycode/{userid}/"); if (!System.IO.Directory.Exists(_root)) { System.IO.Directory.CreateDirectory(_root); } string _filename = Guid.NewGuid().ToString().Replace("-", "") + ".jpg"; image.Save(_root + _filename, System.Drawing.Imaging.ImageFormat.Jpeg); return(JsonConvert.SerializeObject(new repmsg { state = 1, msg = "", data = new { tradeno = (string)ordernum.Value, setname = (string)setname.Value, total = (int)totals.Value, paytype = paytype, qrimg = $"/wxpaycode/{userid}/{_filename}" } })); } catch (Exception e) { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = e.Message })); } } else { return(""); } } else { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = "提交失败,请稍后再试" })); } } }
public object getPayQRcode(Dictionary <string, object> dicParas) { try { string errMsg = string.Empty; string orderId = dicParas.ContainsKey("orderId") ? dicParas["orderId"].ToString() : string.Empty; string strPayChannel = dicParas.ContainsKey("payChannel") ? dicParas["payChannel"].ToString() : string.Empty; string payType = dicParas.ContainsKey("payType") ? dicParas["payType"].ToString() : string.Empty; string subject = dicParas.ContainsKey("subject") ? dicParas["subject"].ToString() : string.Empty; if (string.IsNullOrWhiteSpace(orderId)) { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单号无效")); } if (string.IsNullOrWhiteSpace(payType)) { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付方式为空")); } //支付方式 PaymentChannel PayChannel = (PaymentChannel)Convert.ToInt32(payType); Flw_Order order = Flw_OrderBusiness.GetOrderModel(orderId); if (order == null) { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单号无效")); } Base_StoreInfo store = XCCloudStoreBusiness.GetStoreModel(order.StoreID); if (store == null) { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单所属门店无效")); } //订单减免金额 decimal freePay = order.FreePay == null ? 0 : order.FreePay.Value; //计算订单实付金额,单位:元 decimal amount = (decimal)order.PayCount - freePay; PayQRcodeModel model = new PayQRcodeModel(); model.OrderId = orderId; //SelttleType selttleType = (SelttleType)store.SelttleType.Value; SelttleType selttleType = (SelttleType)Convert.ToInt32(strPayChannel); switch (selttleType) { case SelttleType.NotThird: break; case SelttleType.AliWxPay: //微信支付宝官方通道 { #region 支付宝、微信 if (PayChannel == PaymentChannel.ALIPAY) //支付宝 { try { IAlipayTradeService serviceClient = F2FBiz.CreateClientInstance(AliPayConfig.serverUrl, AliPayConfig.appId, AliPayConfig.merchant_private_key, AliPayConfig.version, AliPayConfig.sign_type, AliPayConfig.alipay_public_key, AliPayConfig.charset); AliPayCommon alipay = new AliPayCommon(); AlipayTradePrecreateContentBuilder builder = alipay.BuildPrecreateContent(order, amount, subject); //如果需要接收扫码支付异步通知,那么请把下面两行注释代替本行。 //推荐使用轮询撤销机制,不推荐使用异步通知,避免单边账问题发生。 //AlipayF2FPrecreateResult precreateResult = serviceClient.tradePrecreate(builder); //AliPayConfig.notify_url //商户接收异步通知的地址 AlipayF2FPrecreateResult precreateResult = serviceClient.tradePrecreate(builder, AliPayConfig.notify_url); switch (precreateResult.Status) { case ResultEnum.SUCCESS: model.QRcode = precreateResult.response.QrCode; break; case ResultEnum.FAILED: LogHelper.SaveLog(TxtLogType.AliPay, precreateResult.response.Body); return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, precreateResult.response.Body)); case ResultEnum.UNKNOWN: if (precreateResult.response == null) { LogHelper.SaveLog(TxtLogType.AliPay, "配置或网络异常,请检查后重试"); return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败")); } else { LogHelper.SaveLog(TxtLogType.AliPay, "系统异常,请更新外部订单后重新发起请求"); return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败")); } } } catch (Exception e) { LogHelper.SaveLog(TxtLogType.AliPay, e.Message); return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败")); } } else if (PayChannel == PaymentChannel.WXPAY) //微信 { NativePay native = new NativePay(); try { WxPayData resultData = native.GetPayUrl(order, amount, subject); if (resultData.GetValue("result_code") != null) { string resule = resultData.GetValue("result_code").ToString(); if (resule == "SUCCESS") { model.QRcode = resultData.GetValue("code_url").ToString(); //获得统一下单接口返回的二维码链接 } else { LogHelper.SaveLog(TxtLogType.WeiXinPay, resultData.GetValue("err_code_des").ToString()); return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败," + resultData.GetValue("err_code_des").ToString())); } } else { LogHelper.SaveLog(TxtLogType.WeiXinPay, resultData.GetValue("return_msg").ToString()); return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败," + resultData.GetValue("return_msg").ToString())); } } catch (WxPayException ex) { LogHelper.SaveLog(TxtLogType.WeiXinPay, ex.Message); return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败")); } catch (Exception e) { LogHelper.SaveLog(TxtLogType.WeiXinPay, e.Message); return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败")); } } #endregion } break; case SelttleType.StarPos: //新大陆 #region 新大陆 { string error = ""; PPosPayData.OrderPay pposOrder = new PPosPayData.OrderPay(); pposOrder.txnTime = System.DateTime.Now.ToString("yyyyMMddHHmmss"); pposOrder.tradeNo = order.OrderID; //pposOrder.tradeNo = Guid.NewGuid().ToString().Replace("-", ""); pposOrder.amount = Convert.ToInt32(amount * 100).ToString(); //实际付款 pposOrder.total_amount = Convert.ToInt32(amount * 100).ToString(); //订单总金额 pposOrder.subject = subject; pposOrder.payChannel = PayChannel.ToString(); PPosPayApi ppos = new PPosPayApi(); PPosPayData.OrderPayACK result = ppos.OrderPay(pposOrder, out error); if (result == null) { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败," + error)); } model.QRcode = result.payCode; } break; #endregion case SelttleType.LcswPay: //扫呗 #region 扫呗 { string qrcode = ""; LcswPayDate.OrderPay payInfo = new LcswPayDate.OrderPay(); //payInfo.terminal_trace = Guid.NewGuid().ToString().Replace("-", ""); payInfo.terminal_trace = order.OrderID; payInfo.pay_type = PayChannel.ToDescription(); payInfo.order_body = subject; payInfo.total_fee = Convert.ToInt32(amount * 100).ToString(); LcswPayAPI api = new LcswPayAPI(); if (api.OrderPay(payInfo, out qrcode)) { model.QRcode = qrcode; } else { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败")); } } break; #endregion case SelttleType.DinPay: //智付 #region 智付 string errmsg = ""; DinPayData.ScanPay scanPay = new DinPayData.ScanPay(); //scanPay.order_no = order.OrderID; scanPay.order_no = Guid.NewGuid().ToString().Replace("-", ""); scanPay.order_time = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); scanPay.order_amount = amount.ToString("0.01"); scanPay.service_type = PayChannel == PaymentChannel.WXPAY ? "weixin_scan" : "alipay_scan"; scanPay.product_name = subject; scanPay.product_desc = subject; DinPayApi payApi = new DinPayApi(); string payCode = payApi.GetQRcode(scanPay, out errmsg); if (payCode == "") { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败," + errmsg)); } model.QRcode = payCode; break; #endregion } return(ResponseModelFactory <PayQRcodeModel> .CreateModel(isSignKeyReturn, model)); } catch (Exception e) { throw e; } }
/// <summary> /// 订单生成 /// </summary> /// <returns></returns> public ActionResult Order() { string proId = Request.Form["proId"]; string name = Request.Form["proName"]; string price = Request.Form["price"]; string num = Request.Form["num"]; string email = Request.Form["email"]; ProductViewModel model = BProduct.SearchById(proId); if (model == null) { return(Content("订单生成异常")); } double _price = Convert.ToDouble(price); int _num = Convert.ToInt32(num); if (model.Price != _price) { return(Content("订单生成异常(金额不符)")); } if (model.Name != name) { return(Content("订单生成异常(名称不符)")); } double totalPrice = _price * _num; string orderNo = DTHelper.GetCurrentTimeOrderNo(); //订单生成 OrderViewModel orderModel = new OrderViewModel(); orderModel.Count = _num; orderModel.NO = orderNo; orderModel.Price = _price; orderModel.Product_Id = Convert.ToInt32(proId); orderModel.Remark = email; orderModel.Type = Request.Form["paytype"]; orderModel.LocalStatus = "待支付"; orderModel.UpdateTime = DateTime.Now; BOrder.Insert(orderModel); string url = ""; if (orderModel.Type == "1") { NativePay nativePay = new NativePay(); //转化为以分为单位的金额 int money = Convert.ToInt32(totalPrice * 100); //生成扫码支付模式二url url = "https://www.baifubao.com/o2o/0/qrcode?size=4&text=" + nativePay.GetPayUrl(proId, money, name, orderNo); } else if (orderModel.Type == "2") { url = "/Zhifu/precreate.aspx?tid=" + orderNo; } else { } ViewBag.QR_url = url; ViewBag.Name = name; ViewBag.Num = _num; ViewBag.Total = totalPrice; ViewBag.tNo = orderNo; ViewBag.payType = Request.Form["paytype"]; return(View()); }
/// <summary> /// 处理订单并跳转至第三方支付平台 /// add by fruitchan /// 2017-1-17 22:34:52 /// </summary> /// <param name="orderNo">订单编号</param> /// <param name="isFullPrice">是否全款</param> /// <param name="payType">支付方式</param> /// <returns>View</returns> public ActionResult OrderPay(string orderNo, int?isFullPrice, int?payType) { // 校验数据 if (!String.IsNullOrEmpty(orderNo) && isFullPrice.HasValue && payType.HasValue) { if ((isFullPrice.Value != 0 && isFullPrice != 1) || (payType.Value != 1 && payType.Value != 2)) { return(Content("参数错误!")); } bool bIsFullPrice = isFullPrice.Value == 1; OrderInfo order = OperateContext.Current.BLLSession.IOrderInfoBLL.GetListBy(m => m.OrderNo == orderNo).FirstOrDefault(); if (order == null || (order.State != 0 && order.State != 1)) { return(Content("未查询到订单信息或订单状态错误!")); } // 支付金额 decimal price = bIsFullPrice ? order.BalancePayment : order.DownPayment; #region 子订单 string strRand = ""; Random rand = new Random(); for (int i = 0; i < 6; i++) { strRand += rand.Next(0, 10); } // 生成订单编号 string newOrderNo = DateTime.Now.ToString("yyyyMMddHHmmss") + strRand; OrderItem orderItem = new OrderItem() { OrderId = order.ID, OrderNo = newOrderNo, Price = price, BalancePayment = order.BalancePayment - price, State = 0, CreateTime = DateTime.Now }; OperateContext.Current.BLLSession.IOrderItemBLL.Add(orderItem); #endregion order.PayType = payType.Value; order.IsFullPrice = bIsFullPrice; int result = OperateContext.Current.BLLSession.IOrderInfoBLL.Modify(order, "PayType", "IsFullPrice"); if (result == 1) { if (payType.Value == 1) { #region 支付宝订单 ////////////////////////////////////////////请求参数//////////////////////////////////////////// //商户订单号,商户网站订单系统中唯一订单号,必填 string out_trade_no = orderItem.OrderNo; //订单名称,必填 string subject = order.HouseTitle; //付款金额,必填 string total_fee = price.ToString(); //商品描述,可空 string body = String.Empty; //////////////////////////////////////////////////////////////////////////////////////////////// //把请求参数打包成数组 SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>(); sParaTemp.Add("service", Config.service); sParaTemp.Add("partner", Config.partner); sParaTemp.Add("seller_id", Config.seller_id); sParaTemp.Add("_input_charset", Config.input_charset.ToLower()); sParaTemp.Add("payment_type", Config.payment_type); sParaTemp.Add("notify_url", Config.notify_url); sParaTemp.Add("return_url", Config.return_url); sParaTemp.Add("anti_phishing_key", Config.anti_phishing_key); sParaTemp.Add("exter_invoke_ip", Config.exter_invoke_ip); sParaTemp.Add("out_trade_no", out_trade_no); sParaTemp.Add("subject", subject); sParaTemp.Add("total_fee", total_fee); sParaTemp.Add("body", body); //其他业务参数根据在线开发文档,添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1 //如sParaTemp.Add("参数名","参数值"); //建立请求 string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认"); return(Content(sHtmlText)); #endregion } else if (payType.Value == 2) { try { // 微信支付 NativePay nativePay = new NativePay(); string url = nativePay.GetPayUrl(orderItem.OrderNo, order.HouseTitle, Convert.ToInt32((price * 100)).ToString()); return(OperateContext.Current.RedirectAjax("ok", HttpUtility.UrlEncode(url), orderItem.OrderNo, null)); } catch (Exception) { return(Content("对不起,系统繁忙,请稍后再试!")); } } } } return(Content("请使用正确方式提交订单!")); }
/// <summary> /// PC在线支付 /// </summary> /// <param name="appId">业务系统ID</param> /// <param name="sign">签名</param> /// <param name="data">数据报文</param> public ActionResult OnlinePay(string appId, string sign, string data) { try { var onlinePay = Builder.BuildOnlinePay(); //校验支付模式 if (onlinePay.CheckModeIsSimulate()) { return(RedirectToActionPermanent("OnlinePay", "Simulate", new { payType = (int)this._payType, appId = appId, sign = sign, data = data })); } //移动端访问,跳转至微信Wap支付 if (RequestHelper.IsWapRequest()) { return(RedirectToAction("OnlineWapPay", new { appId = appId, sign = sign, data = data })); } //保存请求报文 var requestInfo = onlinePay.SaveRequest(appId, data, this._payType); //校验签名 var checkResult = onlinePay.CheckSign(appId, sign, data, requestInfo); if (checkResult.Status != ResultStatus.Success) { ViewBag.ErrorMsg = checkResult.Message; return(View()); } //解析支付请求 checkResult = onlinePay.ResolveRequest(data, requestInfo); if (checkResult.Status != ResultStatus.Success) { ViewBag.ErrorMsg = checkResult.Message; return(View()); } //校验支付参数 var checkResult2 = onlinePay.CheckParamaters(data, this._payType, requestInfo); if (checkResult2.Status != ResultStatus.Success) { ViewBag.ErrorMsg = checkResult2.Message; return(View()); } PayOrderInfo orderInfo = checkResult2.Data; #region 生成支付二维码链接code_url try { NativePay nativePay = new NativePay(); //获取订单支付金额 int paymentAmt = (int)(requestInfo.PaymentAmt * 100);//微信支付金额的单位为“分”,所以要乘以100 //异步通知url string notifyUrl = string.Format("http://{0}/WeChatPay/OnlinePayNotify", AppConfig.Global.Domain); DateTime orderEndTime = DateTime.ParseExact(orderInfo.OrderTime, "yyyyMMddHHmmss", new CultureInfo("zh-CN", true)).AddHours(24); DateTime minExpireTime = DateTime.Now.AddMinutes(6);//为保险,多加1分钟 //交易过期时间(最短过期时间间隔必须大于5分钟) string expireTime = (orderEndTime > minExpireTime ? orderEndTime : minExpireTime).ToString("yyyyMMddHHmmss"); //向微信发起统一下单请求 string codeUrl = nativePay.GetPayUrl(requestInfo.OrderId, paymentAmt, notifyUrl, expireTime); ViewBag.CodeUrl = codeUrl; ViewBag.RequestInfo = requestInfo; } catch (WxPayException wex) { requestInfo.ResultDesc = wex.Message; requestInfo.ExecuteResult = (int)ResultStatus.Error; PayRequestDAL.Update(requestInfo); ViewBag.ErrorMsg = wex.Message; return(View()); } catch (Exception ex) { requestInfo.ExecuteResult = (int)ResultStatus.Error; requestInfo.ResultDesc = ex.ToString(); PayRequestDAL.Update(requestInfo); ViewBag.ErrorMsg = "系统执行时发生异常:" + ex.Message; return(View()); } #endregion //支付请求执行成功 onlinePay.ExecuteSuccess(requestInfo); } catch (Exception ex) { ViewBag.ErrorMsg = "系统执行时发生异常:" + ex.Message; string log = string.Format(@"PC支付请求发生异常!{0}异常描述:{1}{0}异常堆栈:{2}{0}请求参数:appId={3} sign={4} data={5}", Environment.NewLine, ex.Message, ex.StackTrace, appId, sign, data); LogWriter.WriteLog(log, AppConfig.Global.WeChatPayLogFolder, ExceptionHelper.ExceptionLevel.Exception); } return(View()); }