微信支付

第一步:添加捐赠信息和支付订单

#region//Myth:添加捐赠信息和形成支付订单
        /// <summary>
        /// 插入订单信息
        /// </summary>
        /// <param name="userId"></param>
        public void AddOrderInfo(string userId)
        {
            DonateModel donateInfo = new DonateModel();
            T_WxPayOrderInfo orderInfo = new T_WxPayOrderInfo();
            //捐赠信息
            donateInfo.ID = string.Format("{0}", Guid.NewGuid());
            donateInfo.UserID = Guid.Parse(userId);
            donateInfo.FundID = fundid;
            donateInfo.DonateAmount = this.other_raise_money.Value.Trim();
            donateInfo.TogetherDonateID = donateInfo.FundID;
            donateInfo.Blessing = string.IsNullOrEmpty(this.blessing2.Value.Trim()) ? "祝福母校" : this.blessing2.InnerText.Trim();
            donateInfo.IsSendPaper = this.IsSendPaper.Checked ? "1" : "0";//是否寄送发票

            //支付订单信息
            Guid orderID = Guid.Parse(donateInfo.ID);
            orderInfo.ID = orderID;
            orderInfo.UserID = Guid.Parse(userId);
            orderInfo.OrderNo = WxPayApi.GenerateOutTradeNo();
            orderInfo.GoodsId = Guid.Parse(fundid);//若非项目下发起的众筹项则次ID=项目ID
            orderInfo.GoodsType = Guid.Parse(fundid);
            orderInfo.Amount = Convert.ToDecimal(this.other_raise_money.Value.Trim());
            //插入捐赠信息和支付订单信息
            bool addorder = FundController.AddDonateProject(donateInfo, orderInfo);
            if (addorder)
            {
                //请求支付判断
                GetPayTypeWay(string.Format("{0}", orderID));
                //Response.Redirect("~/WxPayAPI/paypage/ProductPage.aspx?OrderID=" + orderID);
            }
            else
            {
                MessageBox.ShowAndRedirect(this.Page, "订单出错!请重新下单", this.Page.Request.Url.PathAndQuery);
            }
        }
        #endregion



第二步:插入捐赠信息和支付订单信息时需要事务处理AddDonateProject(donateInfo,orderInfo)

开启一个事物如果执行失败就回滚

 #region//Myth:事务处理捐款事项
        public static bool AddDonateProject(DonateModel donateInfo, T_WxPayOrderInfo orderInfo)
        {
            bool isok = false;
            try
            {
                //bool donorInfoIsok = InsertIntoDonorInfo(donorInfo);//插入捐款人员信息排除事务之外
                //事务处理订单和捐款事项
                using (TransactionScope ts = new TransactionScope())
                {
                    bool donatoInfoIsok = InsertIntoDonateInfo(donateInfo);//插入捐款信息
                    bool orderisok = new WxPayOrder().InserInToOrderInfo(orderInfo);//形成支付订单信息
                    if (donatoInfoIsok && orderisok)
                    {
                        isok = true;
                        ts.Complete();
                    }
                }
            }
            catch (Exception)
            {
                isok = false;
                throw;
            }
            return isok;
        }
        #endregion



第三步:判断支付方式GetPayTypeWay(OrderID)提交订单ID

#region//Myth:支付提交微信进行支付订单调用
        /// <summary>
        /// 请求支付判断
        /// </summary>
        /// <param name="OrderID"></param>
        public void GetPayTypeWay(string OrderID)
        {
            if (UserAccessStyle == "0") //微信端访问是0 app端访问是1
            {
                if (ConfigParameter.IsAliPay == "1") //判断是否有支付宝账号有则走选择支付方式无则直接支付
                {
                    var PathQ = Page.Request.Url.OriginalString.Replace("http","");
                    var urlpayway = string.Format("~/WxPayAPI/paypage/PayType.aspx?OrderID=" + OrderID + "&openid=" + UserOpenID + "&PathQ=" + PathQ);
                    Response.Redirect(urlpayway);
                }
                else
                {
                    WxCahtPayOrder(OrderID);
                }
            }
            else
            {
                var url = string.Format("~/WxPayAPI/paypage/ProductPage.aspx?OrderID=" + OrderID);
                //var url = string.Format("JsApiPayPage.aspx?tyption={0}&{1}", ConfigParameter.DonatePayment, OrderID);
                Response.Redirect(url);
                //Response.Write("<script>document.getElementById('btn_aptpay').onclick();</script>");
                //Page.ClientScript.RegisterStartupScript(Page.GetType(), "Aclick", "<script language=\"javascript\" >Aclick();</script");
            }
        }

