示例#1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            order_type = Request.QueryString["order_type"];
            order_dd   = Request.QueryString["Order_dd"];
            BLL.HG.Hg_list order_T = new BLL.HG.Hg_list();
            if (order_type == "new")
            {
                Model.HG.A_HG_new_order model = order_T.getorder(order_dd);
                string timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";
                //创建支付应答对象
                Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
                //初始化
                packageReqHandler.Init();
                litMoney  = double.Parse(model.total);
                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr  = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", "wx172ece37e2ed2939");                                                                  //公众账号ID
                packageReqHandler.SetParameter("mch_id", "1403543902");                                                                         //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
                packageReqHandler.SetParameter("body", model.Name_ + "服务");                                                                     //商品信息
                packageReqHandler.SetParameter("out_trade_no", order_dd);                                                                       //商家订单号
                packageReqHandler.SetParameter("total_fee", ((double.Parse(model.total)) * 100).ToString());                                    //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                                                    //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + 44 + "|" + order_dd); //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
                packageReqHandler.SetParameter("openid", model.Openid_);                                                                        //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                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", "wx172ece37e2ed2939");
                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", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                payaddid        = "";
                paytimeStamp    = timeStamp;
                paynonceStr     = nonceStr;
                paypackageValue = string.Format("prepay_id={0}", prepayId);
                paypaySign      = paySign;
                litDate         = DateTime.Now.ToString();
                oreder_name     = model.Name_ + "服务预约";
            }


            else
            {
                hg_number = int.Parse(Request.QueryString["kkl"]);
                Model.HG.HG_order model = order_T.Getorder(order_dd);

                string timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";
                //创建支付应答对象
                Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
                //初始化
                packageReqHandler.Init();
                litMoney  = model.Total;
                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr  = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", "wx172ece37e2ed2939");                                                                  //公众账号ID
                packageReqHandler.SetParameter("mch_id", "1403543902");                                                                         //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
                packageReqHandler.SetParameter("body", model.By_name + "护理");                                                                   //商品信息
                packageReqHandler.SetParameter("out_trade_no", order_dd);                                                                       //商家订单号
                packageReqHandler.SetParameter("total_fee", ((model.Total) * 100).ToString());                                                  //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                                                    //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + 44 + "|" + order_dd); //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
                packageReqHandler.SetParameter("openid", model.Openid);                                                                         //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                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", "wx172ece37e2ed2939");
                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", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                payaddid        = "";
                paytimeStamp    = timeStamp;
                paynonceStr     = nonceStr;
                paypackageValue = string.Format("prepay_id={0}", prepayId);
                paypaySign      = paySign;
                litDate         = DateTime.Now.ToString();
                oreder_name     = model.By_name + "护理预约";
            }
        }
        /// <summary>
        /// 退款申请接口
        /// </summary>
        /// <returns></returns>
        public ActionResult Refund()
        {
            string nonceStr = TenPayV3Util.GetNoncestr();

            string outTradeNo  = (string)(Session["BillNo"]);
            string outRefundNo = "OutRefunNo-" + DateTime.Now.Ticks;
            int    totalFee    = (int)(Session["BillFee"]);
            int    refundFee   = totalFee;
            string opUserId    = TenPayV3Info.MchId;
            var    dataInfo    = new TenPayV3RefundRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, TenPayV3Info.Key,
                                                               null, nonceStr, null, outTradeNo, outRefundNo, totalFee, refundFee, opUserId, null);
            var cert     = @"D:\cert\apiclient_cert_SenparcRobot.p12"; //根据自己的证书位置修改
            var password = TenPayV3Info.MchId;                         //默认为商户号,建议修改
            var result   = TenPayV3.Refund(dataInfo, cert, password);

            return(Content(string.Format("退款结果:{0} {1}。您可以刷新当前页面查看最新结果。", result.result_code, result.err_code_des)));

            //return Json(result, JsonRequestBehavior.AllowGet);

            #region 原始方法

            //RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		 //公众账号ID
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);	     //商户号
            //packageReqHandler.SetParameter("out_trade_no", "124138540220170502163706139412"); //填入商家订单号
            ////packageReqHandler.SetParameter("out_refund_no", "");                //填入退款订单号
            //packageReqHandler.SetParameter("total_fee", "");                    //填入总金额
            //packageReqHandler.SetParameter("refund_fee", "100");                //填入退款金额
            //packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId);   //操作员Id,默认就是商户号
            //packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);	                    //签名
            ////退款需要post的数据
            //string data = packageReqHandler.ParseXML();

            ////退款接口地址
            //string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            ////本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            //string cert = @"D:\cert\apiclient_cert_SenparcRobot.p12";
            ////私钥(在安装证书时设置)
            //string password = TenPayV3Info.MchId;
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ////调用证书
            //X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            //#region 发起post请求
            //HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //webrequest.ClientCertificates.Add(cer);
            //webrequest.Method = "post";

            //byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            //webrequest.ContentLength = postdatabyte.Length;
            //Stream stream;
            //stream = webrequest.GetRequestStream();
            //stream.Write(postdatabyte, 0, postdatabyte.Length);
            //stream.Close();

            //HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            //StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            //string responseContent = streamReader.ReadToEnd();
            //#endregion

            //// var res = XDocument.Parse(responseContent);
            ////string openid = res.Element("xml").Element("out_refund_no").Value;
            //return Content("申请成功:<br>" + HttpUtility.RequestUtility.HtmlEncode(responseContent));

            #endregion
        }
示例#3
0
        public ActionResult NativeNotifyUrl()
        {
            ResponseHandler resHandler = new ResponseHandler(null);

            //返回给微信的请求
            RequestHandler res = new RequestHandler(null);

            string openId    = resHandler.GetParameter("openid");
            string productId = resHandler.GetParameter("product_id");

            if (openId == null || productId == null)
            {
                res.SetParameter("return_code", "FAIL");
                res.SetParameter("return_msg", "回调数据异常");
            }

            //创建支付应答对象
            //RequestHandler packageReqHandler = new RequestHandler(null);

            var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            var nonceStr  = TenPayV3Util.GetNoncestr();

            //创建请求统一订单接口参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);
            //packageReqHandler.SetParameter("nonce_str", nonceStr);
            //packageReqHandler.SetParameter("body", "test");
            //packageReqHandler.SetParameter("out_trade_no", sp_billno);
            //packageReqHandler.SetParameter("total_fee", "1");
            //packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);
            //packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);
            //packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString());
            //packageReqHandler.SetParameter("openid", openId);
            //packageReqHandler.SetParameter("product_id", productId);

            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);

            //string data = packageReqHandler.ParseXML();

            var xmlDataInfo = new TenPayV3RequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "test", sp_billno, 1, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, productId, 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 object GetWeixinPayOption()
        {
            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = DateTime.Now.ToString("yyyyMMddHHmmss") + TenPayV3Util.BuildRandomStr(28);


            RequestHandler packageReqHandler = new RequestHandler(null);

            packageReqHandler.Init();

            timeStamp = TenPayV3Util.GetTimestamp();
            nonceStr  = TenPayV3Util.GetNoncestr();


            var dict_package = new Dictionary <string, string> {
                { "appid", TenPayV3Info.AppId },
                { "mch_id", TenPayV3Info.MchId },
                { "nonce_str", nonceStr },
                { "body", "充值" },
                { "out_trade_no", sp_billno },
                { "total_fee", (0.01 * 100).ToString() },
                { "spbill_create_ip", System.Web.HttpContext.Current.Request.UserHostAddress },
                { "notify_url", TenPayV3Info.TenPayV3Notify },
                { "trade_type", "JSAPI" },
                { "openid", CurrentUser.openId }
            };

            dict_package.Keys.ToList().ForEach(key => packageReqHandler.SetParameter(key, dict_package[key]));

            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 = string.Empty;

            try
            {
                prepayId = res.Element("xml").Element("prepay_id").Value;
            }
            catch (Exception ex)
            {
                return(new ReturnMessage {
                    success = false, message = ex.Message, data = new { xml = res.ToString() }
                });
            }

            var cbll = new CoinBLL();

            cbll.SaveJsapiPackageRequest(prepayId, CurrentUser.userId, dict_package);

            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);

            var ViewData = new Dictionary <string, object> {
            };

            ViewData["appId"]     = TenPayV3Info.AppId;
            ViewData["timeStamp"] = timeStamp;
            ViewData["nonceStr"]  = nonceStr;
            ViewData["package"]   = string.Format("prepay_id={0}", prepayId);
            ViewData["paySign"]   = paySign;
            ViewData["signType"]  = "MD5";
            return(ViewData);
        }
        /// <summary>
        /// 退款申请接口
        /// </summary>
        /// <returns></returns>
        public ActionResult Refund()
        {
            try
            {
                WeixinTrace.SendCustomLog("进入退款流程", "1");

                string nonceStr = TenPayV3Util.GetNoncestr();

                string outTradeNo = HttpContext.Session.GetString("BillNo");

                WeixinTrace.SendCustomLog("进入退款流程", "2 outTradeNo:" + outTradeNo);

                string outRefundNo = "OutRefunNo-" + SystemTime.Now.Ticks;
                int    totalFee    = int.Parse(HttpContext.Session.GetString("BillFee"));
                int    refundFee   = totalFee;
                string opUserId    = TenPayV3Info.MchId;
                var    notifyUrl   = "https://sdk.weixin.senparc.com/TenPayV3/RefundNotifyUrl";
                var    dataInfo    = new TenPayV3RefundRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, TenPayV3Info.Key,
                                                                   null, nonceStr, null, outTradeNo, outRefundNo, totalFee, refundFee, opUserId, null, notifyUrl: notifyUrl);

                #region 旧方法
                //var cert = @"D:\cert\apiclient_cert_SenparcRobot.p12";//根据自己的证书位置修改
                //var password = TenPayV3Info.MchId;//默认为商户号,建议修改
                //var result = TenPayV3.Refund(dataInfo, cert, password);
                #endregion

                #region 新方法(Senparc.Weixin v6.4.4+)
                var result = TenPayV3.Refund(_serviceProvider, dataInfo);//证书地址、密码,在配置文件中设置,并在注册微信支付信息时自动记录
                #endregion

                WeixinTrace.SendCustomLog("进入退款流程", "3 Result:" + result.ToJson());
                ViewData["Message"] = $"退款结果:{result.result_code} {result.err_code_des}。您可以刷新当前页面查看最新结果。";
                return(View());
                //return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));

                throw;
            }

            #region 原始方法

            //RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		 //公众账号ID
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);	     //商户号
            //packageReqHandler.SetParameter("out_trade_no", "124138540220170502163706139412"); //填入商家订单号
            ////packageReqHandler.SetParameter("out_refund_no", "");                //填入退款订单号
            //packageReqHandler.SetParameter("total_fee", "");                    //填入总金额
            //packageReqHandler.SetParameter("refund_fee", "100");                //填入退款金额
            //packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId);   //操作员Id,默认就是商户号
            //packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);	                    //签名
            ////退款需要post的数据
            //string data = packageReqHandler.ParseXML();

            ////退款接口地址
            //string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            ////本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            //string cert = @"D:\cert\apiclient_cert_SenparcRobot.p12";
            ////私钥(在安装证书时设置)
            //string password = TenPayV3Info.MchId;
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ////调用证书
            //X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            //#region 发起post请求
            //HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //webrequest.ClientCertificates.Add(cer);
            //webrequest.Method = "post";

            //byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            //webrequest.ContentLength = postdatabyte.Length;
            //Stream stream;
            //stream = webrequest.GetRequestStream();
            //stream.Write(postdatabyte, 0, postdatabyte.Length);
            //stream.Close();

            //HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            //StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            //string responseContent = streamReader.ReadToEnd();
            //#endregion

            //// var res = XDocument.Parse(responseContent);
            ////string openid = res.Element("xml").Element("out_refund_no").Value;
            //return Content("申请成功:<br>" + HttpUtility.RequestUtility.HtmlEncode(responseContent));

            #endregion
        }
