/// <summary> /// 原生支付 模式二 /// 根据统一订单返回的code_url生成支付二维码。该模式链接较短,生成的二维码打印到结账小票上的识别率较高。 /// 注意:code_url有效期为2小时,过期后扫码不能再发起支付 /// </summary> /// <returns></returns> public ActionResult NativeByCodeUrl() { //创建支付应答对象 //RequestHandler packageReqHandler = new RequestHandler(null); var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28); var nonceStr = TenPayV3Util.GetNoncestr(); //商品Id,用户自行定义 string productId = DateTime.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", Request.UserHostAddress); //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, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.NATIVE, productId, TenPayV3Info.Key, nonceStr); //调用统一订单接口 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); BarcodeWriter bw = new BarcodeWriter(); var ms = new MemoryStream(); var bitmap = bw.Write(bitMatrix); bitmap.Save(ms, ImageFormat.Png); //return File(ms, "image/png"); ms.WriteTo(Response.OutputStream); Response.ContentType = "image/png"; return(null); }
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 })); } }
/// <summary> /// 获取预支付订单 /// </summary> /// <param name="orderId">订单号</param> /// <param name="body">支付主体内容</param> /// <param name="spbillCreateIp">IP</param> /// <param name="openId"></param> /// <param name="price"></param> /// <param name="nonceStr"></param> /// <returns></returns> public string GetPrepayId(string orderId, string body, string spbillCreateIp, string openId, decimal price, string nonceStr = null) { //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(null); //初始化 packageReqHandler.Init(); nonceStr = string.IsNullOrEmpty(nonceStr) ? TenPayUtil.GetNoncestr() : nonceStr; //设置package订单参数 packageReqHandler.SetParameter("appid", AppId); //公众账号ID packageReqHandler.SetParameter("mch_id", MchId); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", body); packageReqHandler.SetParameter("out_trade_no", orderId); //商家订单号 packageReqHandler.SetParameter("total_fee", (price * 100).ToString("0")); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", spbillCreateIp); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", TenPayV3Notify); //接收财付通通知的URL packageReqHandler.SetParameter("trade_type", "JSAPI"); //交易类型 packageReqHandler.SetParameter("openid", openId); //用户的openId string sign = packageReqHandler.CreateMd5Sign("key", Key); packageReqHandler.SetParameter("sign", sign); //签名 string data = packageReqHandler.ParseXML(); var result = TenPayV3.Unifiedorder(data); var res = XDocument.Parse(result); if (res.Element("xml") == null) { throw new Exception("统一订单接口出错"); } var prepayId = res.Element("xml").Element("prepay_id") == null ? null : res.Element("xml").Element("prepay_id").Value; if (string.IsNullOrEmpty(prepayId)) { throw new Exception("统一订单接口出错,未获取到预支付订单号"); } return(prepayId); }
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> /// 创建微信预支付交易单 native /// </summary> private string GetCodeUrl(string orderNo, int amount, string body, string ip, string productId, string attach) { string url = string.Empty; string nonceStr = String2.GetGuid(); var payType = TenPayV3Type.NATIVE; var param = new TenPayV3UnifiedorderRequestData(AppId, MchId, body, orderNo, amount, ip, NotifyUrl, payType, null, Key, nonceStr, productId: productId); param.Attach = attach; var preOrder = TenPayV3.Unifiedorder(param); if (preOrder.IsReturnCodeSuccess() && preOrder.IsResultCodeSuccess()) { url = preOrder.code_url; } return(url); }
/// <summary> /// 创建预支付交易单 /// </summary> private UnifiedorderResult CreatePrePayOrder(TenPayV3Type payType, string orderNo, int amount, string body, string ip, string openId, string productId, string attach) { string nonceStr = String2.GetGuid(); string appId = JsApiAppId; string mchId = JsApiMchId; string key = JsApiKey; if (payType == TenPayV3Type.APP) { appId = AppAppId; mchId = AppMchId; key = AppKey; } var param = new TenPayV3UnifiedorderRequestData(appId, mchId, body, orderNo, amount, ip, NotifyUrl, payType, openId, key, nonceStr, productId: productId, attach: attach); var order = TenPayV3.Unifiedorder(param); return(order); }
private static readonly string NotifyUrl = WxPayConfig.NotifyUrl; //异步回调地址 /// <summary> /// 统一下单 /// </summary> /// <param name="body"></param> /// <param name="detail"></param> /// <param name="totalFee"></param> /// <param name="outTradeNo"></param> /// <param name="spbillCreateIp"></param> /// <param name="attach"></param> /// <returns></returns> public static Hashtable UnifiedOrder(string body, string detail, string totalFee, string outTradeNo, string spbillCreateIp, string attach) { TenPayV3UnifiedorderRequestData tenPayData = new TenPayV3UnifiedorderRequestData(AppId, MchId, body, outTradeNo, (totalFee.ToDecimal() * 100).ToString("0").ToInt32(), spbillCreateIp, NotifyUrl, TenPayV3Type.APP, "", Key, Guid.NewGuid().ToString().Replace("-", ""), "WEB", null, DateTime.Now.AddMinutes(30), detail, attach); UnifiedorderResult result = TenPayV3.Unifiedorder(tenPayData); RequestHandler requestHandler = new RequestHandler(); requestHandler.SetParameter("appid", result.appid); requestHandler.SetParameter("partnerid", result.mch_id); requestHandler.SetParameter("prepayid", result.prepay_id); requestHandler.SetParameter("package", "Sign=WXPay"); requestHandler.SetParameter("noncestr", result.nonce_str); requestHandler.SetParameter("timestamp", System.DateTimeHelper.ConvertDateTimeInt(DateTime.Now).ToString()); requestHandler.SetParameter("sign", requestHandler.CreateMd5Sign("key", Key)); Hashtable request = requestHandler.GetAllParameters(); return(request); }
public WxChatPayResult Pay(decimal amount, string openID, string title, out string orderID) { var m = mpSetting.Value; var price = Convert.ToInt32(amount * 100); orderID = TenPayV3Util.BuildDailyRandomStr(32); //var amount = 1; //var openid = "ohYxb0-EBw7Vr2_H5WhqJRW6k62A"; var param = new TenPayV3UnifiedorderRequestData( m.ParentAppID, m.ParentMchID, m.AppID, m.MchID, title, orderID, price, "127.0.0.1", m.NotifyUrl, TenPayV3Type.JSAPI, "", openID, m.Key, TenPayV3Util.GetNoncestr()); var q = TenPayV3.Unifiedorder(param); if (q.IsResultCodeSuccess() && q.IsReturnCodeSuccess()) { var re = new WxChatPayResult(m.Key, q.appid, q.prepay_id); return(re); } return(null); }
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 jssdkUiPackage = JSSDKHelper.GetJsSdkUiPackage(Service.Config.AppId, Service.Config.AppSecret, Request.Url.AbsoluteUri); var nonceStr = jssdkUiPackage.NonceStr; var timeStamp = jssdkUiPackage.Timestamp; 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, JsSdkUiPackage = jssdkUiPackage, Package = package, PaySign = paySign }; //临时记录订单信息,留给退款申请接口测试使用 Session["BillNo"] = sp_billno;//储存在数据库 Session["BillFee"] = price; return(View(vd)); }
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); }
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 ApiResult GetWxInfo(int money) { spbillCreateIp = Tool.GetIP();//HttpContext.Current.Request.UserHostAddress; notifyUrl = ApiHost + "/api/Recharge/WxNotify"; nonceStr = Guid.NewGuid().ToString("N"); LogHelper.Info("notifyUrl=" + notifyUrl); var result = new ApiResult <WXResDto>(); WXResDto model = new WXResDto(); model.OrderId = GetRandom(); if (_service.AddComeOutRecord(model.OrderId, money, 1, (int)UserInfo.UserId)) { DateTime start = DateTime.Now, end = DateTime.Now.AddMinutes(15); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(appid , mchid, body, model.OrderId, money * 100 , spbillCreateIp, notifyUrl, tradeType , null, key, nonceStr, null, start, end); var resultWx = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口 model.AppId = appid; model.MchId = mchid; model.Package = "Sign=WXPay"; model.PrepayId = resultWx.prepay_id; model.CreatedOn = GetTimeStamp(); model.NonceStr = resultWx.nonce_str; model.Sign = GetAppPaySign(appid, model.CreatedOn, model.NonceStr, model.Package, key, mchid, model.PrepayId); model.TradeType = resultWx.trade_type; result.Data = model; return(result); } else { return(new ApiResult(10000, "生成订单失败")); } }
/// <summary> /// 微信预支付 /// </summary> /// <param name="attach"></param> /// <param name="body"></param> /// <param name="openid"></param> /// <param name="price"></param> /// <param name="orderNum"></param> /// <returns></returns> public static WechatOrderInfo PayInfo(string attach, string body, string openid, string price, string orderNum = "1833431773763549") { RequestHandler requestHandler = new RequestHandler(HttpContext.Current); //微信分配的公众账号ID(企业号corpid即为此appId) requestHandler.SetParameter("appid", tenPayV3Info.AppId); //附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据 requestHandler.SetParameter("attach", attach); //商品或支付单简要描述 requestHandler.SetParameter("body", body); //微信支付分配的商户号 requestHandler.SetParameter("mch_id", tenPayV3Info.MchId); //随机字符串,不长于32位。 requestHandler.SetParameter("nonce_str", TenPayUtil.GetNoncestr()); //接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。 requestHandler.SetParameter("notify_url", tenPayV3Info.TenPayV3Notify); //trade_type=JSAPI,此参数必传,用户在商户公众号appid下的唯一标识。 requestHandler.SetParameter("openid", openid); //商户系统内部的订单号,32个字符内、可包含字母,自己生成 requestHandler.SetParameter("out_trade_no", orderNum); //APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。 requestHandler.SetParameter("spbill_create_ip", "127.0.0.1"); //订单总金额,单位为分,做过银联支付的朋友应该知道,代表金额为12位,末位分分 requestHandler.SetParameter("total_fee", price); //取值如下:JSAPI,NATIVE,APP,我们这里使用JSAPI requestHandler.SetParameter("trade_type", "JSAPI"); //设置KEY requestHandler.SetKey(tenPayV3Info.Key); requestHandler.CreateMd5Sign(); requestHandler.GetRequestURL(); requestHandler.CreateSHA1Sign(); string data = requestHandler.ParseXML(); requestHandler.GetDebugInfo(); //获取并返回预支付XML信息 return(XmlHelper.XmlDeserialize <WechatOrderInfo>(TenPayV3.Unifiedorder(data))); }
private static string GetPrepayOrder(HttpRequest req) { var nonceStr = TenPayV3Util.GetNoncestr(); var unifiedOrder = new RequestHandler(null); unifiedOrder.Init(); QRConnectAccessTokenResult oauth2AccessToken = (QRConnectAccessTokenResult)HttpContext.Current.Session["weixinOauth2AccessToken"]; if (oauth2AccessToken == null) { throw new SystemException("请先通过微信Oauth2对x5外面授权,然后才能发起支付"); } unifiedOrder.SetParameter("openid", oauth2AccessToken.openid); unifiedOrder.SetParameter("appid", ConfigHelper.AppConfig["appId"]); unifiedOrder.SetParameter("body", req.Params["body"]); unifiedOrder.SetParameter("mch_id", req.Params["mchId"]); unifiedOrder.SetParameter("notify_url", req.Params["notifyUrl"]); unifiedOrder.SetParameter("out_trade_no", req.Params["outTradeNo"]); unifiedOrder.SetParameter("spbill_create_ip", req.UserHostAddress); unifiedOrder.SetParameter("total_fee", req.Params["totalFee"]); unifiedOrder.SetParameter("nonce_str", nonceStr); unifiedOrder.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString()); var sign = unifiedOrder.CreateMd5Sign("key", ConfigHelper.AppConfig["appKey"]); unifiedOrder.SetParameter("sign", sign); var data = unifiedOrder.ParseXML(); var result = TenPayV3.Unifiedorder(data); var xElement = XDocument.Parse(result).Element("xml"); var element = xElement?.Element("prepay_id"); return(element?.Value); }
#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) }); }
public string GetRequestUrl(string returnUrl, string notifyUrl, string orderId, decimal totalFee, string productInfo, string openId = null) { string empty = string.Empty; Config config = Utility <Config> .GetConfig(base.WorkDirectory); if (string.IsNullOrEmpty(config.AppId)) { throw new PluginException("未设置AppId"); } if (string.IsNullOrEmpty(config.MCHID)) { throw new PluginException("未设置MCHID"); } string noncestr = TenPayUtil.GetNoncestr(); string str = DateTime.Now.ToString("yyyyMMddHHmmss"); RequestHandler requestHandler = new RequestHandler(); requestHandler.SetParameter("appid", config.AppId); requestHandler.SetParameter("mch_id", config.MCHID); requestHandler.SetParameter("device_info", string.Empty); requestHandler.SetParameter("nonce_str", noncestr); requestHandler.SetParameter("body", productInfo); requestHandler.SetParameter("attach", string.Empty); requestHandler.SetParameter("out_trade_no", orderId); int num = (int)(totalFee * new decimal(100)); requestHandler.SetParameter("total_fee", num.ToString()); requestHandler.SetParameter("spbill_create_ip", "222.240.184.122"); requestHandler.SetParameter("time_start", str); requestHandler.SetParameter("time_expire", string.Empty); requestHandler.SetParameter("goods_tag", string.Empty); requestHandler.SetParameter("notify_url", notifyUrl); requestHandler.SetParameter("trade_type", "NATIVE"); requestHandler.SetParameter("openid", openId); requestHandler.SetParameter("product_id", orderId); string str1 = requestHandler.CreateMd5Sign("key", config.Key); requestHandler.SetParameter("sign", str1); string str2 = requestHandler.ParseXML(); XDocument xDocument = XDocument.Parse(TenPayV3.Unifiedorder(str2)); if (xDocument == null) { throw new PluginException(string.Concat("调用统一支付接口(Native)时出错:", str2)); } XElement xElement = xDocument.Element("xml").Element("return_code"); XElement xElement1 = xDocument.Element("xml").Element("return_msg"); if (xElement == null) { throw new PluginException("调用统一支付接口(Native)时,返回参数异常"); } if (!(xElement.Value == "SUCCESS")) { throw new PluginException(string.Concat("调用统一支付接口(Native)时,接口返回异常:", xElement1.Value)); } xElement1 = xDocument.Element("xml").Element("result_code"); XElement xElement2 = xDocument.Element("xml").Element("err_code_des"); if (!(xElement1.Value == "SUCCESS")) { throw new PluginException(string.Concat("调用统一支付接口(Native)时,接口返回异常:", xElement2.Value)); } xElement1 = xDocument.Element("xml").Element("code_url"); empty = xElement1.Value; return(empty); }
public string GetRequestUrl(string returnUrl, string notifyUrl, string orderId, decimal totalFee, string productInfo, string openId = null) { string timeStamp = ""; string nonceStr = ""; string paySign = ""; string sp_billno = orderId; //当前时间 yyyyMMdd string date = DateTime.Now.ToString("yyyyMMdd"); //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(); //初始化 packageReqHandler.Init(); //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/); timeStamp = TenPayUtil.GetTimestamp(); nonceStr = TenPayUtil.GetNoncestr(); Config config = Utility <Config> .GetConfig(WorkDirectory); //设置package订单参数 packageReqHandler.SetParameter("appid", config.AppId); //公众账号ID packageReqHandler.SetParameter("mch_id", config.MCHID); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", productInfo); packageReqHandler.SetParameter("out_trade_no", sp_billno); //商家订单号 packageReqHandler.SetParameter("total_fee", ((int)(totalFee * 100)).ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", _httpContextAccessor.HttpContext.Features.Get <IHttpConnectionFeature>().RemoteIpAddress.ToString()); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", notifyUrl); //接收财付通通知的URL packageReqHandler.SetParameter("trade_type", "JSAPI"); //交易类型 packageReqHandler.SetParameter("openid", openId); //用户的openId string sign = packageReqHandler.CreateMd5Sign("key", config.Key); packageReqHandler.SetParameter("sign", sign); //签名 string data = packageReqHandler.ParseXML(); var result = TenPayV3.Unifiedorder(data); var res = XDocument.Parse(result); if (res == null) { throw new ApplicationException("调用统一支付出错:请求内容:" + data); } string returnCode = res.Element("xml").Element("return_code").Value; if (returnCode == "FAIL")//失败 { throw new ApplicationException("预支付失败:" + res.Element("xml").Element("return_msg").Value); } string resultCode = res.Element("xml").Element("result_code").Value; if (resultCode == "FAIL") { throw new ApplicationException("预支付失败:" + res.Element("xml").Element("err_code_des").Value); } string prepayId = res.Element("xml").Element("prepay_id").Value; //设置支付参数 RequestHandler paySignReqHandler = new RequestHandler(); paySignReqHandler.SetParameter("appId", config.AppId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId)); paySignReqHandler.SetParameter("signType", "MD5"); paySign = paySignReqHandler.CreateMd5Sign("key", config.Key); string js = string.Format("WeixinJSBridge.invoke('getBrandWCPayRequest', {{" + "'appId': '{0}'," + "'timeStamp': '{1}'," + "'nonceStr': '{2}'," + "'package': '{3}'," + "'signType': 'MD5'," + "'paySign': '{4}'" + "}}, function (res) {{" + "if (res.err_msg == 'get_brand_wcpay_request:ok') {{" + "location.href='" + returnUrl + "'" + "}}else alert('支付失败!')" + "}});", config.AppId, timeStamp, nonceStr, string.Format("prepay_id={0}", prepayId), paySign); return(string.Format("javascript:{0}", js)); }
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)); } }
public string GetRequestUrl_App(string returnUrl, string notifyUrl, string orderId, decimal totalFee, string productInfo, string openId = null) { string timeStamp = ""; string nonceStr = ""; string paySign = ""; string sp_billno = orderId; //当前时间 yyyyMMdd string date = DateTime.Now.ToString("yyyyMMdd"); //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(); //初始化 packageReqHandler.Init(); //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/); timeStamp = TenPayUtil.GetTimestamp(); nonceStr = TenPayUtil.GetNoncestr(); Config config = Utility <Config> .GetConfig(WorkDirectory); //设置package订单参数 packageReqHandler.SetParameter("appid", config.AppId); //公众账号ID packageReqHandler.SetParameter("mch_id", config.MCHID); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", productInfo); packageReqHandler.SetParameter("out_trade_no", sp_billno); //商家订单号 packageReqHandler.SetParameter("total_fee", ((int)(totalFee * 100)).ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", _httpContextAccessor.HttpContext.Features.Get <IHttpConnectionFeature>().RemoteIpAddress.ToString()); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", notifyUrl); //接收财付通通知的URL packageReqHandler.SetParameter("trade_type", "APP"); //交易类型 packageReqHandler.SetParameter("openid", string.IsNullOrWhiteSpace(openId) ? "" : openId); //用户的openId string sign = packageReqHandler.CreateMd5Sign("key", config.Key); packageReqHandler.SetParameter("sign", sign); //签名 string data = packageReqHandler.ParseXML(); //Core.Log.Debug("data=" + data); var result = TenPayV3.Unifiedorder(data); //Core.Log.Debug("result=" + result); var res = XDocument.Parse(result); if (res == null) { throw new ApplicationException("调用统一支付出错:请求内容:" + data); } string returnCode = res.Element("xml").Element("return_code").Value; if (returnCode == "FAIL")//失败 { throw new ApplicationException("预支付失败:" + res.Element("xml").Element("return_msg").Value); } string resultCode = res.Element("xml").Element("result_code").Value; if (resultCode == "FAIL") { throw new ApplicationException("预支付失败:" + res.Element("xml").Element("err_code_des").Value); } string prepayId = res.Element("xml").Element("prepay_id").Value; //设置支付参数 RequestHandler paySignReqHandler = new RequestHandler(); paySignReqHandler.SetParameter("appid", config.AppId); paySignReqHandler.SetParameter("partnerid", config.MCHID); paySignReqHandler.SetParameter("prepayid", prepayId); paySignReqHandler.SetParameter("timestamp", timeStamp); paySignReqHandler.SetParameter("noncestr", nonceStr); paySignReqHandler.SetParameter("package", "Sign=WXPay"); paySign = paySignReqHandler.CreateMd5Sign("key", config.Key); paySignReqHandler.SetParameter("sign", paySign); var hashtable = paySignReqHandler.GetAllParameters(); System.Text.StringBuilder strBuilder = new System.Text.StringBuilder(); strBuilder.Append("{"); foreach (var p in hashtable.Keys) { if (p.ToString() == "timestamp") { strBuilder.Append("\"" + p + "\":" + hashtable[p] + ""); } else { strBuilder.Append("\"" + p + "\":\"" + hashtable[p] + "\""); } strBuilder.Append(","); } string resultStr = strBuilder.ToString().TrimEnd(',') + "}"; return(resultStr); }
/// <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 }); }
/// <summary> /// 添加信息 /// </summary> /// <param name="context"></param> protected void AddRoomInfo(HttpContext context) { var uname = WebConfigurationManager.AppSettings["zcname"];//名称 string appId = WebConfigurationManager.AppSettings["WeixinPay_AppId"].ToString(); var totalprrc = context.Request.Params["total"]; var unnum = Convert.ToInt32(context.Request.Params["tnum"]); if (context.Request.Cookies["ZCWebDomain"] == null || string.IsNullOrEmpty(context.Request.Cookies["ZCWebDomain"]["useropid"])) { string jsonstrlist = JsonHelper.GetJsonString(new jsonResult { code = "用户数据不正确!", result = null, count = 2 }); context.Response.Write(jsonstrlist); } else { var tmpopenid = context.Request.Cookies["ZCWebDomain"]["useropid"]; var phone = context.Request.Params["phone"]; var name = context.Request.Params["name"]; string timeStamp = ""; string nonceStr = ""; string packageValue = ""; string paySign = ""; string tmpOrderId = string.Empty; using (WXDBEntities db = new WXDBEntities()) { int tmptotals = Convert.ToInt32(Convert.ToDouble(totalprrc) * 100);//总价格 var tmodel = db.Oders.Where(s => s.Mobile.Equals(phone) && s.OrderStatus.Equals(1)).FirstOrDefault(); var tmotol = 0; if (tmodel != null) { if (tmodel.Extent1.Equals(name)) { var ttinfo = db.Oders.Where(s => s.Mobile.Equals(phone) && s.OrderStatus.Equals(1)).FirstOrDefault(); if (ttinfo != null) { tmotol = db.Oders.Where(s => s.Mobile.Equals(phone) && s.OrderStatus.Equals(1)).Sum(s => s.Number); } if ((unnum + tmotol) > 20) { string jsonstrlist = JsonHelper.GetJsonString(new jsonResult { code = "你购买的众筹份数已超额,请重新选择数量", result = null, count = 3 }); context.Response.Write(jsonstrlist); } else { //追加购买 try { Oders order = new Oders() { Title = uname, OrderId = WebConn.TenPayInfo.PartnerId + DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(4), Number = unnum, Mobile = phone, Soucre = "12", //房间单价格 Remark = WebConfigurationManager.AppSettings["zcname"], //所选房间 AddTime = DateTime.Now, UpdateTime = DateTime.Now, OrderStatus = 0, Status = 0, Orders = 0, Extent1 = name, Extent2 = "", AddUser = tmpopenid,//订单人 UpdateUser = "", CheckTime = DateTime.Now, CheckoutTime = DateTime.Now, Totals = tmptotals }; db.Oders.AddObject(order); db.SaveChanges(); //设置输出参数 //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(context); //初始化 packageReqHandler.Init(); packageReqHandler.SetKey(WebConfigurationManager.AppSettings["WeixinPay_Key"]); timeStamp = TenPayV3Util.GetTimestamp(); nonceStr = TenPayV3Util.GetNoncestr().ToLower(); //设置package订单参数 packageReqHandler.SetParameter("appid", appId); //公众账号ID packageReqHandler.SetParameter("mch_id", WebConfigurationManager.AppSettings["WeixinPay_PartnerId"]); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", order.Remark); //商品描述 packageReqHandler.SetParameter("out_trade_no", order.OrderId); //商家订单号 packageReqHandler.SetParameter("total_fee", order.Totals.ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", context.Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", WebConfigurationManager.AppSettings["WeixinPay_TenpayNotify"]); //通知的URL packageReqHandler.SetParameter("trade_type", "JSAPI"); //交易类型 packageReqHandler.SetParameter("openid", order.AddUser); //用户Openid //获取package包 string sign = packageReqHandler.CreateMd5Sign("key", WebConfigurationManager.AppSettings["WeixinPay_Key"]); packageReqHandler.SetParameter("sign", sign); //sign签名 string data = packageReqHandler.ParseXML(); var result = TenPayV3.Unifiedorder(data); var res = XDocument.Parse(result); string prepayId = res.Element("xml").Element("prepay_id").Value; packageValue = string.Format("prepay_id={0}", prepayId); //设置支付参数 RequestHandler paySignReqHandler = new RequestHandler(context); paySignReqHandler.SetParameter("appId", appId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId)); paySignReqHandler.SetParameter("signType", "MD5"); paySign = paySignReqHandler.CreateMd5Sign("key", WebConfigurationManager.AppSettings["WeixinPay_Key"]);// List <object> listDesc = new List <object>(); listDesc.Add(new { appId = appId, timeStamp = timeStamp, nonceStr = nonceStr, package = packageValue, paySign = paySign, orderid = order.OrderId }); string jsonstrlist = JsonHelper.GetJsonString(new jsonResult { code = "succ", result = listDesc, count = listDesc.Count }); context.Response.Write(jsonstrlist); } catch (Exception ex) { string jsonstrlist = JsonHelper.GetJsonString(new jsonResult { code = ex.Message, result = "", count = 0 }); context.Response.Write(jsonstrlist); } } } else { string jsonstrlist = JsonHelper.GetJsonString(new jsonResult { code = "用户数据不匹配,不能进行购买!", result = null, count = 3 }); context.Response.Write(jsonstrlist); } } else { //新的购买 try { Oders order = new Oders() { Title = uname, OrderId = WebConn.TenPayInfo.PartnerId + DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(4), Number = unnum, Mobile = phone, Soucre = "12", //房间单价格 Remark = WebConfigurationManager.AppSettings["zcname"], //所选房间 AddTime = DateTime.Now, UpdateTime = DateTime.Now, OrderStatus = 0, Status = 0, Orders = 0, Extent1 = name, Extent2 = "", AddUser = tmpopenid,//订单人 UpdateUser = "", CheckTime = DateTime.Now, CheckoutTime = DateTime.Now, Totals = tmptotals }; db.Oders.AddObject(order); db.SaveChanges(); //设置输出参数 //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(context); //初始化 packageReqHandler.Init(); packageReqHandler.SetKey(WebConfigurationManager.AppSettings["WeixinPay_Key"]); timeStamp = TenPayV3Util.GetTimestamp(); nonceStr = TenPayV3Util.GetNoncestr().ToLower(); //设置package订单参数 packageReqHandler.SetParameter("appid", appId); //公众账号ID packageReqHandler.SetParameter("mch_id", WebConfigurationManager.AppSettings["WeixinPay_PartnerId"]); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", order.Remark); //商品描述 packageReqHandler.SetParameter("out_trade_no", order.OrderId); //商家订单号 packageReqHandler.SetParameter("total_fee", order.Totals.ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", context.Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", WebConfigurationManager.AppSettings["WeixinPay_TenpayNotify"]); //通知的URL packageReqHandler.SetParameter("trade_type", "JSAPI"); //交易类型 packageReqHandler.SetParameter("openid", order.AddUser); //用户Openid //获取package包 string sign = packageReqHandler.CreateMd5Sign("key", WebConfigurationManager.AppSettings["WeixinPay_Key"]); packageReqHandler.SetParameter("sign", sign); //sign签名 string data = packageReqHandler.ParseXML(); var result = TenPayV3.Unifiedorder(data); var res = XDocument.Parse(result); string prepayId = res.Element("xml").Element("prepay_id").Value; packageValue = string.Format("prepay_id={0}", prepayId); //设置支付参数 RequestHandler paySignReqHandler = new RequestHandler(context); paySignReqHandler.SetParameter("appId", appId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId)); paySignReqHandler.SetParameter("signType", "MD5"); paySign = paySignReqHandler.CreateMd5Sign("key", WebConfigurationManager.AppSettings["WeixinPay_Key"]);// List <object> listDesc = new List <object>(); listDesc.Add(new { appId = appId, timeStamp = timeStamp, nonceStr = nonceStr, package = packageValue, paySign = paySign, orderid = order.OrderId }); string jsonstrlist = JsonHelper.GetJsonString(new jsonResult { code = "succ", result = listDesc, count = listDesc.Count }); context.Response.Write(jsonstrlist); } catch (Exception ex) { string jsonstrlist = JsonHelper.GetJsonString(new jsonResult { code = ex.Message, result = ex.Message, count = 0 }); context.Response.Write(jsonstrlist); } } } } }
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 = SystemTime.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", HttpContext.UserHostAddress()?.ToString()); //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, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPay.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 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> /// 调用商户服务器支付统一下单接口,进行预支付 /// </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 ApiResult GetWxPayJsApiParam([FromBody] PayViewModel payModel) { var orderId = payModel.OrderId; if (orderId.Equals(Guid.Empty)) { throw new WebApiInnerException("0001", "订单Id不合法"); } var order = _currencyService.GetSingleById <Order>(orderId); if (order == null) { throw new WebApiInnerException("0002", "订单数据不存在"); } if (order.PayStatus != PayStatus.Unpaid) { throw new WebApiInnerException("0003", "订单状态不合理,无法支付"); } var payment = _paymentService.LoadPayment(PaymentType.WeiXin.ToString()); if (payment == null || !payment.Enabled) { throw new WebApiInnerException("0004", "支付方式不合法或已停用"); } var paymentDispatcher = HostConstObject.Container.ResolveNamed <IPaymentDispatcher>(payment.Code.ToLower()); if (paymentDispatcher == null) { throw new WebApiInnerException("0005", "支付方式不合法"); } var oath = _currencyService.GetSingleByConditon <UserOAuth>(ua => ua.MemberId == order.MemberId && ua.OAuthType == OAuthType.WeiXin); if (oath == null) { throw new WebApiInnerException("0008", "未绑定微信号,无法支付"); } var result = new ApiResult(); try { var routeParas = new RouteValueDictionary { { "area", PaymentProcessModule.Area }, { "controller", "Receive" }, { "action", "AsyncReturn" }, { "paymentCode", payment.Code } }; var notifyUrl = HostConstObject.HostUrl + _urlHelper.RouteUrl(routeParas); if (payModel.UseBalance == 1) { //使用余额付款 #region using (TransactionScope scope = new TransactionScope()) { var cashWallet = _walletService.GetWalletByMemberId(order.MemberId, Wallet.Models.WalletType.Cash); if (cashWallet != null && cashWallet.Available > 0) { if (cashWallet.Available > order.PayFee) { string error; _walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash, order.PayFee, "支付订单" + order.OrderNo, out error); if (string.IsNullOrWhiteSpace(error)) { order.BalancePay = order.PayFee; order.OrderStatus = OrderStatus.WaitingForDelivery; order.PayStatus = PayStatus.Paid; order.PayTime = DateTime.Now; var balancePayment = _paymentService.LoadPayment(PaymentType.Balance.ToString()); order.PaymentId = balancePayment.Id; order.PaymentName = balancePayment.Name; _orderService.ChangeOrderStatus(order.Id, order.OrderStatus, order.PayStatus); _currencyService.Update(order); } } else { string error; _walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash, cashWallet.Available, "支付订单" + order.OrderNo, out error); if (string.IsNullOrWhiteSpace(error)) { order.UnpayFee = order.PayFee - cashWallet.Available; order.BalancePay = cashWallet.Available; _currencyService.Update(order); } } } scope.Complete(); } #endregion } var payLog = new PayLog { Id = KeyGenerator.GetGuidKey(), TransactionNo = $"{order.OrderNo}{KeyGenerator.GenerateRandom(1000, 1)}", OrderId = order.Id, OrderNo = order.OrderNo, OrderAmount = order.PayFee,//UnpayFee PaymentId = payment.Id, PaymentName = payment.Name, CreateTime = DateTime.Now, LogStatus = LogStatus.Unpaid }; if (!_currencyService.Create(payLog)) { throw new WebApiInnerException("0007", "生成支付流水失败"); } string timeStamp = ""; string nonceStr = ""; string paySign = ""; var appId = _configService.Get <WeiXinConfig>().AppId; var mchId = _configService.Get <WeiXinConfig>().MchId; var key = _configService.Get <WeiXinConfig>().Key; //创建支付应答对象 WxRequestHandler packageReqHandler = new WxRequestHandler(null); //初始化 packageReqHandler.Init(); timeStamp = TenPayV3Util.GetTimestamp(); nonceStr = TenPayV3Util.GetNoncestr(); //设置package订单参数 packageReqHandler.SetParameter("appid", appId); //公众账号ID packageReqHandler.SetParameter("mch_id", mchId); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", order.OrderNo); //商品信息 packageReqHandler.SetParameter("out_trade_no", payLog.TransactionNo); //商家订单号 packageReqHandler.SetParameter("total_fee", Convert.ToInt32(order.PayFee * 100).ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", "127.0.0.1"); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", notifyUrl); //接收财付通通知的URL packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString()); //交易类型 packageReqHandler.SetParameter("openid", oath.OAuthId); //用户的openId string sign = packageReqHandler.CreateMd5Sign("key", key); packageReqHandler.SetParameter("sign", sign); //签名 string data = packageReqHandler.ParseXML(); var orderResult = TenPayV3.Unifiedorder(data); var res = XDocument.Parse(orderResult); var prepayXml = res.Element("xml").Element("prepay_id"); if (prepayXml == null) { Logger.Error("生成微信预付单失败:" + res.ToString()); throw new WebApiInnerException("0009", "生成微信预付单失败"); //res.Element("xml").Element("return_msg").Value; } string prepayId = prepayXml.Value; //设置支付参数 WxRequestHandler paySignReqHandler = new WxRequestHandler(null); paySignReqHandler.SetParameter("appId", appId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", $"prepay_id={prepayId}"); paySignReqHandler.SetParameter("signType", "MD5"); paySign = paySignReqHandler.CreateMd5Sign("key", key); result.SetData(new { appId, timeStamp, nonceStr, package = $"prepay_id={prepayId}", paySign, signType = "MD5", orderid = order.Id, orderType = order.ModuleKey, orderStatus = order.OrderStatus, payStatus = order.PayStatus }); } catch (Exception ex) { Logger.Error(ex, "获取订单支付签名数据失败"); throw new WebApiInnerException("0006", "生成签名数据出现异常"); } return(result); }
public ActionResult paymentProcess(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 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)); } }
public ActionResult JsApi(string code, string state) { if (string.IsNullOrEmpty(code)) { return(Content("您拒绝了授权!")); } if (!state.Contains("|")) { //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下 //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证 return(Content("验证失败!请从正规途径进入!1001")); } //获取产品信息 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 timeStamp = ""; string nonceStr = ""; string paySign = ""; string sp_billno = Request["order_no"]; //当前时间 yyyyMMdd string date = DateTime.Now.ToString("yyyyMMdd"); if (null == sp_billno) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28); } else { sp_billno = Request["order_no"].ToString(); } //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(null); //初始化 packageReqHandler.Init(); timeStamp = TenPayV3Util.GetTimestamp(); nonceStr = TenPayV3Util.GetNoncestr(); //设置package订单参数 packageReqHandler.SetParameter("appid", TenPayV3Info.AppId); //公众账号ID packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", product == null ? "test" : product.Name); //商品信息 packageReqHandler.SetParameter("out_trade_no", sp_billno); //商家订单号 packageReqHandler.SetParameter("total_fee", product == null ? "100" : (product.Price * 100).ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify); //接收财付通通知的URL packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString()); //交易类型 packageReqHandler.SetParameter("openid", openIdResult.openid); //用户的openId string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); packageReqHandler.SetParameter("sign", sign); //签名 string data = packageReqHandler.ParseXML(); var result = TenPayV3.Unifiedorder(data); var res = XDocument.Parse(result); string prepayId = res.Element("xml").Element("prepay_id").Value; //设置支付参数 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}", prepayId)); paySignReqHandler.SetParameter("signType", "MD5"); paySign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); ViewData["appId"] = TenPayV3Info.AppId; ViewData["timeStamp"] = timeStamp; ViewData["nonceStr"] = nonceStr; ViewData["package"] = string.Format("prepay_id={0}", prepayId); ViewData["paySign"] = paySign; return(View()); }
/// <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 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)); } }