第四步:发起微信支付

        //触发微信支付
        void bttWxPay_Click(object sender, EventArgs e)
        {
            string OrderID = Request.QueryString["OrderID"];
            WxCahtPayOrder(OrderID);
        }

        /// <summary>
        /// 发起微信支付
        /// </summary>
        /// <param name="OrderID"></param>
        public void WxCahtPayOrder(string OrderID)
        {
            ViewState["OrderID"] = OrderID;
            wxJsApiParam = new WxPayOrder().WxChatPayWayOrder(OrderID, UserOpenID, ref isPaynow, this, wxJsApiParam);
            if (string.IsNullOrEmpty(wxJsApiParam))
            {
                MessageBox.Show(this.Page, "支付出错,请联系管理员!");
            }
          
        }

第五步:向微信提交表单WxChartPayWayOrder(XXX)(最主要功能涉及到微信支付接口)

#region//Myth:形成表单发起微信支付请求
        /// <summary>
        /// 向微信递交支付订单
        /// </summary>
        /// <param name="OrderID"></param>
        /// <param name="openId"></param>
        /// <param name="isPaynow"></param>
        /// <param name="page"></param>
        /// <param name="wxJsApiParam"></param>
        /// <returns></returns>
        public string WxChatPayWayOrder(string OrderID, string openId, ref string isPaynow, Page page, string wxJsApiParam)
        {
            string openid = openId;
            if (!string.IsNullOrEmpty(openid) && !string.IsNullOrEmpty(OrderID))
            {
                //ViewState["OrderID"] = OrderID;
                string orderId = OrderID;
                if (!string.IsNullOrEmpty(orderId))
                {
                    T_WxPayOrderInfo orderinfo = GetOrderInfobyOrderId(orderId);//获取微信订单对象
                    //BindData(orderinfo);
                    string total_fee = orderinfo != null ? string.Format("{0}", orderinfo.AmountInt) : string.Empty;
                    //检测是否给当前页面传递了相关参数
                    if (string.IsNullOrEmpty(openid) || string.IsNullOrEmpty(total_fee))
                    {
                        //Response.Write("<span style='color:#FF0000;font-size:20px'>" + "页面传参出错,请返回重试" + "</span>");
                        //submit.Visible = false;
                        return wxJsApiParam;
                    }

                    //若传递了相关参数,则调统一下单接口,获得后续相关接口的入口参数
                    JsApiPay jsApiPay = new JsApiPay(page);
                    jsApiPay.openid = openid;
                    jsApiPay.total_fee = int.Parse(total_fee);
                    //JSAPI支付预处理
                    try
                    {
                        //创建订单对象 获取订单信息提交微信
                        WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(orderinfo);
                        wxJsApiParam = jsApiPay.GetJsApiParameters(); //获取H5调起JS API参数 
                        isPaynow = "1";
                        //Page.ClientScript.RegisterStartupScript(typeof(FundDetail), "callpay", "<script type='text/javascript'>callpay();</script>");
                    }
                    catch (Exception ex)
                    {
                        //submit.Visible = false;
                        new WxPayOrder().InsertError("向微信提交订单", ex.ToString());
                        //MessageBox.Show(this.Page, "支付参数出错,请联系管理员!");

                    }

                }

            }
            return wxJsApiParam;
        }
        #endregion

5.1 统一订单接口执行GetUnifiedOrderResult()

 /**
         * 调用统一下单,获得下单结果
         * @return 统一下单结果
         * @失败时抛异常WxPayException
         */
        public WxPayData GetUnifiedOrderResult(T_WxPayOrderInfo orderInfo)
        {
            //统一下单 
            WxPayData data = new WxPayData();
            data.SetValue("body", orderInfo.GoodName);//订单主题
            data.SetValue("attach", orderInfo.GoodName);//订单标题
            data.SetValue("out_trade_no", orderInfo.OrderNo);//WxPayApi.GenerateOutTradeNo() 订单编号
            data.SetValue("total_fee", total_fee);//金额 *100
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//订单创建时间戳
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//支付时间戳
            data.SetValue("goods_tag", orderInfo.GoodName);//订单标签
            data.SetValue("trade_type", "JSAPI");//支付方式
            data.SetValue("openid", openid);//

            orderInfo.PayType = string.Format("{0}", data.GetValue("trade_type"));
            orderInfo.Time_start = string.Format("{0}", data.GetValue("time_start"));
            orderInfo.Time_expire = string.Format("{0}", data.GetValue("time_expire"));
            //更新支付订单必要字段
            WxPayOrder ordercs = new WxPayOrder();
            bool Isupdate = ordercs.UpDateOrderInfoByOrderId(orderInfo);
            //完善统一下单参数
            WxPayData result = WxPayApi.UnifiedOrder(data);
            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                new WxPayOrder().InsertError("向微信申请凭证", string.Format("{0}", result.GetValue("return_code")) + string.Format("{0}", result.GetValue("return_msg")));
            }

            unifiedOrderResult = result;
            return result;
        }