示例#6
0
        /// <summary>
        /// 调用微信支付,生成预支付交易ID:prepay_id
        /// </summary>
        /// <param name="param">微信支付参数</param>
        /// <returns></returns>
        public WxPayReturn Pay(WxPayParam param)
        {
            string       nonceStr  = TenPayV3Util.GetNoncestr();
            string       notifyUrl = string.Format(param.Domain + param.NotifyUrl);//通知地址,接收微信支付异步通知回调地址
            int          totalFee  = (int)(param.TotalFee * 100);
            TenPayV3Type tradeType = TenPayV3Type.JSAPI;

            switch (param.TradeType)
            {
            case TradeType.App:
                tradeType = TenPayV3Type.APP;
                break;

            case TradeType.JsApi:
                tradeType = TenPayV3Type.JSAPI;
                break;

            case TradeType.Native:
                tradeType = TenPayV3Type.NATIVE;
                break;
            }
            DateTime timeStart  = DateTime.Now;
            DateTime timeExpire = DateTime.Now.AddHours(0.5);
            //设置参数
            TenPayV3UnifiedorderRequestData requestData = new TenPayV3UnifiedorderRequestData(
                param.AppId,
                param.MchId,
                param.Body,
                param.OutTradeNo,
                totalFee,
                param.ServiceIpAddress,
                notifyUrl,
                tradeType,
                param.Openid,
                param.Key,
                nonceStr,
                param.DeviceInfo,
                timeStart,
                timeExpire,
                param.Detail,
                param.Attach,
                param.FeeType);
            var result = TenPayV3.Unifiedorder(requestData);

            LogHelper.Info(string.Format("生成预支付ID:{0}", JsonConvert.SerializeObject(result)));

            if (!result.IsReturnCodeSuccess())
            {
                throw new BaseException(result.return_msg);
            }
            if (!result.IsResultCodeSuccess())
            {
                throw new BaseException(result.err_code_des);
            }
            WxPayReturn wxPayReturn = new WxPayReturn();

            wxPayReturn.ReturnCode = WxPayState.Success;
            if (param.TradeType == TradeType.Native)
            {
                wxPayReturn.CodeUrl = result.code_url;
            }
            wxPayReturn.PrepayId   = result.prepay_id;
            wxPayReturn.DeviceInfo = result.device_info;
            return(wxPayReturn);
        }
示例#7
0
        public string GetRequestUrl(string returnUrl, string notifyUrl, string orderId, decimal totalFee, string productInfo, string openId = null)
        {
            string timestamp = "";
            string noncestr  = "";
            string str       = "";
            string str1      = orderId;

            DateTime.Now.ToString("yyyyMMdd");
            RequestHandler requestHandler = new RequestHandler();

            requestHandler.Init();
            timestamp = TenPayUtil.GetTimestamp();
            noncestr  = TenPayUtil.GetNoncestr();
            Config config = Utility <Config> .GetConfig(base.WorkDirectory);

            requestHandler.SetParameter("appid", config.AppId);
            requestHandler.SetParameter("mch_id", config.MCHID);
            requestHandler.SetParameter("nonce_str", noncestr);
            requestHandler.SetParameter("body", productInfo);
            requestHandler.SetParameter("out_trade_no", str1);
            int num = (int)(totalFee * new decimal(100));

            requestHandler.SetParameter("total_fee", num.ToString());
            requestHandler.SetParameter("spbill_create_ip", "222.240.184.122");
            requestHandler.SetParameter("notify_url", notifyUrl);
            requestHandler.SetParameter("trade_type", "JSAPI");
            requestHandler.SetParameter("openid", openId);
            string str2 = requestHandler.CreateMd5Sign("key", config.Key);

            requestHandler.SetParameter("sign", str2);
            string    str3      = requestHandler.ParseXML();
            XDocument xDocument = XDocument.Parse(TenPayV3.Unifiedorder(str3));

            if (xDocument == null)
            {
                throw new ApplicationException(string.Concat("调用统一支付出错:请求内容:", str3));
            }
            if (xDocument.Element("xml").Element("return_code").Value == "FAIL")
            {
                throw new ApplicationException(string.Concat("预支付失败:", xDocument.Element("xml").Element("return_msg").Value));
            }
            if (xDocument.Element("xml").Element("result_code").Value == "FAIL")
            {
                throw new ApplicationException(string.Concat("预支付失败:", xDocument.Element("xml").Element("err_code_des").Value));
            }
            string         value           = xDocument.Element("xml").Element("prepay_id").Value;
            RequestHandler requestHandler1 = new RequestHandler();

            requestHandler1.SetParameter("appId", config.AppId);
            requestHandler1.SetParameter("timeStamp", timestamp);
            requestHandler1.SetParameter("nonceStr", noncestr);
            requestHandler1.SetParameter("package", string.Format("prepay_id={0}", value));
            requestHandler1.SetParameter("signType", "MD5");
            str = requestHandler1.CreateMd5Sign("key", config.Key);
            string str4 = string.Concat("WeixinJSBridge.invoke('getBrandWCPayRequest', {{'appId': '{0}','timeStamp': '{1}','nonceStr': '{2}','package': '{3}','signType': 'MD5','paySign': '{4}'}}, function (res) {{if (res.err_msg == 'brand_wcpay_request:ok') {{location.href='", returnUrl, "'}}else alert('支付失败!')}});");

            object[] appId = new object[] { config.AppId, timestamp, noncestr, string.Format("prepay_id={0}", value), str };
            string   str5  = string.Format(str4, appId);

            return(string.Format("javascript:{0}", str5));
        }
示例#8
0
        public ActionResult ajaxorder(OrdersEntity ordersEntity)
        {
            try
            {
                string city = ordersEntity.City;
                if (city.Contains("-"))
                {
                    string[] area = ordersEntity.City.Split('-');
                    if (area.Length > 0)
                    {
                        ordersEntity.Province = area[0]; //省
                        ordersEntity.City     = area[1]; //市
                        ordersEntity.Country  = area[2]; //市
                    }
                }
                else
                {
                    string[] area = ordersEntity.City.Split(' ');
                    if (area.Length > 0)
                    {
                        ordersEntity.Province = area[0]; //省
                        ordersEntity.City     = area[1]; //市
                    }
                }

                string payType = ordersEntity.PayType;
                if (payType == "alipay")
                {
                    payType = "支付宝";
                }
                else
                {
                    if (ordersEntity.PC == 1)
                    {
                        payType = "微信扫码";
                    }
                    else
                    {
                        payType = "微信H5";
                    }
                }
                ordersEntity.PayType = payType;
                ordersEntity         = ordersbll.SaveForm(ordersEntity);

                var sp_billno = ordersEntity.OrderSn;
                var nonceStr  = TenPayV3Util.GetNoncestr();

                //商品Id,用户自行定义
                string productId = ordersEntity.TelphoneID.ToString();

                H5Response root = null;

                if (payType == "支付宝")
                {
                    try
                    {
                        DefaultAopClient client = new DefaultAopClient(WeixinConfig.serviceUrl, WeixinConfig.aliAppId, WeixinConfig.privateKey, "json", "1.0",
                                                                       WeixinConfig.signType, WeixinConfig.payKey, WeixinConfig.charset, false);

                        // 组装业务参数model
                        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
                        model.Body           = "支付宝购买靓号";                                           // 商品描述
                        model.Subject        = productId;                                           // 订单名称
                        model.TotalAmount    = ordersEntity.Price.ToString();                       // 付款金额"0.01"
                        model.OutTradeNo     = sp_billno;                                           // 外部订单号,商户网站订单系统中唯一的订单号
                        model.ProductCode    = "QUICK_WAP_WAY";
                        model.QuitUrl        = "https://ghdh.digitdance.cn:8069/webapp/jntt/Index"; // 支付中途退出返回商户网站地址
                        model.TimeoutExpress = "90m";
                        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
                        //设置支付完成同步回调地址
                        request.SetReturnUrl(WeixinConfig.return_url);
                        //设置支付完成异步通知接收地址
                        request.SetNotifyUrl(WeixinConfig.notify_url);
                        // 将业务model载入到request
                        request.SetBizModel(model);

                        AlipayTradeWapPayResponse response = null;
                        try
                        {
                            response = client.pageExecute(request, null, "post");
                            //Response.Write(response.Body);

                            H5PayData h5PayData = new H5PayData();
                            h5PayData.form = response.Body;
                            root           = new H5Response {
                                code = true, status = true, msg = "\u652f\u4ed8\u5b9d\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData
                            };
                        }
                        catch (Exception exp)
                        {
                            throw exp;
                        }
                    }
                    catch (Exception ex)
                    {
                        //return Json(new { Result = false, msg = "缺少参数" });
                    }
                }
                else
                {
                    //pc端返回二维码,否则H5
                    if (payType == "微信扫码")
                    {
                        //创建请求统一订单接口参数
                        var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2,
                                                                              tenPayV3Info.MchId,
                                                                              "扫码支付靓号",
                                                                              sp_billno,
                                                                              Convert.ToInt32(ordersEntity.Price * 100),
                                                                              //1,
                                                                              Request.UserHostAddress,
                                                                              tenPayV3Info.TenPayV3Notify,
                                                                              TenPayV3Type.NATIVE,
                                                                              null,
                                                                              tenPayV3Info.Key,
                                                                              nonceStr,
                                                                              productId: productId);
                        //调用统一订单接口
                        var result = TenPayV3.Unifiedorder(xmlDataInfo);
                        if (result.return_code == "SUCCESS")
                        {
                            H5PayData h5PayData = new H5PayData()
                            {
                                appid         = WeixinConfig.AppID2,
                                code_url      = result.code_url,//weixin://wxpay/bizpayurl?pr=lixpXgt-----------扫码支付
                                mch_id        = WeixinConfig.MchId,
                                nonce_str     = result.nonce_str,
                                prepay_id     = result.prepay_id,
                                result_code   = result.result_code,
                                return_code   = result.return_code,
                                return_msg    = result.return_msg,
                                sign          = result.sign,
                                trade_type    = "NATIVE",
                                trade_no      = sp_billno,
                                payid         = ordersEntity.Id.ToString(),
                                wx_query_href = "https://shop.jnlxsm.net/webapp/jntt/queryWx/" + ordersEntity.Id,
                                wx_query_over = "https://shop.jnlxsm.net/webapp/jntt/paymentFinish/" + ordersEntity.Id
                            };

                            root = new H5Response {
                                code = true, status = true, msg = "\u5fae\u4fe1\u626b\u7801\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData
                            };
                        }
                        else
                        {
                            root = new H5Response {
                                code = false, status = false, msg = result.return_msg
                            };
                        }
                    }
                    else
                    {
                        var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2, tenPayV3Info.MchId, "H5购买靓号", sp_billno,
                                                                                // 1,
                                                                                Convert.ToInt32(ordersEntity.Price * 100),
                                                                                Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, null, tenPayV3Info.Key, nonceStr);

                        var resultH5 = TenPayV3.Html5Order(xmlDataInfoH5); //调用统一订单接口
                        LogHelper.AddLog(resultH5.ResultXml);              //记录日志
                        if (resultH5.return_code == "SUCCESS")
                        {
                            H5PayData h5PayData = new H5PayData()
                            {
                                appid         = WeixinConfig.AppID2,
                                mweb_url      = resultH5.mweb_url,//H5访问链接
                                mch_id        = WeixinConfig.MchId,
                                nonce_str     = resultH5.nonce_str,
                                prepay_id     = resultH5.prepay_id,
                                result_code   = resultH5.result_code,
                                return_code   = resultH5.return_code,
                                return_msg    = resultH5.return_msg,
                                sign          = resultH5.sign,
                                trade_type    = "H5",
                                trade_no      = sp_billno,
                                payid         = ordersEntity.Id.ToString(),
                                wx_query_href = "https://shop.jnlxsm.net/webapp/jntt/queryWx/" + ordersEntity.Id,
                                wx_query_over = "https://shop.jnlxsm.net/webapp/jntt/paymentFinish/" + ordersEntity.Id
                            };

                            root = new H5Response {
                                code = true, status = true, msg = "\u5fae\u4fe1\u0048\u0035\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData
                            };
                        }
                        else
                        {
                            root = new H5Response {
                                code = false, status = false, msg = resultH5.return_msg
                            };
                        }
                    }
                }

                LogHelper.AddLog(JsonConvert.SerializeObject(root));//记录日志

                return(Content(JsonConvert.SerializeObject(root)));
            }
            catch (Exception ex)
            {
                LogHelper.AddLog(ex.Message);//记录日志
                throw;
            }
        }
        public ActionResult 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 timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";

                string sp_billno = Request["order_no"];
                //当前时间 yyyyMMdd
                string date = DateTime.Now.ToString("yyyyMMdd");

                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"].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 body        = product == null ? "test" : product.Name;
                var price       = product == null ? 100 : product.Price * 100;
                var xmlDataInfo = new TenPayV3XmlDataInfo(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openIdResult.openid, TenPayV3Info.Key, nonceStr);

                var result = TenPayV3.Unifiedorder(xmlDataInfo);
                var res    = XDocument.Parse(result);

                if (res.Element("xml").Element("prepay_id") == null)
                {
                    throw new Exception(res.ToString().HtmlEncode());
                }

                //throw new Exception(res.ToString().HtmlEncode());
                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());
            }
            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));
            }
        }
示例#10
0
        public ActionResult upgradeLevel(int?tid)
        {
            var agentEntity = agentBll.GetEntityByOpenId(CurrentWxUser.OpenId);

            if (agentEntity != null)
            {
                //var ordersEntityOld = ordersJMBll.GetList("{\"AgentId\":\"" + agentEntity.Id + "\",\"PayStatus\":\"" + 0 + "\"}");
                //if (ordersEntityOld.Count()>0)
                //{
                //    //存在未付款的升级订单

                //}

                LogHelper.AddLog("upgradeLevel tid=" + tid);//记录日志
                decimal price = 0;
                string  LV    = "";
                if (tid == 2)
                {
                    price = 399;
                    LV    = "黄金代理";
                }
                else if (tid == 3)
                {
                    price = 1999;
                    LV    = "钻石代理";
                }
                var sp_billno = string.Format("{0}{1}", "JM-", DateTime.Now.ToString("yyyyMMddHHmmss"));

                OrdersJMEntity ordersEntity = new OrdersJMEntity()
                {
                    Price    = price,
                    LV       = LV,
                    OrderSn  = sp_billno,
                    OpenId   = CurrentWxUser.OpenId,
                    NickName = CurrentWxUser.NickName,
                    AgentId  = agentEntity.Id,
                    Pid      = agentEntity.Pid,
                    Tid      = agentEntity.Tid
                };

                ordersEntity = ordersJMBll.SaveForm(null, ordersEntity);//创建JM升级订单表

                var nonceStr  = TenPayV3Util.GetNoncestr();
                var timeStamp = TenPayV3Util.GetTimestamp();

                //商品Id,用户自行定义
                var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID, tenPayV3Info.MchId, LV, sp_billno,
                                                                        Convert.ToInt32(Convert.ToDecimal(price) * 100), //1
                                                                        Request.UserHostAddress, WeixinConfig.TenPayV3Notify, TenPayV3Type.JSAPI, CurrentWxUser.OpenId, tenPayV3Info.Key, nonceStr);
                var result = TenPayV3.Unifiedorder(xmlDataInfoH5);                                                       //调用统一订单接口
                LogHelper.AddLog(result.ResultXml);                                                                      //记录日志
                var package = string.Format("prepay_id={0}", result.prepay_id);
                if (result.return_code == "SUCCESS")
                {
                    WFTWxModel jsApiPayData = new WFTWxModel()
                    {
                        appId     = WeixinConfig.AppID,
                        timeStamp = timeStamp,
                        nonceStr  = nonceStr,
                        package   = package,
                        paySign   = TenPayV3.GetJsPaySign(WeixinConfig.AppID, timeStamp, nonceStr, package, WeixinConfig.Key)
                    };
                    ViewBag.WxModel = jsApiPayData;
                    LogHelper.AddLog(JsonConvert.SerializeObject(jsApiPayData));//记录日志
                }
            }
            return(View());
        }