完善同一订单参数UnifiedOrder()

/**
        * 
        * 统一下单
        * @param WxPaydata inputObj 提交给统一下单API的参数
        * @param int timeOut 超时时间
        * @throws WxPayException
        * @return 成功时返回,其他抛异常
        */
        public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            //检测必填参数
            if (!inputObj.IsSet("out_trade_no"))
            {
                throw new WxPayException("缺少统一支付接口必填参数out_trade_no!");
            }
            else if (!inputObj.IsSet("body"))
            {
                throw new WxPayException("缺少统一支付接口必填参数body!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new WxPayException("缺少统一支付接口必填参数total_fee!");
            }
            else if (!inputObj.IsSet("trade_type"))
            {
                throw new WxPayException("缺少统一支付接口必填参数trade_type!");
            }

            //关联参数
            if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
            {
                throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
            }
            if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
            {
                throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
            }

            //异步通知url未设置,则使用配置文件中的url
            if (!inputObj.IsSet("notify_url"))
            {
                inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url
            }

            inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
            inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
            inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);//终端ip	  	    
            inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串

            //签名
            inputObj.SetValue("sign", inputObj.MakeSign());
            string xml = inputObj.ToXml();

            var start = DateTime.Now;

            Log.Debug("WxPayApi", "UnfiedOrder request : " + xml);
            string response = HttpService.Post(xml, url, false, timeOut);//这里向微信发起了请求并获得了结果
            Log.Debug("WxPayApi", "UnfiedOrder response : " + response);

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WxPayData result = new WxPayData();
            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//测速上报

            return result;
        }

5.2 调用JSAPI接口GetJsApiParameters()

 /**
        *  
        * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数,
        * 微信浏览器调起JSAPI时的输入参数格式如下:
        * {
        *   "appId" : "wx2421b1c4370ec43b",     //公众号名称,由商户传入     
        *   "timeStamp":" 1395712654",         //时间戳,自1970年以来的秒数     
        *   "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串     
        *   "package" : "prepay_id=u802345jgfjsdfgsdg888",     
        *   "signType" : "MD5",         //微信签名方式:    
        *   "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
        * }
        * @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用
        * 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7
        * 
        */
        public string GetJsApiParameters()
        {
            Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");

            WxPayData jsApiParam = new WxPayData();
            jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
            jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
            jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
            jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
            jsApiParam.SetValue("signType", "MD5");
            jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

            string parameters = jsApiParam.ToJson();

            Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
            return parameters;
        }

将返回参数传递给js并用ajax提交

<script type="text/javascript">
         //调用微信JS api 支付
         var orderId = '<%=ViewState["OrderID"]%>';
         var PathQ = QueryString("PathQ");
         function jsApiCall() {
             var Isok = "";
             WeixinJSBridge.invoke('getBrandWCPayRequest',<%=wxJsApiParam%>,//josn串
            function (res)
            {
                WeixinJSBridge.log(res.err_msg);
                Isok = res.err_msg;
                //alert(JSON.stringify(res));
                //alert(res.err_code + res.err_desc + res.err_msg);
                if (res.err_msg === "get_brand_wcpay_request:ok") {
                    UpDate();
                    window.location.href = "../../Views/PaySuccess.aspx?OrderID=" + orderId+"&PathQ=" + PathQ;
                    return;
                }
                if (res.err_msg.indexOf(":ok") > -1) {
                    UpDate();
                    window.location.href = "../../Views/PaySuccess.aspx?OrderID=" + orderId+"&PathQ=" + PathQ;
                    return;
                }
            }
        );
            //alert("111" + Isok);
            if (Isok=== "get_brand_wcpay_request:ok") {
                UpDate();
                window.location.href = "../../Views/PaySuccess.aspx?OrderID=" + orderId+"&PathQ=" + PathQ;
                return;
            }
            if (Isok.indexOf(":ok") > -1) {
                UpDate();
                window.location.href = "../../Views/PaySuccess.aspx?OrderID=" + orderId+"&PathQ=" + PathQ;
                return;
            }
            //WeixinJSBridge.invoke('closeWindow',{},function(res){

            //    alert(res.err_msg);

            //});
        }

        function callpay() {
            if (typeof WeixinJSBridge == "undefined")
            {
                if (document.addEventListener)
                {
                    document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                }
                else if (document.attachEvent)
                {
                    document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                    document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                }
            }
            else
            {
                jsApiCall();
            }
        }
               
    </script>





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值