示例#11
0
        //public static TenPayInfo TenPayInfo
        //{
        //    get
        //    {
        //        if (_tenPayInfo == null)
        //        {
        //            _tenPayInfo =
        //                TenPayInfoCollection.Data[System.Configuration.ConfigurationManager.AppSettings["WeixinPay_PartnerId"]];
        //        }
        //        return _tenPayInfo;
        //    }
        //}
        /// <summary>
        /// 微信支付:生成请求数据
        /// </summary>
        /// <param name="openid">微信用户id</openid>
        /// <param name="ttFee">商品总价格</param>
        /// <param name="busiBody"></param>
        /// <returns></returns>
        protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no)
        {
            WxPayHelper wxPayHelper = new WxPayHelper();

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            // //先设置基本信息
            // string partnerId = paymentInfo.partnerId;// "1218574001";//
            // string appId = paymentInfo.appId;// "wxa9b8e33e48ac5e0f";//
            // string partnerKey = paymentInfo.partnerKey;// "huyuxianghuyuxianghuyuxiang12345";//
            // //paysignkey(非appkey)
            // string appKey = paymentInfo.paySignKey; //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";//

            // wxPayHelper.SetAppId(appId);
            // wxPayHelper.SetAppKey(appKey);
            // wxPayHelper.SetPartnerKey(partnerKey);
            // wxPayHelper.SetSignType("SHA1");
            // //设置请求package信息
            // wxPayHelper.SetParameter("bank_type", "WX");
            // wxPayHelper.SetParameter("body", busiBody);
            // wxPayHelper.SetParameter("attach",wid+"|"+busiBody);
            // wxPayHelper.SetParameter("partner", partnerId);
            // wxPayHelper.SetParameter("out_trade_no", out_trade_no);
            // wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString());
            // wxPayHelper.SetParameter("fee_type", "1");
            //// wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid);

            // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数
            // wxPayHelper.SetParameter("spbill_create_ip", MXRequest.GetIP());
            // wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            // //---------有效期截至日期------

            // wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss"));

            // wxPayHelper.SetParameter("input_charset", "UTF-8");
            // packageValue = wxPayHelper.CreateBizPackage();

            ///////////////////////////////////////////////////////////////////////////


            //通过,用code换取access_token
            //var openIdResult = OAuthApi.GetAccessToken(paymentInfo.appId, "a891edd957f2aede546f9256096bf95a", code);
            //if (openIdResult.errcode != ReturnCode.请求成功)
            //{
            //    return Content("错误:" + openIdResult.errmsg);
            //}

            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            }
            else
            {
                sp_billno = Request["order_no"].ToString();
            }

            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化
            packageReqHandler.Init();

            timeStamp = TenPayV3Util.GetTimestamp();
            nonceStr  = TenPayV3Util.GetNoncestr();

            //设置package订单参数
            packageReqHandler.SetParameter("appid", paymentInfo.appId);                                    //公众账号ID
            packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId);                               //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                                         //随机字符串
            packageReqHandler.SetParameter("body", "aaa");                                                 //商品信息
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                                     //商家订单号
            packageReqHandler.SetParameter("total_fee", "100");                                            //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                   //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", "http://ddd.com");                                //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", Senparc.Weixin.MP.TenPayV3Type.JSAPI.ToString()); //交易类型
            packageReqHandler.SetParameter("openid", "oFo2Hjq6_yMhyz6cQ2MZtmxODOVU");                      //用户的openId

            string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.partnerKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", paymentInfo.appId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", paymentInfo.partnerKey);

            payaddid        = paymentInfo.appId;
            paytimeStamp    = timeStamp;
            paynonceStr     = nonceStr;
            paypackageValue = packageValue;
            paypaySign      = paySign;
        }
示例#12
0
        public IActionResult JsApi([FromRoute] string orderid)
        {
            IActionResult actionResult = NoContent();

            try
            {
                var _order = _context.Order.FirstOrDefault(z => z.OrderID == orderid);

                if (_order == null || _order.OrderStatus != 0)
                {
                    _logger.LogInformation($"订单不存在{orderid}");
                    actionResult = Ok(new { code = 1010, msg = $"商品信息不存在,或已支付{_order.OrderStatus}" });
                }
                else
                {
                    var    items      = from bi in _context.BuyItem where bi.OrderID == orderid select bi;
                    var    body       = string.Join('_', (from bi in items select bi.GoodsName).Take(3).ToArray());
                    var    sessionBag = SessionContainer.GetSession(Request.GetJwtSecurityToken()?.GetUserId());
                    var    openId     = sessionBag.OpenId;
                    string sp_billno  = orderid;
                    var    timeStamp  = TenPayV3Util.GetTimestamp();
                    var    nonceStr   = TenPayV3Util.GetNoncestr();
                    int    willpay    = (int)(_order.Payable * 100);
                    int    minipay    = (int)(((int)(_order.TotalPrice * 100)) * 0.8);
                    int    price      = (_order.Payable != 0 && willpay >= minipay) ? willpay : minipay;//单位:分
                    _logger.LogInformation($"body:{body},openId={openId},orderid={orderid},timeStamp={timeStamp},nonceStr={nonceStr},_order.Payable={_order.Payable};_order.TotalPrice={_order.TotalPrice},willpay={willpay};minipay={minipay},price={price}");
                    var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr);
                    var result      = TenPayV3.Unifiedorder(xmlDataInfo);
                    if (result.return_code == "SUCCESS")
                    {
                        _logger.LogInformation($"= {result.prepay_id}  ");
                        var package = string.Format("prepay_id={0}", result.prepay_id);
                        var data    = new
                        {
                            out_trade_no = orderid,
                            TenPayV3Info.AppId,
                            timeStamp,
                            nonceStr,
                            package,
                            signType = "MD5",
                            paySign  = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key)
                        };
                        _order.PrepayId    = result.prepay_id;
                        _order.OrderStatus = TradeState.USERPAYING;
                        _context.SaveChanges();
                        actionResult = Ok(new { code = 0, msg = "OK", data });
                    }
                    else
                    {
                        actionResult = Ok(new { code = 1013, msg = result.return_msg, result.result_code, result.err_code, result.err_code_des });
                        _logger.LogInformation($"msg ={ result.return_msg},result_code= {result.result_code} ,err_code={result.err_code},err_code_des={result.err_code_des}");
                    }
                }
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                msg += $"\r\n{ex.StackTrace}\r\n==Source==\r\n{ex.Source}";
                if (ex.InnerException != null)
                {
                    msg += $"\r\n ===InnerException===\r\n{ex.InnerException.Message}";
                }
                actionResult = Ok(new { code = 1012, msg = msg });
            }
            return(actionResult);
        }
示例#13
0
        public ActionResult GetWxPayJsApi(string mpid, string openid, string productname, int total, string orderno)
        {
            try
            {
                #region 校验公众号
                var account = GetAccount(mpid);
                if (account == null)
                {
                    LogWriter.Info(string.Format("mpid为“{0}”的发送红包接口调用失败,原因:公众号不存在", mpid));
                    return(Content("公众号不存在"));
                }
                #endregion

                string timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";

                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                orderno = string.IsNullOrEmpty(orderno) ? (DateTime.Now.ToString("yyyyMMddHHmmss") + TenPayV3Util.BuildRandomStr(3)) : orderno;

                //创建支付应答对象
                RequestHandler packageReqHandler = new RequestHandler(null);
                //初始化
                packageReqHandler.Init();

                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr  = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", account.AppID);                                                                      //公众账号ID
                packageReqHandler.SetParameter("mch_id", account.MchID);                                                                     //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                       //随机字符串
                packageReqHandler.SetParameter("body", productname);                                                                         //商品信息
                packageReqHandler.SetParameter("out_trade_no", orderno);                                                                     //商家订单号
                packageReqHandler.SetParameter("total_fee", total.ToString());                                                               //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                                                 //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", $"{Request.Url.Scheme}://{Request.Url.Host}/wechatservice/wxapi/PayNotifyUrl"); //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                 //交易类型
                packageReqHandler.SetParameter("openid", openid);                                                                            //用户的openId
                packageReqHandler.SetParameter("attach", mpid);                                                                              //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", account.WxPayAppSecret);
                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", account.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", account.WxPayAppSecret);

                ViewData["appId"]     = account.AppID;
                ViewData["timeStamp"] = timeStamp;
                ViewData["nonceStr"]  = nonceStr;
                ViewData["package"]   = string.Format("prepay_id={0}", prepayId);
                ViewData["paySign"]   = paySign;
                return(Json(new
                {
                    success = true,
                    data = new
                    {
                        appId = account.AppID,
                        timeStamp = timeStamp,
                        nonceStr = nonceStr,
                        package = string.Format("prepay_id={0}", prepayId),
                        paySign = paySign,
                        orderNO = orderno
                    }
                }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                LogWriter.Info($"openid:'{openid}',total:{total},productname:'{productname}',ex:'{ex.Message}'");
                return(Json(new
                {
                    success = false,
                    msg = ex.Message,
                }, JsonRequestBehavior.AllowGet));
            }
        }
示例#14
0
        public object Do_Payment(BaseApi baseApi)
        {
            PaymentParam paymentParam = JsonConvert.DeserializeObject <PaymentParam>(baseApi.param.ToString());

            if (paymentParam == null)
            {
                throw new ApiException(CodeMessage.InvalidParam, "InvalidParam");
            }
            if (paymentParam.billId == null || paymentParam.billId == "")
            {
                throw new ApiException(CodeMessage.InterfaceValueError, "InterfaceValueError");
            }

            string  openId  = Utils.GetOpenID(baseApi.token);
            OpenDao openDao = new OpenDao();

            //处理10分取消未支付订单
            openDao.UpdateBookingStatusBy10Minute(openId);
            BILLLIST billList = openDao.getBillListById(paymentParam.billId, openId);

            if (billList == null)
            {
                throw new ApiException(CodeMessage.PaymentBillError, "PaymentBillError");
            }
            if (billList.bookingState != "1")
            {
                throw new ApiException(CodeMessage.PaymentStateError, "PaymentStateError");
            }
            var billId     = paymentParam.billId;
            int totalPrice = Convert.ToInt32(billList.billPrice * 100);

            if (totalPrice <= 0)
            {
                throw new ApiException(CodeMessage.PaymentTotalPriceZero, "PaymentTotalPriceZero");
            }

            //if (billList.prePayId!=null && billList.prePayId!="" && billList.prePayTime != null && billList.prePayTime != "")
            //{
            //    try
            //    {
            //        DateTime preDateTime = Convert.ToDateTime(billList.prePayTime);
            //        if (DateTime.Now.AddHours(-2)< preDateTime)
            //        {
            //            var timeStamp = TenPayV3Util.GetTimestamp();
            //            var nonceStr = TenPayV3Util.GetNoncestr();
            //            var product = "船票";
            //            var package = string.Format("prepay_id={0}", billList.prePayId);
            //            var paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key);

            //            PaymentResults paymentResults = new PaymentResults();
            //            paymentResults.appId = tenPayV3Info.AppId;
            //            paymentResults.nonceStr = nonceStr;
            //            paymentResults.package = package;
            //            paymentResults.paySign = paySign;
            //            paymentResults.timeStamp = timeStamp;
            //            paymentResults.product = product;
            //            paymentResults.billId = billId;

            //            return paymentResults;
            //        }
            //    }
            //    catch (Exception)
            //    {

            //    }

            //}

            try
            {
                var timeStamp   = TenPayV3Util.GetTimestamp();
                var nonceStr    = TenPayV3Util.GetNoncestr();
                var product     = "船票";
                var xmlDataInfo =
                    new TenPayV3UnifiedorderRequestData(
                        tenPayV3Info.AppId,
                        tenPayV3Info.MchId,
                        product,
                        billId,
                        totalPrice,
                        "127.0.0.1",
                        tenPayV3Info.TenPayV3Notify,
                        TenPayV3Type.JSAPI,
                        openId,
                        tenPayV3Info.Key,
                        nonceStr);

                var result = TenPayV3.Html5Order(xmlDataInfo);
                if (result.return_msg != "")
                {
                    openDao.writeLog(Global.POSCODE, "", "pay", result.return_msg);
                }

                pDao.writePrePayId(billId, result.prepay_id);
                var package = string.Format("prepay_id={0}", result.prepay_id);
                var paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key);

                PaymentResults paymentResults = new PaymentResults();
                paymentResults.appId     = tenPayV3Info.AppId;
                paymentResults.nonceStr  = nonceStr;
                paymentResults.package   = package;
                paymentResults.paySign   = paySign;
                paymentResults.timeStamp = timeStamp;
                paymentResults.product   = product;
                paymentResults.billId    = billId;

                return(paymentResults);
            }
            catch (Exception ex)
            {
                throw new ApiException(CodeMessage.PaymentError, "PaymentError");
            }
        }
示例#15
0
        /// <summary>
        /// 最新接口调用
        /// 2014-11-24
        /// </summary>
        /// <param name="ttFee">支付金额(单位元)</param>
        /// <param name="busiBody">订单内容</param>
        /// <param name="out_trade_no">订单号</param>
        /// <param name="code"></param>
        protected void WxPayDataV3(decimal ttFee, string busiBody, string out_trade_no, string code)
        {
            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            BLL.wx_userweixin   uwBll    = new BLL.wx_userweixin();
            Model.wx_userweixin uwEntity = uwBll.GetModel(wid);

            // logBll.AddLog(wid,"【微支付】微信预定", "paypage.aspx WxPayDataV3", "211 wid:" + wid, 1);

            //先设置基本信息
            string MchId = paymentInfo.partnerId;       // "1218574001";//

            string partnerKey = paymentInfo.partnerKey; // 商户支付密钥Key。登录微信商户后台,进入栏目【账户设置】【密码安全】【API 安全】【API 密钥】

            string notify_url = "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx";

            logBll.AddLog(wid, "【微支付】微信预定", "paypage.aspx WxPayDataV3", "uwEntity.AppId: " + uwEntity.AppId + "| uwEntity.AppSecret;" + uwEntity.AppSecret + "|code:" + code, 1);


            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = out_trade_no;
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayUtil.BuildRandomStr(28);
            }


            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化

            //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/);

            timeStamp = TenPayUtil.GetTimestamp();
            nonceStr  = TenPayUtil.GetNoncestr();

            //设置package订单参数
            packageReqHandler.SetParameter("appid", uwEntity.AppId);                      //公众账号ID
            packageReqHandler.SetParameter("mch_id", MchId);                              //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                        //随机字符串
            packageReqHandler.SetParameter("body", busiBody);                             //商品描述
            packageReqHandler.SetParameter("attach", wid + "|" + busiBody);
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                    //商家订单号
            packageReqHandler.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);  //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", notify_url);                     //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());  //交易类型
            packageReqHandler.SetParameter("openid", openid);                             //用户的openId

            string sign = packageReqHandler.CreateMd5Sign("key", partnerKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;



            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", uwEntity.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", partnerKey);

            packageValue  = "";
            packageValue += " \"appId\": \"" + uwEntity.AppId + "\", ";
            packageValue += " \"timeStamp\": \"" + timeStamp + "\", ";
            packageValue += " \"nonceStr\": \"" + nonceStr + "\", ";
            packageValue += " \"package\": \"" + string.Format("prepay_id={0}", prepayId) + "\", ";
            packageValue += " \"signType\": \"MD5\", ";
            packageValue += " \"paySign\": \"" + paySign + "\"";
        }
示例#16
0
        /// <summary>
        /// 生成jsapi支付预付单(JASPI)
        /// </summary>
        /// <param name="clientId">客户端ID</param>
        /// <param name="title">商品标题</param>
        /// <param name="totalAmount">支付金额(单位分)</param>
        /// <param name="attach">附加数据</param>
        /// <param name="orderId">订单id</param>
        /// <param name="openId">用户openid</param>
        /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param>
        /// <returns></returns>
        public async Task <PrePayResult <JsApiResult> > BuildJsApi(string appId, string mchId, string mchKey, string title,
                                                                   int totalAmount,
                                                                   string attach, string orderId, string localTradeNo, string openId, string notifyUrl,
                                                                   TimeSpan?expire = null)
        {
            if (string.IsNullOrWhiteSpace(title))
            {
                throw new ArgumentException("支付标题不能为空", nameof(title));
            }
            if (string.IsNullOrWhiteSpace(orderId))
            {
                throw new ArgumentException("订单id不能为空", nameof(orderId));
            }
            if (totalAmount < 1)
            {
                throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount));
            }

            string nonceStr = TenPayV3Util.GetNoncestr();

            // 微信支付统一订单 api调用,生成预付单
            var requestData = new TenPayV3UnifiedorderRequestData(
                appId,
                mchId,
                title,
                localTradeNo,
                totalAmount,
                null,
                notifyUrl,
                TenPayV3Type.JSAPI,
                openId,
                mchKey,
                nonceStr,
                attach: attach,
                productId: orderId,
                timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1))
                );

            var result = await TenPayV3.UnifiedorderAsync(requestData);

            Logger.LogInformation($"JASPI支付预付单结果:{result.ResultXml}");
            if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess())
            {
                throw new Exception(
                          $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}");
            }

            // 返回前端支付jaapi支付数据
            var    timeStamp    = TenPayV3Util.GetTimestamp();
            string nonceStrSign = TenPayV3Util.GetNoncestr();
            var    package      = $"prepay_id={result.prepay_id}";
            var    sign         = TenPayV3.GetJsPaySign(appId, timeStamp, nonceStrSign, package, mchKey);

            return(new PrePayResult <JsApiResult>
            {
                Result = new JsApiResult
                {
                    AppId = appId,
                    NonceStr = nonceStrSign,
                    Package = package,
                    PaySign = sign,
                    SignType = "MD5",
                    TimeStamp = timeStamp
                },
                UnifiedorderResult = result,
                LocalTradeNo = localTradeNo
            });
        }
示例#17
0
        /// <summary>
        /// 企业支付
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="payCode">支付ID,订单号+支付日志ID</param>
        /// <param name="amount">金额</param>
        /// <param name="desc">付款描述信息</param>
        /// <returns></returns>
        public static string QYPay(string openId, string payCode, decimal amount, string desc)
        {
            var payStatus = 1;
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            var            nonceStr          = TenPayV3Util.GetNoncestr();

            //创建请求接口参数
            packageReqHandler.SetParameter("mch_appid", AppId);
            packageReqHandler.SetParameter("mchid", Mchid);
            packageReqHandler.SetParameter("nonce_str", nonceStr);
            packageReqHandler.SetParameter("partner_trade_no", payCode);
            packageReqHandler.SetParameter("openid", openId);
            packageReqHandler.SetParameter("check_name", "NO_CHECK");//不校验用户姓名
            packageReqHandler.SetParameter("desc", desc);
            packageReqHandler.SetParameter("amount", Convert.ToInt32(amount * 100).ToString());
            packageReqHandler.SetParameter("spbill_create_ip", IP);
            string sign = packageReqHandler.CreateMd5Sign("key", PayKey);

            packageReqHandler.SetParameter("sign", sign);

            string data = packageReqHandler.ParseXML();

            //证书相关
            var cert          = new X509Certificate2(SSLCERT_PATH, SSLCERT_PASSWORD);
            var access        = new WeixinPayLogDataAccess();
            var weixinService = new WeiXinService(access);

            try
            {
                //调用企业支付接口
                var result = TenPayV3.QYPay(data, cert);
                logger.Info("企业支付返回信息:" + result);
                var    unifiedorderRes = XDocument.Parse(result);
                string return_code     = unifiedorderRes.Element("xml").Element("return_code").Value;
                if (return_code == "SUCCESS")
                {
                    payStatus = 1;
                }
                else
                {
                    payStatus = 0;
                }

                return(return_code);
            }
            catch (Exception e)
            {
                logger.Error(e);
                //payStatus = 0;
                //var paylog = new WeixinPayLog()
                //{
                //    OrderId = orderId,
                //    WxOpenId = openId,
                //    Description = desc,
                //    Amount = amount,
                //    Status = payStatus,
                //    CreateTime = DateTime.Now
                //};
                //weixinService.InsertWeixinPayLog(paylog);
                return("ERROR");
            }
        }
示例#18
0
        /// <summary>
        /// app支付预付单
        /// </summary>
        /// <param name="clientId">客户端ID</param>
        /// <param name="title">商品标题</param>
        /// <param name="totalAmount">支付金额(单位分)</param>
        /// <param name="attach">附加数据</param>
        /// <param name="orderId">订单id</param>
        /// <param name="clientIp">客户端ip</param>
        /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param>
        /// <returns></returns>
        public async Task <PrePayResult <AppPayResult> > BuildApp(string appId, string mchId, string mchKey, string title,
                                                                  int totalAmount,
                                                                  string attach, string orderId, string localTradeNo, string clientIp, string notifyUrl,
                                                                  TimeSpan?expire = null)
        {
            if (string.IsNullOrWhiteSpace(title))
            {
                throw new ArgumentException("支付标题不能为空", nameof(title));
            }
            if (string.IsNullOrWhiteSpace(orderId))
            {
                throw new ArgumentException("订单id不能为空", nameof(orderId));
            }
            if (totalAmount < 1)
            {
                throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount));
            }

            string nonceStr = TenPayV3Util.GetNoncestr();
            // 微信支付统一订单 api调用,生成预付单
            var requestData = new TenPayV3UnifiedorderRequestData(
                appId,
                mchId,
                title,
                localTradeNo,
                totalAmount,
                clientIp,
                notifyUrl,
                TenPayV3Type.APP,
                null,
                mchKey,
                nonceStr,
                attach: attach,
                productId: orderId,
                timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1))
                );

            var result = await TenPayV3.UnifiedorderAsync(requestData);

            Logger.LogInformation($"APP支付预付单结果:{result.ResultXml}");
            if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess())
            {
                throw new Exception(
                          $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}");
            }

            var    timeStamp    = TenPayV3Util.GetTimestamp();
            string nonceStrSign = TenPayV3Util.GetNoncestr();

            ;
            var package = $"Sign=WXPay";

            // 生成签名sign
            RequestHandler paySignReqHandler = new RequestHandler(null);

            paySignReqHandler.SetParameter("appid", appId);
            paySignReqHandler.SetParameter("timestamp", timeStamp);
            paySignReqHandler.SetParameter("noncestr", nonceStrSign);
            paySignReqHandler.SetParameter("package", package);
            paySignReqHandler.SetParameter("prepayid", result.prepay_id);
            paySignReqHandler.SetParameter("partnerid", mchId);
            var paySign = paySignReqHandler.CreateMd5Sign("key", mchKey);

            return(new PrePayResult <AppPayResult>
            {
                Result = new AppPayResult
                {
                    Appid = appId,
                    Noncestr = nonceStrSign,
                    Prepayid = result.prepay_id,
                    Package = package,
                    Partnerid = mchId,
                    Sign = paySign,
                    Timestamp = timeStamp
                },
                UnifiedorderResult = result,
                LocalTradeNo = localTradeNo
            });
        }
示例#19
0
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="id">订单编号</param>
        /// <returns>视图</returns>
        public ActionResult GoPayWeiXin(string id)
        {
            Log4Helper.WriteInfoLog(id, "pay");

            //当前上下文
            var context = CustomerContext.Context;

            if (context == null)
            {
                return(View("Error", new JResult()
                {
                    Message = "用户已超时、请重新登录﹗"
                }));
            }

            var customerExt = CustomerApp.Instance.Get(context.SysNo);

            if (customerExt == null)
            {
                return(View("Error", new JResult()
                {
                    Message = "扩展会员不存在﹗"
                }));
            }

            //获取订单
            var recharge = RechargeApp.Instance.GetbyOrderNo(id);

            if (recharge == null)
            {
                return(View("Error", new JResult()
                {
                    Message = "订单号不存在﹗"
                }));
            }

            ViewBag.SourceUrl = WebUtil.GetSource();

            #region JsApi支付

            try
            {
                //创建支付应答对象
                var packageReqHandler = new RequestHandler(null);
                //初始化
                packageReqHandler.Init();

                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr  = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);      //公众账号ID
                packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);     //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);            //随机字符串
                packageReqHandler.SetParameter("body", "千年教育充值订单");               //商品信息
                packageReqHandler.SetParameter("out_trade_no", recharge.OrderNo); //订单号
                packageReqHandler.SetParameter("total_fee", Convert.ToInt32(recharge.Amount * 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", customerExt.OpenId);                //用户的openId

                var sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
                packageReqHandler.SetParameter("sign", sign); //签名

                var data = packageReqHandler.ParseXML();
                Log4Helper.WriteInfoLog("data:" + data, "pay");
                var result = TenPayV3.Unifiedorder(data);
                Log4Helper.WriteInfoLog("统一支付接口:" + result, "pay");

                var res = XDocument.Parse(result);

                var return_code = res.Element("xml").Element("return_code").Value;
                var result_code = res.Element("xml").Element("result_code").Value;
                if (return_code.ToUpper() != "SUCCESS")
                {
                    return(View("Error", new JResult {
                        Message = "通信故障,请稍后再试!"
                    }));
                }
                if (result_code.ToUpper() == "FAIL")
                {
                    var err_code_des = res.Element("xml").Element("err_code_des").Value;
                    if (err_code_des.Contains("订单号重复"))
                    {
                        return(View("Error", new JResult {
                            Message = "订单号重复"
                        }));
                    }
                    return(View("Error", new JResult {
                        Message = err_code_des
                    }));
                }

                var prepayId = res.Element("xml").Element("prepay_id").Value;

                //设置支付参数
                var 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");
                var 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;
            }
            catch (Exception ex)
            {
                Log4Helper.WriteInfoLog(ex.Message, "pay");
            }
            #endregion

            return(View(customerExt));
        }
示例#20
0
        /// <summary>
        /// H5支付预付单
        /// </summary>
        /// <param name="clientId">客户端ID</param>
        /// <param name="title">商品标题</param>
        /// <param name="totalAmount">支付金额(单位分)</param>
        /// <param name="attach">附加数据</param>
        /// <param name="orderId">订单id</param>
        /// <param name="openId">用户openid</param>
        /// <param name="clientIp">客户端ip(微信安全校验)</param>
        /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param>
        /// <param name="redirect_url">前端跳转地址</param>
        /// <returns></returns>
        public async Task <PrePayResult <H5PayResult> > BuildH5(string appId, string mchId, string mchKey, string title,
                                                                int totalAmount,
                                                                string attach, string orderId, string localTradeNo, string clientIp, string notifyUrl, string redirect_url,
                                                                TimeSpan?expire = null)
        {
            if (string.IsNullOrWhiteSpace(title))
            {
                throw new ArgumentException("支付标题不能为空", nameof(title));
            }
            if (string.IsNullOrWhiteSpace(orderId))
            {
                throw new ArgumentException("订单id不能为空", nameof(orderId));
            }
            if (totalAmount < 1)
            {
                throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount));
            }

            string nonceStr = TenPayV3Util.GetNoncestr();
            // 微信支付统一订单 api调用,生成预付单
            var requestData = new TenPayV3UnifiedorderRequestData(
                appId,
                mchId,
                title,
                localTradeNo,
                totalAmount,
                clientIp,
                notifyUrl,
                TenPayV3Type.MWEB,
                null,
                mchKey,
                nonceStr,
                attach: attach,
                productId: orderId,
                timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1))
                );

            var result = await TenPayV3.UnifiedorderAsync(requestData);

            Logger.LogInformation($"MWEB支付预付单结果:{result.ResultXml}");
            if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess())
            {
                throw new Exception(
                          $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}");
            }

            string mWebUrl = result.mweb_url;

            if (redirect_url.IsNullOrWhiteSpace())
            {
                if (!HttpUtility.UrlDecode(redirect_url).IsMatch(Consts.Regexs.Url))
                {
                    throw new ArgumentException("跳转参数错误", nameof(redirect_url));
                }

                mWebUrl += string.Format("&redirect_url={0}", redirect_url);
            }

            return(new PrePayResult <H5PayResult>
            {
                Result = new H5PayResult
                {
                    MwebUrl = mWebUrl
                },
                LocalTradeNo = localTradeNo,
                UnifiedorderResult = result
            });
        }
示例#21
0
        public HttpResult JsApi(int productId)
        {
            string errorMessage = string.Empty;

            try
            {
                //获取产品信息
                var products = ProductModel.GetFakeProductList();
                var product  = products.FirstOrDefault(z => z.Id == productId);
                if (product == null)
                {
                    return(HttpResult.WeChatError("商品信息不存在!", null));
                }

                var openId = Common.Current.WxOpenId;

                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                string sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmssfff"),
                                                 TenPayV3Util.BuildRandomStr(6));
                //注意:以上订单号仅作为演示使用,如果访问量比较大,建议增加订单流水号的去重检查。

                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr  = TenPayV3Util.GetNoncestr();

                var body        = product.Name;
                var price       = (int)(product.Price * 100);//单位:分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr);
                xmlDataInfo.NotifyUrl = "https://yufaquan.cn/wx/PayV3/PayNotifyUrl";

                var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口
                                                                 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);
                var package = string.Format("prepay_id={0}", result.prepay_id);

                //TO DO
                //记录订单信息,留给退款申请接口测试使用
                //HttpContext.Session.SetString("BillNo", sp_billno);
                //HttpContext.Session.SetString("BillFee", price.ToString());


                var res = new
                {
                    product,
                    appId = TenPayV3Info.AppId,
                    timeStamp,
                    nonceStr,
                    package,
                    paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key)
                };
                return(HttpResult.Success(res));
            }
            catch (Exception ex)
            {
                //var msg = ex.Message;
                //msg += "<br>" + ex.StackTrace;
                //msg += "<br>==Source==<br>" + ex.Source;

                //if (ex.InnerException != null)
                //{
                //    msg += "<br>===InnerException===<br>" + ex.InnerException.Message;
                //}
                return(HttpResult.WeChatError(ex.Message, null));
            }
        }
示例#22
0
        public ActionResult JsApi(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

            if (state != "JeffreySu")
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return(Content("验证失败!请从正规途径进入!"));
            }

            //通过,用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();
            //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/);

            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", "test");
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                   //商家订单号
            packageReqHandler.SetParameter("total_fee", "100");                          //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", 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"));
                }
            }
        }
示例#24
0
        public static string Pay(string orderNumber, int totalFee, string openid)
        {
            //读取配置文件
            var merchantId = string.Empty;
            var appId      = string.Empty;
            var key        = string.Empty;
            var appSecret  = string.Empty;
            //接收微信支付异步通知回调地址
            var notifyUrl = string.Empty;
            var payUrl    = string.Empty;

            var xd = new XmlDocument();

            xd.Load(HttpContext.Current.Server.MapPath("/app_data/xml/payment.xml"));
            var selectSingleNode = xd.SelectSingleNode("paymentMethod");

            if (selectSingleNode != null)
            {
                var xnl = selectSingleNode.ChildNodes;
                foreach (XmlNode xn in xnl)
                {
                    var xe = (XmlElement)xn;
                    if (xe.GetAttribute("id") != "wechat")
                    {
                        continue;
                    }
                    merchantId = xe.GetAttribute("merchant_id");
                    appId      = xe.GetAttribute("app_id");
                    appSecret  = xe.GetAttribute("app_secret");
                    key        = xe.GetAttribute("key");
                    notifyUrl  = xe.GetAttribute("notify_url");
                    payUrl     = xe.GetAttribute("pay_url") + orderNumber.ToString();
                    break;
                }
            }
            var timestamp = Senparc.Weixin.MP.TenPayLib.TenPayUtil.GetTimestamp();
            var nonceStr  = Senparc.Weixin.MP.TenPayLib.TenPayUtil.GetNoncestr();

            JsApiTicketContainer.Register(appId, appSecret);
            var jsapiTicket = JsApiTicketContainer.GetJsApiTicket(appId);
            var signConfig  = new Senparc.Weixin.MP.TenPayLib.RequestHandler(null);

            signConfig.SetParameter("jsapi_ticket", jsapiTicket);
            signConfig.SetParameter("noncestr", nonceStr);
            signConfig.SetParameter("timestamp", timestamp);
            signConfig.SetParameter("url", payUrl);
            var signature = signConfig.CreateSHA1Sign();
            //支付
            //商品或支付单简要描述
            var body = "Billion智能仪表管理系统";
            //商户系统内部的订单号,32个字符内,可包含字母,其他说明见商户订单号
            //APP和网页支付提交用户端IP,Native支付填调用微信支付API的机器IP
            var spbillCreateIp = HttpContext.Current.Request.ServerVariables.Get("Remote_Addr");

            //JSAPI,NATIVE,APP,WAP
            var trade_type = "JSAPI";
            //创建支付应答对象
            var panSigig = new RequestHandler(null);

            //初始化
            panSigig.Init();
            //设置package订单参数
            panSigig.SetParameter("appid", appId);
            panSigig.SetParameter("mch_id", merchantId);
            panSigig.SetParameter("nonce_str", nonceStr);
            panSigig.SetParameter("body", body);
            panSigig.SetParameter("out_trade_no", orderNumber);
            panSigig.SetParameter("total_fee", totalFee.ToString());
            panSigig.SetParameter("spbill_create_ip", spbillCreateIp);
            panSigig.SetParameter("notify_url", notifyUrl);
            panSigig.SetParameter("trade_type", trade_type);
            panSigig.SetParameter("openid", openid);

            var sign = panSigig.CreateMd5Sign("key", key);

            panSigig.SetParameter("sign", sign);

            var data = panSigig.ParseXML();

            var result = TenPayV3.Unifiedorder(data);

            var res      = System.Xml.Linq.XDocument.Parse(result);
            var xElement = res.Element("xml");

            if (xElement == null)
            {
                return("");
            }
            var element = xElement.Element("prepay_id");

            if (element == null)
            {
                return("");
            }
            var prepayId          = element.Value;
            var paysignReqHandler = new RequestHandler(null);

            paysignReqHandler.Init();

            //设置支付参数
            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");
            var paysign = paysignReqHandler.CreateMd5Sign("key", key);

            paysignReqHandler.SetParameter("paysign", paysign);
            NVelocityHelper nh = new NVelocityHelper();

            nh.Put("app_id", appId);
            nh.Put("timestamp", timestamp);
            nh.Put("nonceStr", nonceStr);
            nh.Put("signature", signature);
            nh.Put("package", string.Format("prepay_id={0}", prepayId));
            nh.Put("signType", "MD5");
            nh.Put("paySign", paysign);
            nh.Put("orderid", orderNumber);
            return(nh.Write("app_data/template/wechat"));
        }
        public ActionResult JsApi(int productId, int hc)
        {
            try
            {
                //获取产品信息
                var products = ProductModel.GetFakeProductList();
                var product  = products.FirstOrDefault(z => z.Id == productId);
                if (product == null || product.GetHashCode() != hc)
                {
                    return(Content("商品信息不存在,或非法进入!1002"));
                }

                //var openId = User.Identity.Name;
                var openId = (string)Session["OpenId"];

                string sp_billno = Request["order_no"];
                if (string.IsNullOrEmpty(sp_billno))
                {
                    //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                    sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
                                              TenPayV3Util.BuildRandomStr(6));
                }
                else
                {
                    sp_billno = Request["order_no"];
                }

                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr  = TenPayV3Util.GetNoncestr();

                var body        = product == null ? "test" : product.Name;
                var price       = product == null ? 100 : (int)product.Price * 100;//单位:分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr);

                var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口
                                                                 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);
                var package = string.Format("prepay_id={0}", result.prepay_id);

                ViewData["product"] = product;

                ViewData["appId"]     = TenPayV3Info.AppId;
                ViewData["timeStamp"] = timeStamp;
                ViewData["nonceStr"]  = nonceStr;
                ViewData["package"]   = package;
                ViewData["paySign"]   = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);

                //临时记录订单信息,留给退款申请接口测试使用
                Session["BillNo"]  = sp_billno;
                Session["BillFee"] = price;

                return(View());
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                msg += "<br>" + ex.StackTrace;
                msg += "<br>==Source==<br>" + ex.Source;

                if (ex.InnerException != null)
                {
                    msg += "<br>===InnerException===<br>" + ex.InnerException.Message;
                }
                return(Content(msg));
            }
        }
示例#26
0
        /// <summary>
        /// 查询订单退款
        /// </summary>
        /// <param name="orderNumber">订单号</param>
        /// <returns></returns>
        public string RefundQuery(string orderNumber)
        {
            //读取配置文件
            var merchantId = string.Empty;
            var appId      = string.Empty;
            var key        = string.Empty;
            //接收微信支付异步通知回调地址

            var xd = new XmlDocument();

            xd.Load(HttpContext.Current.Server.MapPath("/app_data/xml/payment.xml"));
            var selectSingleNode = xd.SelectSingleNode("paymentMethod");

            if (selectSingleNode != null)
            {
                var xnl = selectSingleNode.ChildNodes;
                foreach (XmlNode xn in xnl)
                {
                    var xe = (XmlElement)xn;
                    if (xe.GetAttribute("id") != "wechat")
                    {
                        continue;
                    }
                    merchantId = xe.GetAttribute("merchant_id");
                    appId      = xe.GetAttribute("app_id");
                    key        = xe.GetAttribute("key");
                    break;
                }
            }
            var nonceStr          = TenPayV3Util.GetNoncestr();
            var packageReqHandler = new RequestHandler(null);

            packageReqHandler.SetKey(key);
            packageReqHandler.SetParameter("appid", appId);
            packageReqHandler.SetParameter("mch_id", merchantId);
            packageReqHandler.SetParameter("nonce_str", nonceStr);
            packageReqHandler.SetParameter("out_trade_no", orderNumber);//商户系统内部的订单号

            var querysign = packageReqHandler.CreateMd5Sign("key", key);

            packageReqHandler.SetParameter("sign", querysign);                        //签名

            var data = packageReqHandler.ParseXML();

            var result = TenPayV3.RefundQuery(data);
            var res    = System.Xml.Linq.XDocument.Parse(result);

            var xElement = res.Element("xml");

            if (xElement == null)
            {
                return("");
            }
            var element = xElement.Element("return_code");

            if (element == null)
            {
                return("");
            }
            var returnCode = element.Value;

            return(returnCode);
        }
        /// <summary>
        /// H5支付
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="hc"></param>
        /// <returns></returns>
        public ActionResult H5Pay(int productId, int hc)
        {
            {
                try
                {
                    //获取产品信息
                    var products = ProductModel.GetFakeProductList();
                    var product  = products.FirstOrDefault(z => z.Id == productId);
                    if (product == null || product.GetHashCode() != hc)
                    {
                        return(Content("商品信息不存在,或非法进入!1002"));
                    }

                    string openId = null;//此时在外部浏览器,无法或得到OpenId

                    string sp_billno = Request["order_no"];
                    if (string.IsNullOrEmpty(sp_billno))
                    {
                        //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                        sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
                                                  TenPayV3Util.BuildRandomStr(6));
                    }
                    else
                    {
                        sp_billno = Request["order_no"];
                    }

                    var timeStamp = TenPayV3Util.GetTimestamp();
                    var nonceStr  = TenPayV3Util.GetNoncestr();

                    var body  = product == null ? "test" : product.Name;
                    var price = product == null ? 100 : (int)product.Price * 100;
                    //var ip = Request.Params["REMOTE_ADDR"];
                    var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, openId, TenPayV3Info.Key, nonceStr);

                    var result = TenPayV3.Html5Order(xmlDataInfo); //调用统一订单接口
                                                                   //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);

                    /*
                     * result:{"device_info":"","trade_type":"MWEB","prepay_id":"wx20170810143223420ae5b0dd0537136306","code_url":"","mweb_url":"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20170810143223420ae5b0dd0537136306\u0026package=1505175207","appid":"wx669ef95216eef885","mch_id":"1241385402","sub_appid":"","sub_mch_id":"","nonce_str":"juTchIZyhXvZ2Rfy","sign":"5A37D55A897C854F64CCCC4C94CDAFE3","result_code":"SUCCESS","err_code":"","err_code_des":"","return_code":"SUCCESS","return_msg":null}
                     */
                    //return Json(result, JsonRequestBehavior.AllowGet);

                    var package = string.Format("prepay_id={0}", result.prepay_id);

                    ViewData["product"] = product;

                    ViewData["appId"]     = TenPayV3Info.AppId;
                    ViewData["timeStamp"] = timeStamp;
                    ViewData["nonceStr"]  = nonceStr;
                    ViewData["package"]   = package;
                    ViewData["paySign"]   = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);

                    //设置成功页面(也可以不设置,支付成功后默认返回来源地址)
                    var returnUrl =
                        string.Format("https://sdk.weixin.senparc.com/TenpayV3/H5PaySuccess?productId={0}&hc={1}",
                                      productId, hc);

                    var mwebUrl = result.mweb_url;
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        mwebUrl += string.Format("&redirect_url={0}", returnUrl.AsUrlData());
                    }

                    ViewData["MWebUrl"] = mwebUrl;

                    //临时记录订单信息,留给退款申请接口测试使用
                    Session["BillNo"]  = sp_billno;
                    Session["BillFee"] = price;

                    return(View());
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                    msg += "<br>" + ex.StackTrace;
                    msg += "<br>==Source==<br>" + ex.Source;

                    if (ex.InnerException != null)
                    {
                        msg += "<br>===InnerException===<br>" + ex.InnerException.Message;
                    }
                    return(Content(msg));
                }
            }
        }
示例#28
0
        /// <summary>
        /// 订单查询
        /// </summary>
        /// <param name="requestDto"></param>
        /// <returns></returns>
        public async Task <OrderQueryResult> OrderQuery(GetWeiXinPaymentBeforeRequestDto requestDto)
        {
            TenPayV3OrderQueryRequestData data = new TenPayV3OrderQueryRequestData(AppID, MerchantNumber, "wx0818171559664608e39c01920461325676", GetRandomString(16, false, true, true, false, string.Empty), "GDSPDD_IKJRMNLCCJ20190408181709", MerchantSecret);

            return(TenPayV3.OrderQuery(data));
        }
示例#29
0
        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));
            }
        }
示例#30
0
        public void ProcessRequest(HttpContext context)
        {
            Model.HG.A_HG_new_order Str = new Model.HG.A_HG_new_order();

            BLL.HG.Hg_list add = new BLL.HG.Hg_list();
            Dictionary <string, string> jsonDict = new Dictionary <string, string>();

            jsonDict = new Dictionary <string, string>();
            string case_ = context.Request.QueryString["case_"];

            if (case_ == "save")
            {
                //  string openid=context.Request.QueryString["openid"];
                string name      = context.Request.QueryString["name"];
                string phone     = context.Request.QueryString["phone"];
                string sex       = context.Request.QueryString["sex"];
                string money     = context.Request.QueryString["money"];
                string type_     = context.Request.QueryString["type_"];
                string time      = context.Request.QueryString["time"];
                string day       = context.Request.QueryString["day"];
                string adress    = context.Request.QueryString["adress"];
                string weixiname = context.Request.QueryString["weixinname"];
                string openid    = context.Request.QueryString["openid"];
                //   string total=context.Request.QueryString["total"];
                //   Str.Openid_ = openid;
                Str.Name_       = name;
                Str.Tel_        = phone;
                Str.Sex_        = sex;
                Str.Pick_many   = money;
                Str.Type_       = type_;
                Str.Time_       = time;
                Str.start_time  = DateTime.Now.ToString();//开始时间
                Str.Pick_day    = day;
                Str.Weixin_name = weixiname;
                Str.Openid_     = openid;
                int day_   = int.Parse(day);
                int money_ = int.Parse(money);
                int total_ = day_ * money_;
                Str.total = total_.ToString();
                string bb = DateTime.Now.Day.ToString() + GuidTo16String();//生成的订单号
                Str.Order_dd   = bb;
                Str.Order_from = "小程序";
                Str.Fw_zt      = "未支付";
                Str.Delet_     = "未删除";
                Str.Adress     = adress;
                int fal = add.Add_order_new(Str);
                //   Str.total = total;
                if (fal == 0)
                {
                    jsonDict.Add("order_dd", bb);
                    jsonDict.Add("errCode", "false");
                    jsonDict.Add("recontent", fal.ToString());
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                }
                else
                {
                    jsonDict.Add("order_dd", bb);
                    jsonDict.Add("errCode", "true");
                    jsonDict.Add("recontent", fal.ToString());
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                }
            }
            else if (case_ == "jujia")
            {
                {
                    //  string openid=context.Request.QueryString["openid"];
                    string name      = context.Request.QueryString["name"];
                    string phone     = context.Request.QueryString["phone"];
                    string sex       = context.Request.QueryString["sex"];
                    string money     = context.Request.QueryString["money"];
                    string type_     = context.Request.QueryString["type_"];
                    string time      = context.Request.QueryString["time"];
                    string day       = context.Request.QueryString["day"];
                    string adress    = context.Request.QueryString["adress"];
                    string weixiname = context.Request.QueryString["weixinname"];
                    string openid    = context.Request.QueryString["openid"];
                    //   string total=context.Request.QueryString["total"];
                    //   Str.Openid_ = openid;
                    Str.Name_       = name;
                    Str.Tel_        = phone;
                    Str.Sex_        = sex;
                    Str.Pick_many   = money;
                    Str.Type_       = type_;
                    Str.Time_       = time;
                    Str.start_time  = DateTime.Now.ToString();//开始时间
                    Str.Pick_day    = day;
                    Str.Weixin_name = weixiname;
                    Str.Openid_     = openid;

                    Str.total = money;
                    string bb = DateTime.Now.Day.ToString() + GuidTo16String();//生成的订单号
                    Str.Order_dd   = bb;
                    Str.Order_from = "小程序";
                    Str.Fw_zt      = "未支付";
                    Str.Delet_     = "未删除";
                    Str.Adress     = adress;
                    int fal = add.Add_order_new(Str);
                    //   Str.total = total;
                    if (fal == 0)
                    {
                        jsonDict.Add("order_dd", bb);
                        jsonDict.Add("errCode", "false");
                        jsonDict.Add("recontent", fal.ToString());
                        context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    }
                    else
                    {
                        jsonDict.Add("order_dd", bb);
                        jsonDict.Add("errCode", "true");
                        jsonDict.Add("recontent", fal.ToString());
                        context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    }
                }
            }
            else if (case_ == "order")
            {
                string openid = context.Request.QueryString["openid"];
                context.Response.ContentType = "text/json";
                context.Response.Write(MyCommFun.GetJsonByDataset(order_new(openid)));
            }
            else
            {
                order_dd = MyCommFun.QueryString("order");
                BLL.HG.Hg_list          order_T = new BLL.HG.Hg_list();
                Model.HG.A_HG_new_order model   = order_T.getorder(order_dd);
                string timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";
                //创建支付应答对象
                Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
                //初始化
                packageReqHandler.Init();

                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr  = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", "wx16650bedd9b0916a");                                                                  //公众账号ID
                packageReqHandler.SetParameter("mch_id", "1403543902");                                                                         //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
                packageReqHandler.SetParameter("body", model.Name_ + "服务");                                                                     //商品信息
                packageReqHandler.SetParameter("out_trade_no", order_dd);                                                                       //商家订单号
                packageReqHandler.SetParameter("total_fee", ((double.Parse(model.total)) * 100).ToString());                                    //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", context.Request.UserHostAddress);                                            //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + 44 + "|" + order_dd); //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
                packageReqHandler.SetParameter("openid", model.Openid_);                                                                        //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                packageReqHandler.SetParameter("sign", sign);                       //签名
                string data = packageReqHandler.ParseXML();


                var      result = TenPayV3.Unifiedorder(data);
                DateTime bb111  = new DateTime();
                WriteTextLog(bb111, result);
                var    res      = XDocument.Parse(result);
                string prepayId = res.Element("xml").Element("prepay_id").Value;

                //设置支付参数
                RequestHandler paySignReqHandler = new RequestHandler(null);
                paySignReqHandler.SetParameter("appId", "wx16650bedd9b0916a");
                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", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                payaddid        = "";
                paytimeStamp    = timeStamp;
                paynonceStr     = nonceStr;
                paypackageValue = string.Format("prepay_id={0}", prepayId);
                paypaySign      = paySign;
                litDate         = DateTime.Now.ToString();
                oreder_name     = model.Name_ + "服务预约";
                context.Response.ContentType = "text/json";
                pay_ bb = new pay_
                {
                    timeStamp = timeStamp,
                    nonceStr  = nonceStr,
                    paySign   = paySign,
                    signType  = "MD5",
                    package   = prepayId
                };
                string json_bill = JsonMapper.ToJson(bb);
                context.Response.Write(json_bill);
            }
        }