<%@ Page Language="C#" AutoEventWireup="true" Theme="" CodeBehind="PayOnline.aspx.cs"
    Inherits="PowerEasy.Module.General.WebSite.PayOnline.PayOnlineUI" EnableEventValidation="false" %>

<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="PowerEasy.Foundation" %>
<%@ Import Namespace="PowerEasy.Framework.Common" %>
<%@ Import Namespace="PowerEasy.Framework.Components" %>
<%@ Import Namespace="PowerEasy.Module.General.Model.Accessories" %>
<%@ Import Namespace="PowerEasy.Module.Shop.BusinessLogic" %>
<%@ Import Namespace="PowerEasy.Module.General.BusinessLogic.Accessories" %>
<%@ Import Namespace="PowerEasy.Module.Shop.Model" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>
        <asp:Localize ID="Localize10" Text="<%$ Res: PayOnline_PayOnline_Page , 在线支付 %>"
            runat="server" /></title>
</head>
<body>
    <asp:PlaceHolder ID="form1" runat="server">
        <table class="border" cellspacing="1">
            <tr class="title">
                <td>
                    <strong>
                        <asp:Localize ID="Localize1" Text="<%$ Res: PayOnline_PayOnline_Localize1 , 在线支付操作（确认支付款项） %>"
                            runat="server" /></strong>
                </td>
            </tr>
            <tr>
                <td class="tdbg">
                    <div class="p_center">
                        <table width="500" cellspacing="1" cellpadding="2" style="background-color: #CCCCCC;
                            margin: auto;">
                            <tr class="title">
                                <td colspan="2">
                                    <b>
                                        <asp:Localize ID="Localize2" Text="<%$ Res: PayOnline_PayOnline_Localize2 , 确 认 款 项 %>"
                                            runat="server" /></b>
                                </td>
                            </tr>
                            <tr class="tdbg">
                                <td style="width: 30%" align="right">
                                    <asp:Localize ID="Localize3" Text="<%$ Res: PayOnline_PayOnline_Localize3 , 支付平台： %>"
                                        runat="server" />
                                </td>
                                <td align="left">
                                    <asp:Label ID="LblPayPlatform" runat="server"></asp:Label>
                                </td>
                            </tr>
                            <tr class="tdbg">
                                <td align="right">
                                    <asp:Localize ID="Localize4" Text="<%$ Res: PayOnline_PayOnline_Localize4 , 支付序列号： %>"
                                        runat="server" />
                                </td>
                                <td align="left">
                                    <asp:Label ID="LblOid" runat="server"></asp:Label>
                                </td>
                            </tr>
                            <tr class="tdbg">
                                <td align="right">
                                    <asp:Localize ID="Localize5" Text="<%$ Res: PayOnline_PayOnline_Localize5 , 支付金额： %>"
                                        runat="server" />
                                </td>
                                <td align="left">
                                    <asp:Label ID="LblPayMoney" runat="server"></asp:Label>
                                </td>
                            </tr>
                            <tr class="tdbg">
                                <td align="right">
                                    <asp:Localize ID="Localize6" Text="<%$ Res: PayOnline_PayOnline_Localize6 , 手续费： %>"
                                        runat="server" />
                                </td>
                                <td align="left">
                                    <asp:Label ID="LblRate" runat="server"></asp:Label>
                                </td>
                            </tr>
                            <tr class="tdbg">
                                <td align="right">
                                    <asp:Localize ID="Localize7" Text="<%$ Res: PayOnline_PayOnline_Localize7 , 实际划款金额： %>"
                                        runat="server" />
                                </td>
                                <td align="left">
                                    <asp:Label ID="LblvMoney" runat="server"> </asp:Label>
                                </td>
                            </tr>
                            <asp:PlaceHolder ID="PlhCoupon" runat="server" Visible="false">
                                <tr class="tdbg">
                                    <td colspan="2">
                                        <iframe src='../Shop/UserCoupon.aspx?OrderID=<%= Request.QueryString["OrderID"] %>&PayPlatformId=<%= Request.QueryString["PayPlatformId"] %>'
                                            marginheight="0" marginwidth="0" frameborder="0" width="100%" height="30px" scrolling="no">
                                        </iframe>
                                    </td>
                                </tr>
                            </asp:PlaceHolder>
                            <tr class="tdbg">
                                <td colspan="2">
                                    <asp:Localize ID="LocOnlineMsg" Text="<%$ Res: PayOnline_PayOnline_Localize8 , 点击“确认支付”按钮后，将进入 %>"
                                        runat="server" /><asp:Label ID="LblPayPlatformName" runat="server"></asp:Label><asp:Localize
                                            ID="LocOnlineMsg2" Text="<%$ Res: PayOnline_PayOnline_Localize9 , 支付界面，在此页面选择您的银行卡。 %>"
                                            runat="server" />
                                </td>
                            </tr>
                            <tr class="tdbg">
                                <td colspan="2">
                                    <pe:ExtendedLabel HtmlEncode="false" ID="LblHiddenValue" runat="server"></pe:ExtendedLabel>
                                </td>
                            </tr>
                        </table>
                    </div>
                </td>
            </tr>
        </table>
    </asp:PlaceHolder>
</body>
</html>
<script runat="server" type="text/C#">
    protected override string PageFileName
    {
        get
        {
            if (RequestString("prevpage").ToLower() == "shoppingcheckout" && m_IsOpenPayPlatform)
            {
                return "~/PayOnline/PayOnlineRedirect.aspx";
            }
            return "~/PayOnline/PayOnline.aspx";
        }
    }

    /// <summary>
    /// 是否开启了在线支付平台
    /// </summary>
    private bool m_IsOpenPayPlatform = true;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (SiteConfig.ShopConfig.EnableCoupon && DataConverter.ToInt32(Request.QueryString["OrderId"]) > 0)
        {
            PlhCoupon.Visible = true;
        }

        string v_oid = "";                 //订单编号
        string v_amount = "";              //实际支付金额       
        string v_mid = "";                 //商户编号
        string v_url = "";                 //支付动作完成后返回到该url，支付结果以POST方式发送
        string payOnlineKey = "";        //MD5私钥

        decimal vmoney = 0;           //支付金额   
        int payPlatformId = 0;           //支付平台ID
        string md5string;             //订单MD5校验码
        int orderId;              //订单ID
        string userName = "";          //登录用户名
        string paymentNum = "";       //支付序号
        int pointAmount = 0;        //购买点券数


        orderId = DataConverter.ToInt32(Request.QueryString["OrderId"]);
		//暂时用Session["OrderID"]记录支付的orderid
        PEContext.Current.Context.Session["OrderID"] = orderId;
        payPlatformId = DataConverter.ToInt32(Request.QueryString["PayPlatformId"]);
        userName = PEContext.Current.User.UserName;
        pointAmount = DataConverter.ToInt32(Request.QueryString["PointAmount"]);

        if (orderId > 0)
        {
            vmoney = GetMoneyByOrserId(vmoney, orderId);
        }
        else
        {
            vmoney = GetMoneyByPointAmount(vmoney, payPlatformId, userName, pointAmount);
        }

        PayPlatformInfo payPlatformInfo = PayPlatform.GetPayPlatformById(payPlatformId);
        if (!payPlatformInfo.IsNull && !payPlatformInfo.IsDisabled && payPlatformInfo.MD5 != "3069" && payPlatformInfo.MD5 != "3056" && !string.IsNullOrEmpty(payPlatformInfo.MD5))
        {
            v_mid = payPlatformInfo.AccountsId;
            payOnlineKey = payPlatformInfo.MD5;
        }
        else
        {
            //在线支付平台未开通，模板用默认值
            m_IsOpenPayPlatform = false;
            
            if (RequestString("AddOrder") == "success")
            {
                string orderViewURL = "";
                if (PEContext.Current.User.Identity.IsAuthenticated)
                {
                    orderViewURL = "../User/Shop/ShowOrder.aspx?OrderId=" + orderId.ToString();
                }
                else
                {
                    OrderInfo oldOrderInfo = Order.GetOrderById(orderId);
                    orderViewURL = "../Shop/OrderForm.aspx?OrderNum=" + oldOrderInfo.OrderNum + "&Name=" + oldOrderInfo.ContacterName;
                }
                if (VersionHelper.IsBizIdea)
                {
                    WriteErrMsg("网站没有开通在线支付平台，订单已经成功提交。只有付款成功后，才能完成本次交易。", new string[] { "查看订单详情", orderViewURL });
                }
                else
                {
                    WriteErrMsg("网站没有开通在线支付平台，请与管理员联系。", new string[] { "返回上一页", "SelectPayPlatform.aspx?PointAmount=" + pointAmount.ToString() });
                }
            }
            else
            {
                WriteErrMsg(Resources.DynamicPageResources.PayOnline_PayOnline_NoToPayInfo, "~/Default.aspx");
            }
        }

        v_oid = PaymentLog.GetPaymentNum();    //构造支付ID

        if (payPlatformInfo.PayPlatformId == 11)  //快钱神州行
        {
            v_amount = decimal.Ceiling(vmoney + vmoney * DataConverter.ToDecimal(payPlatformInfo.Rate) / 100).ToString();
            vmoney = decimal.Ceiling(vmoney);
        }
        else
        {
            v_amount = decimal.Round(vmoney + vmoney * DataConverter.ToDecimal(payPlatformInfo.Rate) / 100, 2).ToString();
            vmoney = decimal.Round(vmoney, 2);
        }

        if (vmoney < 0.01M)
        {
            if (Order.GetOrderById(orderId).CouponId == 0)
            {
                WriteErrMsg(Resources.DynamicPageResources.PayOnline_PayOnline_RMBErr, "");
            }
            else
            {
                LocOnlineMsg.Text = Resources.DynamicPageResources.PayOnline_PayOnline_RMBErr;
                LblPayPlatformName.Visible = false;
                LocOnlineMsg2.Visible = false;
            }
        }

        paymentNum = v_oid;

        PaymentLogInfo paymentLogInfo = GetpaymentLogInfo(v_amount, vmoney, orderId, userName, paymentNum, pointAmount, payPlatformInfo);

        if (!PaymentLog.Add(paymentLogInfo))
        {
            WriteErrMsg(Resources.DynamicPageResources.PayOnline_PayOnline_SaveErr, "");
        }

        OrderInfo orderInfo = new OrderInfo(true);
        if (!HttpContext.Current.User.Identity.IsAuthenticated && (orderId > 0))
        {
            orderInfo = Order.GetOrderById(orderId);
        }

        DateTime datatime = DateTime.Now;
        string v_hms = datatime.ToString("HHmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
        string v_ymd = datatime.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);

        StringBuilder strHiddenField = new StringBuilder();
        StringBuilder md5Builder = new StringBuilder();
        StringBuilder v_urlBuilder = new StringBuilder(FullBasePath);    //构造返回URL

        string applicationName = PayOnline.GetApplicationName();
        if (!applicationName.EndsWith("/"))
        {
            applicationName = applicationName + "/";
        }
        bool isFabrication = false;

        string v_ShowResultUrl = v_urlBuilder.ToString() + "PayOnline/ShowResult.aspx?PayMessage=ok";


        switch (paymentLogInfo.PlatformId)
        {
            case 1:    //网银在线
                m_PayOnlineProviderUrl = "https://pay3.chinabank.com.cn/PayGate";
                //生成返回URL
                v_urlBuilder.Append("PayOnline/PayResultChinabank.aspx");
                v_url = v_urlBuilder.ToString();
                //生成MD5校验数据字符串
                md5Builder.Append(v_amount);
                md5Builder.Append("0");
                md5Builder.Append(v_oid);
                md5Builder.Append(v_mid);
                md5Builder.Append(v_url);
                md5Builder.Append(payOnlineKey);
                md5string = DataCrypto.MD5(md5Builder.ToString()).ToUpper();

                strHiddenField.Append("<input type='hidden' name='v_md5info' value='" + md5string + "'>");
                strHiddenField.Append("<input type='hidden' name='v_mid' value='" + v_mid + "'>");
                strHiddenField.Append("<input type='hidden' name='v_oid' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='v_amount' value='" + v_amount + "'>");
                strHiddenField.Append("<input type='hidden' name='v_moneytype'  value='0'>");
                strHiddenField.Append("<input type='hidden' name='v_url' value='" + v_url + "'>");
                break;

            case 2://'中国在线支付网
                m_PayOnlineProviderUrl = "http://www.ipay.cn/4.0/bank.shtml";
                v_urlBuilder.Append("PayOnline/PayResultIpay.aspx");
                v_url = v_urlBuilder.ToString();

                md5Builder.Append(v_mid);
                md5Builder.Append(v_oid);
                md5Builder.Append(v_amount);
                md5Builder.Append("test@Ipay.com.cn13800138000");
                md5Builder.Append(payOnlineKey);
                md5string = DataCrypto.MD5(md5Builder.ToString());

                strHiddenField.Append("<input type='hidden' name='v_mid' value='" + v_mid + "'>");
                strHiddenField.Append("<input type='hidden' name='v_oid' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='v_amount' value='" + v_amount + "'>");
                strHiddenField.Append("<input type='hidden' name='v_email' value='test@Ipay.com.cn'>");
                strHiddenField.Append("<input type='hidden' name='v_mobile' value='13800138000'>");
                strHiddenField.Append("<input type='hidden' name='v_md5' value='" + md5string + "'>");
                strHiddenField.Append("<input type='hidden' name='v_url' value='" + v_url + "'>");
                break;

            case 3://上海环迅
                m_PayOnlineProviderUrl = "http://pay.ips.com.cn/ipayment.aspx";
                //m_PayOnlineProviderUrl = "http://pay.ips.net.cn/ipayment.aspx";  //测试接口，配合测试帐号测试
                v_urlBuilder.Append("PayOnline/PayResultIps.aspx");
                v_url = v_urlBuilder.ToString();

                md5Builder.Append(v_oid);
                md5Builder.Append(v_amount);
                md5Builder.Append(v_ymd);
                md5Builder.Append("RMB");
                md5Builder.Append(payOnlineKey);
                md5string = DataCrypto.MD5(md5Builder.ToString());

                strHiddenField.Append("<input type='hidden' name='mer_code' value='" + v_mid + "'>");
                strHiddenField.Append("<input type='hidden' name='billNo' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='amount' value='" + v_amount + "'>");
                strHiddenField.Append("<input type='hidden' name='date' value='" + v_ymd + "'>");
                strHiddenField.Append("<input type='hidden' name='lang' value='GB'>");
                strHiddenField.Append("<input type='hidden' name='Gateway_type' value='01'>");
                strHiddenField.Append("<input type='hidden' name='Currency_Type' value='RMB'>");
                strHiddenField.Append("<input type='hidden' name='Merchanturl' value='" + v_url + "'>");
                strHiddenField.Append("<input type='hidden' name='OrderEncodeType' value='2'>");
                strHiddenField.Append("<input type='hidden' name='RetEncodeType' value='12'>");
                strHiddenField.Append("<input type='hidden' name='RetType' value='0'>");
                strHiddenField.Append("<input type='hidden' name='SignMD5' value='" + md5string + "'>");
                strHiddenField.Append("<input type='hidden' name='ServerUrl' value=''>");
                break;
            case 5://西部支付
                m_PayOnlineProviderUrl = "https://www.yeepay.com/app-merchant-proxy/node";
                v_urlBuilder.Append("PayOnline/PayResultYeepay.aspx");
                v_url = v_urlBuilder.ToString();
                CreateBuyUrl(v_mid, payOnlineKey, v_oid, v_amount, "CNY", "", "", "", v_url, "0", "", "utf-8", "1");
                m_PayOnlineProviderUrl +=  CreateBuyUrl(v_mid, payOnlineKey, v_oid, v_amount, "CNY", "", "", "", v_url, "0", "", "utf-8", "1");

                strHiddenField.Append("<input type='hidden' name='MerchantID' value='" + v_mid + "'>");
                strHiddenField.Append("<input type='hidden' name='OrderNumber' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='OrderAmount' value='" + v_amount + "'>");
                strHiddenField.Append("<input type='hidden' name='PostBackURL' value='" + v_url + "'>");

                //                p0_Cmd=Buy
                //&p1_MerId=10001126856
                //&p2_Order=asdfg
                //&p3_Amt=0.01
                //&p4_Cur=CNY
                //&p5_Pid=productname
                //&p6_Pcat=producttype
                //&p7_Pdesc=productdesc
                //&p8_Url=http%3a%2f%2flocalhost%3a4495%2fCallback.aspx
                //&p9_SAF=0
                //&pa_MP=userId+or+other
                //&pd_FrpId=utf-8
                //&pr_NeedResponse=1
                //&hmac=52818ec065d5983881cf4bb879f956ad
                break;
            case 6://易付通
                m_PayOnlineProviderUrl = "http://pay.xpay.cn/Pay.aspx";
                v_urlBuilder.Append("PayOnline/PayResultXpay.aspx");
                v_url = v_urlBuilder.ToString();

                md5Builder.Append(payOnlineKey);
                md5Builder.Append(":");
                md5Builder.Append(v_amount);
                md5Builder.Append(",");
                md5Builder.Append(v_oid);
                md5Builder.Append(",");
                md5Builder.Append(v_mid);
                md5Builder.Append(",bank,,sell,,2.0");
                md5string = DataCrypto.MD5(md5Builder.ToString());

                strHiddenField.Append("<input type='hidden' name='Tid' value='" + v_mid + "'>");
                strHiddenField.Append("<input type='hidden' name='Bid' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='Prc' value='" + v_amount + "'>");
                strHiddenField.Append("<input type='hidden' name='url' value='" + v_url + "'>");
                strHiddenField.Append("<input type='hidden' name='Card' value='bank'>");
                strHiddenField.Append("<input type='hidden' name='Scard' value=''>");
                strHiddenField.Append("<input type='hidden' name='ActionCode' value='sell'>");
                strHiddenField.Append("<input type='hidden' name='ActionParameter' value=''>");
                strHiddenField.Append("<input type='hidden' name='Ver' value='2.0'>");
                strHiddenField.Append("<input type='hidden' name='Pdt' value='" + applicationName + "'>");
                strHiddenField.Append("<input type='hidden' name='type' value=''>");
                strHiddenField.Append("<input type='hidden' name='lang' value='gb2312'>");
                strHiddenField.Append("<input type='hidden' name='md' value='" + md5string + "'>");
                break;

            case 7://云网支付
                m_PayOnlineProviderUrl = "https://www.cncard.net/purchase/getorder.asp";
                v_urlBuilder.Append("PayOnline/PayResultCncard.aspx");
                v_url = v_urlBuilder.ToString();

                md5Builder.Append(v_mid);
                md5Builder.Append(v_oid);
                md5Builder.Append(v_amount);
                md5Builder.Append(v_ymd);
                md5Builder.Append("01");
                md5Builder.Append(v_url);
                md5Builder.Append("00");
                md5Builder.Append(payOnlineKey);
                md5string = DataCrypto.MD5(md5Builder.ToString());

                strHiddenField.Append("<input type='hidden' name='c_mid' value='" + v_mid + "'>");
                strHiddenField.Append("<input type='hidden' name='c_order' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='c_orderamount' value='" + v_amount + "'>");
                strHiddenField.Append("<input type='hidden' name='c_ymd' value='" + v_ymd + "'>");
                strHiddenField.Append("<input type='hidden' name='c_moneytype' value='0'>");
                strHiddenField.Append("<input type='hidden' name='c_retflag' value='1'>");
                strHiddenField.Append("<input type='hidden' name='c_paygate' value=''>");
                strHiddenField.Append("<input type='hidden' name='c_returl' value='" + v_url + "'>");
                strHiddenField.Append("<input type='hidden' name='c_memo1' value=''>");
                strHiddenField.Append("<input type='hidden' name='c_memo2' value=''>");
                strHiddenField.Append("<input type='hidden' name='c_language' value='0'>");
                strHiddenField.Append("<input type='hidden' name='notifytype' value='0'>");
                strHiddenField.Append("<input type='hidden' name='c_signstr' value='" + md5string + "'>");
                break;
            case 8:    //支付宝
                m_PayOnlineProviderUrl = "https://mapi.alipay.com/gateway.do";
                v_urlBuilder.Append("PayOnline/PayResultAlipay.aspx");
                v_url = v_urlBuilder.ToString();


                //订单含有虚拟商品的情况
                if (orderId == 0)
                {
                    isFabrication = true;   //会员充值，视为虚拟物品
                }
                else
                {
                    isFabrication = PayOnline.IsFabrication(orderId);   //检测订单中的物品是否含有虚拟物品
                }

                string partner = "";
                if (payOnlineKey.IndexOf("|") > 0)
                {
                    string[] ArrMD5Key = payOnlineKey.Split(new char[] { '|' });
                    payOnlineKey = ArrMD5Key[0];
                    partner = ArrMD5Key[1];
                }

                if (isFabrication)
                {
                    md5Builder.Append("notify_url=" + v_url);
                    md5Builder.Append("&out_trade_no=" + v_oid);
                    md5Builder.Append("&partner=" + partner);
                    md5Builder.Append("&price=" + v_amount);
                    md5Builder.Append("&quantity=1");
                    md5Builder.Append("&return_url=" + v_ShowResultUrl);
                    md5Builder.Append("&seller_email=" + v_mid);
                    md5Builder.Append("&service=create_digital_goods_trade_p");
                    md5Builder.Append("&subject=" + v_oid);
                    md5Builder.Append("");
                    md5Builder.Append(payOnlineKey);
                    strHiddenField.Append("<input type='hidden' name='service' value='create_digital_goods_trade_p'>");
                }
                else
                {
                    md5Builder.Append("logistics_fee=0");
                    md5Builder.Append("&logistics_payment=SELLER_PAY");
                    md5Builder.Append("&logistics_type=EXPRESS");
                    md5Builder.Append("&notify_url=" + v_url);
                    md5Builder.Append("&out_trade_no=" + v_oid);
                    md5Builder.Append("&partner=" + partner);
                    md5Builder.Append("&payment_type=1");
                    md5Builder.Append("&price=" + v_amount);
                    md5Builder.Append("&quantity=1");
                    md5Builder.Append("&return_url=" + v_ShowResultUrl);
                    md5Builder.Append("&seller_email=" + v_mid);
                    md5Builder.Append("&service=trade_create_by_buyer");
                    md5Builder.Append("&subject=" + v_oid);
                    md5Builder.Append(payOnlineKey);
                    strHiddenField.Append("<input type='hidden' name='service' value='trade_create_by_buyer'>");
                    strHiddenField.Append("<input type='hidden' name='logistics_type' value='EXPRESS'>");
                    strHiddenField.Append("<input type='hidden' name='logistics_fee' value='0'>");
                    strHiddenField.Append("<input type='hidden' name='logistics_payment' value='SELLER_PAY'>");
                    strHiddenField.Append("<input type='hidden' name='payment_type' value='1'>");
                }
                md5string = DataCrypto.MD5(md5Builder.ToString());

                strHiddenField.Append("<input type='hidden' name='seller_email' value='" + v_mid + "'>");
                strHiddenField.Append("<input type='hidden' name='subject' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='out_trade_no' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='price' value='" + v_amount + "'>");
                strHiddenField.Append("<input type='hidden' name='partner' value='" + partner + "'>");
                strHiddenField.Append("<input type='hidden' name='quantity' value='1'>");
                strHiddenField.Append("<input type='hidden' name='notify_url' value='" + v_url + "'>");
                strHiddenField.Append("<input type='hidden' name='sign' value='" + md5string + "'>");
                strHiddenField.Append("<input type='hidden' name='sign_type' value='MD5'>");
                strHiddenField.Append("<input type='hidden' name='return_url' value='" + v_ShowResultUrl + "'>\n");
                break;
            case 9:      //快钱支付
                m_PayOnlineProviderUrl = "https://www.99bill.com/gateway/recvMerchantInfoAction.htm";
                //生成返回URL
                v_urlBuilder.Append("PayOnline/PayResult99bill.aspx");
                v_url = v_urlBuilder.ToString();

                string merchantAcctId = v_mid;   //网关账户号
                string key = payOnlineKey; //网关密钥
                string inputCharset = "3"; //1代表UTF-8; 2代表GBK; 3代表gb2312
                string pageUrl = v_url; //接受支付结果的页面地址
                string bgUrl = ""; //服务器接受支付结果的后台地址
                string version = "v2.0"; //网关版本.固定值
                string language = "1"; //1代表中文；2代表英文
                string signType = "1"; //1代表MD5签名
                string payerName = ""; //支付人姓名
                string payerContactType = ""; //支付人联系方式类型 1代表Email；2代表手机号
                string payerContact = ""; //支付人联系方式,只能选择Email或手机号
                string orderAmount = Convert.ToString(decimal.Ceiling(DataConverter.ToDecimal(v_amount) * 100)); //订单金额,以分为单位
                string orderTime = v_ymd + v_hms; //订单提交时间,14位数字
                string productName = ""; //商品名称
                string productNum = ""; //商品数量
                string productId = ""; //商品代码
                string productDesc = ""; //商品描述
                string ext1 = ""; //扩展字段1,在支付结束后原样返回给商户
                string ext2 = ""; //扩展字段2
                string payType = "00"; //支付方式,00：组合支付,显示快钱支持的各种支付方式,11：电话银行支付,12：快钱账户支付,13：线下支付,14：B2B支付
                string bankId = ""; //银行代码,实现直接跳转到银行页面去支付,具体代码参见 接口文档银行代码列表,只在payType=10时才需设置参数
                string redoFlag = "1"; //同一订单禁止重复提交标志:1代表同一订单号只允许提交1次,0表示同一订单号在没有支付成功的前提下可重复提交多次
                string pid = ""; //快钱的合作伙伴的账户号

                string signMsgVal = "";
                signMsgVal = PayOnline.AppendParam(signMsgVal, "inputCharset", inputCharset);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "pageUrl", pageUrl);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "bgUrl", bgUrl);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "version", version);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "language", language);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "signType", signType);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "merchantAcctId", merchantAcctId);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "payerName", payerName);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "payerContactType", payerContactType);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "payerContact", payerContact);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "orderId", v_oid);  //商户订单号
                signMsgVal = PayOnline.AppendParam(signMsgVal, "orderAmount", orderAmount);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "orderTime", orderTime);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "productName", productName);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "productNum", productNum);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "productId", productId);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "productDesc", productDesc);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "ext1", ext1);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "ext2", ext2);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "payType", payType);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "bankId", bankId);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "redoFlag", redoFlag);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "pid", pid);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "key", key);

                md5string = DataCrypto.MD5(signMsgVal).ToUpper();

                strHiddenField.Append("<input type='hidden' name='inputCharset' value='" + inputCharset + "'>\n");
                strHiddenField.Append("<input type='hidden' name='bgUrl' value='" + bgUrl + "'>\n");
                strHiddenField.Append("<input type='hidden' name='pageUrl' value='" + pageUrl + "'>\n");
                strHiddenField.Append("<input type='hidden' name='version' value='" + version + "'>\n");
                strHiddenField.Append("<input type='hidden' name='language' value='" + language + "'>\n");
                strHiddenField.Append("<input type='hidden' name='signType' value='" + signType + "'>\n");
                strHiddenField.Append("<input type='hidden' name='signMsg' value='" + md5string + "'>\n");
                strHiddenField.Append("<input type='hidden' name='merchantAcctId' value='" + merchantAcctId + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payerName' value='" + payerName + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payerContactType' value='" + payerContactType + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payerContact' value='" + payerContact + "'>\n");
                strHiddenField.Append("<input type='hidden' name='orderId' value='" + v_oid + "'>\n");
                strHiddenField.Append("<input type='hidden' name='orderAmount' value='" + orderAmount + "'>\n");
                strHiddenField.Append("<input type='hidden' name='orderTime' value='" + orderTime + "'>\n");
                strHiddenField.Append("<input type='hidden' name='productName' value='" + productName + "'>\n");
                strHiddenField.Append("<input type='hidden' name='productNum' value='" + productNum + "'>\n");
                strHiddenField.Append("<input type='hidden' name='productId' value='" + productId + "'>\n");
                strHiddenField.Append("<input type='hidden' name='productDesc' value='" + productDesc + "'>\n");
                strHiddenField.Append("<input type='hidden' name='ext1' value='" + ext1 + "'>\n");
                strHiddenField.Append("<input type='hidden' name='ext2' value='" + ext2 + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payType' value='" + payType + "'>\n");
                strHiddenField.Append("<input type='hidden' name='bankId' value='" + bankId + "'>\n");
                strHiddenField.Append("<input type='hidden' name='redoFlag' value='" + redoFlag + "'>\n");
                strHiddenField.Append("<input type='hidden' name='pid' value='" + pid + "'>\n");
                break;
            case 11:  //快钱神州行
                m_PayOnlineProviderUrl = "https://www.99bill.com/szxgateway/recvMerchantInfoAction.htm";
                //生成返回URL
                v_urlBuilder.Append("PayOnline/PayResult99billSzx.aspx");
                v_url = v_urlBuilder.ToString();

                merchantAcctId = v_mid; //神州行网关账户号
                key = payOnlineKey; //设置人民币网关密钥
                inputCharset = "3"; //1代表UTF-8; 2代表GBK; 3代表gb2312
                bgUrl = ""; //服务器接受支付结果的后台地址
                pageUrl = v_url; //接受支付结果的页面地址
                version = "v2.0"; //网关版本.固定值
                language = "1"; //1代表中文；2代表英文
                signType = "1"; //签名类型.固定值
                payerName = ""; //支付人姓名
                payerContactType = ""; //支付人联系方式类型,1代表Email；2代表手机号
                payerContact = ""; //支付人联系方式,只能选择Email或手机号
                orderAmount = Convert.ToString(decimal.Ceiling(DataConverter.ToDecimal(v_amount) * 100)); //订单金额,以分为单位，必须是整型数字
                orderTime = v_ymd + v_hms; //订单提交时间
                productName = ""; //商品名称
                productNum = ""; //商品数量
                productId = ""; //商品代码
                productDesc = ""; //商品描述
                ext1 = ""; //扩展字段1
                ext2 = ""; //扩展字段2
                payType = "00"; //只能选择00,代表支持神州行卡和快钱帐户支付
                string cardNumber = ""; //神州行卡序号,仅在商户定制了神州行卡密直连功能时填写
                string cardPwd = ""; //神州行卡密码,仅在商户定制了神州行卡密直连功能时填写
                //全额支付标志       ////0代表卡面额小于订单金额时返回支付结果为失败；1代表卡面额小于订单金额是返回支付结果为成功，同时订单金额和实际支付金额都为神州行卡的面额.如果商户定制神州行卡密直连时，本参数固定值为1
                string fullAmountFlag = "0"; //0代表卡面额小于订单金额时返回支付结果为失败

                //请务必按照如下顺序和规则组成加密串！
                signMsgVal = "";
                signMsgVal = PayOnline.AppendParam(signMsgVal, "inputCharset", inputCharset);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "bgUrl", bgUrl);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "pageUrl", pageUrl);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "version", version);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "language", language);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "signType", signType);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "merchantAcctId", merchantAcctId);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "payerName", payerName);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "payerContactType", payerContactType);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "payerContact", payerContact);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "orderId", v_oid);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "orderAmount", orderAmount);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "payType", payType);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "cardNumber", cardNumber);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "cardPwd", cardPwd);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "fullAmountFlag", fullAmountFlag);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "orderTime", orderTime);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "productName", productName);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "productNum", productNum);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "productId", productId);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "productDesc", productDesc);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "ext1", ext1);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "ext2", ext2);
                signMsgVal = PayOnline.AppendParam(signMsgVal, "key", key);
                md5string = DataCrypto.MD5(signMsgVal).ToUpper();

                strHiddenField.Append("<input type='hidden' name='inputCharset' value='" + inputCharset + "'>\n");
                strHiddenField.Append("<input type='hidden' name='bgUrl' value='" + bgUrl + "'>\n");
                strHiddenField.Append("<input type='hidden' name='pageUrl' value='" + pageUrl + "'>\n");
                strHiddenField.Append("<input type='hidden' name='version' value='" + version + "'>\n");
                strHiddenField.Append("<input type='hidden' name='language' value='" + language + "'>\n");
                strHiddenField.Append("<input type='hidden' name='signType' value='" + signType + "'>\n");
                strHiddenField.Append("<input type='hidden' name='merchantAcctId' value='" + merchantAcctId + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payerName' value='" + payerName + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payerContactType' value='" + payerContactType + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payerContact' value='" + payerContact + "'>\n");
                strHiddenField.Append("<input type='hidden' name='orderId' value='" + v_oid + "'>\n");
                strHiddenField.Append("<input type='hidden' name='orderAmount' value='" + orderAmount + "'>\n");
                strHiddenField.Append("<input type='hidden' name='orderTime' value='" + orderTime + "'>\n");
                strHiddenField.Append("<input type='hidden' name='productName' value='" + productName + "'>\n");
                strHiddenField.Append("<input type='hidden' name='productNum' value='" + productNum + "'>\n");
                strHiddenField.Append("<input type='hidden' name='productId' value='" + productId + "'>\n");
                strHiddenField.Append("<input type='hidden' name='productDesc' value='" + productDesc + "'>\n");
                strHiddenField.Append("<input type='hidden' name='ext1' value='" + ext1 + "'>\n");
                strHiddenField.Append("<input type='hidden' name='ext2' value='" + ext2 + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payType' value='" + payType + "'>\n");
                strHiddenField.Append("<input type='hidden' name='fullAmountFlag' value='" + fullAmountFlag + "'>\n");
                strHiddenField.Append("<input type='hidden' name='cardNumber' value='" + cardNumber + "'>\n");
                strHiddenField.Append("<input type='hidden' name='cardPwd' value='" + cardPwd + "'>\n");
                strHiddenField.Append("<input type='hidden' name='signMsg' value='" + md5string + "'>\n");
                break;
            case 12:   //支付宝即时到帐
                m_PayOnlineProviderUrl = "https://mapi.alipay.com/gateway.do";
                v_urlBuilder.Append("PayOnline/PayResultAlipayInstant.aspx");
                v_url = v_urlBuilder.ToString();
                v_ShowResultUrl = v_ShowResultUrl + "&PaymentNum=" + v_oid;
                partner = "";
                if (payOnlineKey.IndexOf("|") > 0)
                {
                    string[] ArrMD5Key = payOnlineKey.Split(new char[] { '|' });
                    payOnlineKey = ArrMD5Key[0];
                    partner = ArrMD5Key[1];
                }

                md5Builder.Append("discount=0");
                md5Builder.Append("&notify_url=" + v_url);
                md5Builder.Append("&out_trade_no=" + v_oid);
                md5Builder.Append("&partner=" + partner);
                md5Builder.Append("&payment_type=1");
                md5Builder.Append("&price=" + v_amount);
                md5Builder.Append("&quantity=1");
                md5Builder.Append("&return_url=" + v_ShowResultUrl);
                md5Builder.Append("&seller_email=" + v_mid);
                md5Builder.Append("&service=create_direct_pay_by_user");
                md5Builder.Append("&subject=" + v_oid);
                md5Builder.Append(payOnlineKey);
                md5string = DataCrypto.MD5(md5Builder.ToString());

                strHiddenField.Append("<input type='hidden' name='discount' value='0'>\n");
                strHiddenField.Append("<input type='hidden' name='notify_url' value='" + v_url + "'>\n");
                strHiddenField.Append("<input type='hidden' name='out_trade_no' value='" + v_oid + "'>\n");
                strHiddenField.Append("<input type='hidden' name='payment_type' value='1'>\n");
                strHiddenField.Append("<input type='hidden' name='partner' value='" + partner + "'>\n");
                strHiddenField.Append("<input type='hidden' name='price' value='" + v_amount + "'>\n");
                strHiddenField.Append("<input type='hidden' name='quantity' value='1'>\n");
                strHiddenField.Append("<input type='hidden' name='seller_email' value='" + v_mid + "'>\n");
                strHiddenField.Append("<input type='hidden' name='service' value='create_direct_pay_by_user'>\n");
                strHiddenField.Append("<input type='hidden' name='subject' value='" + v_oid + "'>\n");
                strHiddenField.Append("<input type='hidden' name='sign' value='" + md5string + "'>\n");
                strHiddenField.Append("<input type='hidden' name='sign_type' value='MD5'>\n");
                strHiddenField.Append("<input type='hidden' name='return_url' value='" + v_ShowResultUrl + "'>\n");
                break;
            case 13: //财付通
                v_urlBuilder.Append("PayOnline/PayResultTenpay.aspx");
                v_url = v_urlBuilder.ToString();

                //string transaction_id = v_mid + v_ymd + v_oid.Substring(0,10);
                string transaction_id = v_mid + v_ymd + v_oid.Substring(v_oid.Length - 10, 10);


                m_PayOnlineProviderUrl = "https://www.tenpay.com/cgi-bin/v1.0/pay_gate.cgi";
                string amount = Convert.ToString(decimal.Round(DataConverter.ToDecimal(v_amount) * 100, 0));
                string spbill_create_ip = getRealIp();
                md5string = "cmdno=1&date=" + v_ymd + "&bargainor_id=" + v_mid + "&transaction_id=" + transaction_id + "&sp_billno=" + v_oid + "&total_fee=" + amount + "&fee_type=1&return_url=" + v_url + "&attach=my_magic_string&spbill_create_ip=" + spbill_create_ip + "&key=" + payOnlineKey;
                md5string = DataCrypto.MD5(md5string);
                strHiddenField.Append("<input type='hidden' name='cmdno' value='1'>\n");        //业务代码,1表示支付
                strHiddenField.Append("<input type='hidden' name='date' value='" + v_ymd + "'>\n");       //商户日期
                strHiddenField.Append("<input type='hidden' name='bank_type' value='0'>\n");        //银行类型:财付通,0
                strHiddenField.Append("<input type='hidden' name='desc' value='" + v_oid + "'>\n");       //交易的商品名称
                strHiddenField.Append("<input type='hidden' name='purchaser_id' value=''>\n");       //用户(买方)的财付通帐户,可以为空
                strHiddenField.Append("<input type='hidden' name='bargainor_id' value='" + v_mid + "'>\n");       //商家的商户号
                strHiddenField.Append("<input type='hidden' name='transaction_id' value='" + transaction_id + "'>\n");      //交易号(订单号)
                strHiddenField.Append("<input type='hidden' name='sp_billno' value='" + v_oid + "'>\n");       //商户系统内部的订单号
                strHiddenField.Append("<input type='hidden' name='total_fee' value='" + amount + "'>\n");    //总金额，以分为单位
                strHiddenField.Append("<input type='hidden' name='fee_type' value='1'>\n");      //现金支付币种,1人民币
                strHiddenField.Append("<input type='hidden' name='return_url' value='" + v_url + "'>\n");    //接收财付通返回结果的URL
                strHiddenField.Append("<input type='hidden' name='attach' value='my_magic_string'>\n");      //商家数据包，原样返回
                strHiddenField.Append("<input type='hidden' name='sign' value='" + md5string + "'>\n");     //MD5签名
                strHiddenField.Append("<input type='hidden' name='spbill_create_ip' value='" + spbill_create_ip + "'>\n");     //财付通风险防范参数      
                break;
            case 15://财付通中介支付
                m_PayOnlineProviderUrl = "https://www.tenpay.com/cgi-bin/med/show_opentrans.cgi";

                version = "2";//	否	整数	[1,4]	版本号，取值如下：1：先前版本。2：本次更新的版本。对于旧版本，不此字段，对于新版本，此字段必填。
                int cmdno = 12;//	是	整数	[1,4]	任务代码，暂取定值：12
                int encode_type = 1;//	否	整数	[1,2]	1：GB2312编码，默认为GB2312编码。                2：UTF-8编码。
                string chnid = v_mid;//	否	字符串	[1,65]	平台提供者的财付通账号
                string seller = v_mid;//	是	字符串	[1,65]	收款方财付通账号
                string mch_name = v_oid;//	否	字符串	[1,32]	商品名称，不能包含<>’”%特殊字符
                string mch_price = Convert.ToString(decimal.Round(DataConverter.ToDecimal(v_amount) * 100, 0));//	否	整数	[1,10]	商品总价，单位为分。而财付通界面不再允许选择数量
                string transport_desc = v_mid + v_ymd + v_oid.Substring(v_oid.Length - 10, 10);//	否	字符串	[32]	物流公司或物流方式说明
                int transport_fee = 0;//	否	整数	[1,10]	需买方另支付的物流费用。如已包含在商品价格中，请填写0。如果不填，默认为0。
                string mch_desc = "caifutong";//	否	字符串	[1,64]	交易说明，不能包含<>’”%特殊字符
                int need_buyerinfo = 2;//	否	整数	[0,1]	是否需要在财付通填定物流信息，1：需要，2：不需要。
                int mch_type = 1;//	否	整数	[1,1]	交易类型：1、实物交易，2、虚拟交易。
                string mch_vno = v_oid;//	否	整数	[12]	商家的定单号
                string mch_returl = v_urlBuilder.ToString() + "PayOnline/PayResultTenpayMed.aspx";//	否	字符串	[1,255]	回调通知URL,如果cmdno为12且此字段填写有效回调链接,财付通将把交易相关信息通知给此URL,通知格式如下述.3.4节
                string show_url = v_urlBuilder.ToString() + "PayOnline/PayResultTenpayMedShow.aspx";//	否	字符串	[1,255]	支付后的商户支付结果展示页面。
                string attach = v_oid;//	否	字符串	[1,200]	该参数财付通不做处理。回调时原样返回。为商户可能的个性化应用预留。
                string sign;//	是	字符串	[32,32]	Md5签名信息，签名方法如下：
                //1、	对所有请求字段，其值为空的不加入MD5验证
                //2、	对所有请求字段，按字段名的ASCII顺序进行连接，连接方式同URL参数连接方式。
                //3、	Key=总是附加在签名串的最后，不参与ASCII排序。

                StringBuilder buf = new StringBuilder();
                AddParameter(buf, "attach", attach);
                AddParameter(buf, "chnid", chnid);
                AddParameter(buf, "cmdno", (cmdno).ToString());
                AddParameter(buf, "encode_type", (encode_type).ToString());
                AddParameter(buf, "mch_desc", mch_desc);
                AddParameter(buf, "mch_name", mch_name);
                AddParameter(buf, "mch_price", (mch_price).ToString());
                AddParameter(buf, "mch_returl", mch_returl);
                AddParameter(buf, "mch_type", (mch_type).ToString());
                AddParameter(buf, "mch_vno", mch_vno.ToString());
                AddParameter(buf, "need_buyerinfo", (need_buyerinfo).ToString());
                AddParameter(buf, "seller", seller);
                AddParameter(buf, "show_url", show_url);
                AddParameter(buf, "transport_desc", transport_desc);
                AddParameter(buf, "transport_fee", (transport_fee).ToString());
                AddParameter(buf, "version", version.ToString());
                AddParameter(buf, "key", payOnlineKey);

                sign = DataCrypto.MD5(buf.ToString());

                m_PayOnlineProviderUrl = m_PayOnlineProviderUrl + "?attach=" + attach + "&chnid=" + chnid + "&cmdno=" + cmdno + "&encode_type=" + encode_type + "&mch_desc=" + mch_desc
                    + "&mch_name=" + mch_name + "&mch_price=" + mch_price + "&mch_returl="
                    + mch_returl + "&mch_type=" + mch_type + "&mch_vno=" + mch_vno + "&need_buyerinfo=" + need_buyerinfo + "&seller=" + seller
                    + "&show_url=" + show_url + "&transport_desc=" + transport_desc + "&transport_fee=" + transport_fee + "&version=" + version + "&sign=" + sign;
                break;
            case 16://支付宝担保交易接口
                m_PayOnlineProviderUrl = "https://mapi.alipay.com/gateway.do?_input_charset=utf-8";
                string v_ShowOrderUrl = string.Empty;
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    v_ShowOrderUrl = v_urlBuilder.ToString() + "User/Shop/ShowOrder.aspx?OrderId=" + orderId.ToString();
                }
                else
                {
                    if (!orderInfo.IsNull)
                    {
                        v_ShowOrderUrl = v_urlBuilder.ToString() + "Shop/OrderForm.aspx?OrderNum=" + orderInfo.OrderNum + "&Name=" + DataSecurity.UrlEncode(orderInfo.ContacterName);

                    }
                }

                v_urlBuilder.Append("PayOnline/PayResultAlipayGuarantee.aspx");
                v_url = v_urlBuilder.ToString();
                v_ShowResultUrl = v_ShowResultUrl + "&PaymentNum=" + v_oid;
                partner = "";
                if (payOnlineKey.IndexOf("|") > 0)
                {
                    string[] ArrMD5Key = payOnlineKey.Split(new char[] { '|' });
                    payOnlineKey = ArrMD5Key[0];
                    partner = ArrMD5Key[1];
                }
                md5Builder.Append("_input_charset=utf-8");                  //编码类型，完全根据客户自身的项目的编码格式而定，千万不要填错。否则极其容易造成MD5加密错误。
                md5Builder.Append("&logistics_fee=0");                      //物流配送费用
                md5Builder.Append("&logistics_payment=SELLER_PAY");         //物流配送费用付款方式：SELLER_PAY(卖家支付)、BUYER_PAY(买家支付)、BUYER_PAY_AFTER_RECEIVE(货到付款)
                md5Builder.Append("&logistics_type=EXPRESS");               //物流配送方式：POST(平邮)、EMS(EMS)、EXPRESS(其他快递)
                md5Builder.Append("&notify_url=" + v_url);                  //针对该交易的交易状态同步通知接收URL。
                md5Builder.Append("&out_trade_no=" + v_oid);                //客户自己的订单号，（现取系统时间，可改成网站自己的变量），订单号必须在自身订单系统中保持唯一性
                md5Builder.Append("&partner=" + partner);                   //商户ID，合作身份者ID，合作伙伴ID
                md5Builder.Append("&payment_type=1");                       //支付类型
                md5Builder.Append("&price=" + v_amount);                    //商品价格，也可称为订单的总金额
                md5Builder.Append("&quantity=1");                           //商品数量，当该支付被当作是订单而非单个商品时，数量写为“1”
                md5Builder.Append("&return_url=" + v_ShowResultUrl);        //服务器返回url（return_Alipay_Notify.asp文件所在路经），必须是完整的路径地址
                md5Builder.Append("&seller_email=" + v_mid);                //商家签约时的支付宝帐号，即收款的支付宝帐号
                md5Builder.Append("&service=create_partner_trade_by_buyer");//服务名称，这个是识别是何接口实现何功能的标识，请勿修改
                md5Builder.Append("&show_url=" + v_ShowOrderUrl);           //展示地址，即在支付页面时，商品名称旁边的“详情”的链接地址。
                md5Builder.Append("&subject=" + v_oid);                     //商品名称，也可称为订单名称，该接口并不是单一的只能买一样东西，可把一次支付当作一次下订单
                md5Builder.Append(payOnlineKey);
                md5string = DataCrypto.MD5(md5Builder.ToString());

                strHiddenField.Append("<input type='hidden' name='logistics_type' value='EXPRESS'>");
                strHiddenField.Append("<input type='hidden' name='logistics_fee' value='0'>");
                strHiddenField.Append("<input type='hidden' name='logistics_payment' value='SELLER_PAY'>");
                strHiddenField.Append("<input type='hidden' name='notify_url' value='" + v_url + "'>");
                strHiddenField.Append("<input type='hidden' name='out_trade_no' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='partner' value='" + partner + "'>");
                strHiddenField.Append("<input type='hidden' name='payment_type' value='1'>");
                strHiddenField.Append("<input type='hidden' name='price' value='" + v_amount + "'>");
                strHiddenField.Append("<input type='hidden' name='quantity' value='1'>\n");
                strHiddenField.Append("<input type='hidden' name='return_url' value='" + v_ShowResultUrl + "'>");
                strHiddenField.Append("<input type='hidden' name='seller_email' value='" + v_mid + "'>");
                strHiddenField.Append("<input type='hidden' name='service' value='create_partner_trade_by_buyer'>");
                strHiddenField.Append("<input type='hidden' name='show_url' value='" + v_ShowOrderUrl + "'>");
                strHiddenField.Append("<input type='hidden' name='subject' value='" + v_oid + "'>");
                strHiddenField.Append("<input type='hidden' name='sign' value='" + md5string + "'>");
                strHiddenField.Append("<input type='hidden' name='sign_type' value='MD5'>\n");
                break;
            case 1000://银联网付通
                //投产用的地址 https://www.gnete.com/bin/scripts/OpenVendor/gnete/V34/GetOvOrder.asp 
                //测试用的地址 http://test.gnete.com/Bin/Scripts/OpenVendor/Gnete/V34/GetOvOrder.asp
                m_PayOnlineProviderUrl = "https://www.gnete.com/bin/scripts/OpenVendor/gnete/V34/GetOvOrder.asp";
                v_urlBuilder.Append("PayOnline/PayResultChinaPay.aspx");
                string MerId = v_mid;                                           //商户ID参数	
                string OrderNo = v_oid;                                         //商户订单号
                string OrderAmount = v_amount;                                  //订单金额，格式：元.角分
                string CurrCode = "CNY";                                        //货支付结果接收URL币代码，值为：CNY
                string CallBackUrl = v_urlBuilder.ToString();                   //支付结果接收URL
                string ResultMode = "0";                                        //支付结果返回方式(0-成功和失败支付结果均返回；1-仅返回成功支付结果)
                string Reserved01 = "";                                         //保留域1
                string Reserved02 = "";                                         //保留域
                string SendCertPath = Server.MapPath("~/PayOnline/ChinaPay/MERCHANT.pfx");          //发送方证书路径(商户证书)
                string RcvCertPath = Server.MapPath("~/PayOnline/ChinaPay/GNETEWEB-TEST.cer");     //接收方证书路径(银联证书)
                string SendCertPWD = payOnlineKey;                             //发送方证书密码(商户证书) 12345678

                string SourceText = "MerId=" + MerId + "&" + "OrderNo=" + OrderNo + "&"
                    + "OrderAmount=" + OrderAmount + "&" + "CurrCode=" + CurrCode + "&"
                    + "CallBackUrl=" + CallBackUrl + "&" + "BankCode=" + "&"
                    + "ResultMode=" + ResultMode + "&" + "Reserved01=" + Reserved01 + "&"
                    + "Reserved02=" + Reserved02;

                OpenVendorV34.NetTranClass netTran = new OpenVendorV34.NetTranClass();

                string encrypteMsg = string.Empty;//使用接收方证书对订单原始数据进行加密

                if (netTran.EncryptMsg(SourceText, RcvCertPath) == 0)
                {
                    encrypteMsg = netTran.LastResult;
                }
                else
                {
                    WriteErrMsg(netTran.LastErrMsg);
                }

                string signedMsg = string.Empty;//使用发送方证书对订单原始数据进行签名

                if (netTran.SignMsg(SourceText, SendCertPath, SendCertPWD) == 0)
                {
                    signedMsg = netTran.LastResult;
                }
                else
                {
                    Response.Write(netTran.LastErrMsg);
                }
                strHiddenField.AppendFormat("<input type='hidden' name='EncodeMsg' value='{0}'>", encrypteMsg);
                strHiddenField.AppendFormat("<input type='hidden' name='SignMsg' value='{0}'>", signedMsg);
                break;
            default:
                WriteErrMsg(Resources.DynamicPageResources.PayOnline_PayOnline_Err);
                break;
        }
        string newForm = "<form method=\"post\" action='" + m_PayOnlineProviderUrl + "' id=\"form2\" >";
        string redirectcft = string.Empty;
        string styleStr = RequestString("prevpage").ToLower() == "shoppingcheckout" ? "style=\"display:none\"" : "";
        if (paymentLogInfo.PlatformId == 15)
        {
            redirectcft = "<input type=\"button\" class=\"inputbutton\" " + styleStr + " id=\"Cft\" value=\"" + Resources.DynamicPageResources.PayOnline_PayOnline_YesToPay + "\" onclick=\"window.location.href='" + m_PayOnlineProviderUrl + "'\" />";
        }
        else
        {
            if (vmoney >= 0.01M)
            {
                redirectcft = "<input type=\"submit\" id=\"submit\" class=\"inputbutton\" " + styleStr + "  value=\"" + Resources.DynamicPageResources.PayOnline_PayOnline_YesToPay + "\">";
            }
        }
        string endFrom = redirectcft;
        if (RequestString("prevpage").ToLower() == "shoppingcheckout")
        {
            string clickObj = paymentLogInfo.PlatformId == 15 ? "Cft" : "submit";
            endFrom += "<script>document.getElementById(\"" + clickObj + "\").click();";
            endFrom += "if(window.parent!=null&&window.parent.ChangeButton !=undefined){parent.ChangeButton();}";
            endFrom += "</";
            endFrom += "script>";
            endFrom += "</form>";
            m_HiddenValue = newForm + strHiddenField.ToString() + endFrom;
            Response.Write(m_HiddenValue);
        }
        else
        {
            endFrom += "<div class=\"payonline_tips\">完成支付之后，你还可以：";
            if (vmoney >= 0.01M)
            {
                endFrom += " <a href=\"../User/Info/PaymentLog.aspx\" id=\"Cancel\">返回支付明细</a> ";
            }
            endFrom += "  <a href=\"../User/Default.aspx\" id='GotoUserCenter'>" + Resources.DynamicPageResources.PayOnline_PayOnline_InUser + "</a> ";
            if (orderId > 0)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    endFrom += "  <a href=\"../User/Shop/ShowOrder.aspx?OrderId=" + orderId.ToString() + "\" id='GotoUserCenter2'>" + Resources.DynamicPageResources.PayOnline_PayOnline_LookOrders + "</a> ";
                }
                else
                {
                    endFrom += "  <a href=\"../Shop/OrderForm.aspx?OrderNum=" + orderInfo.OrderNum + "&Name=" + DataSecurity.UrlEncode(orderInfo.ContacterName) + "\" id='GotoUserCenter'>" + Resources.DynamicPageResources.PayOnline_PayOnline_LookOrders + "</a> ";
                }
            }
            endFrom += "</div></form>";
            m_HiddenValue = newForm + strHiddenField.ToString() + endFrom;
        }

        //给页面赋值
        LblPayPlatform.Text = payPlatformInfo.PayPlatformName;
        LblPayPlatformName.Text = payPlatformInfo.PayPlatformName;
        LblOid.Text = v_oid;
        LblPayMoney.Text = vmoney + Resources.DynamicPageResources.PayOnline_PayOnline_Yuan;
        LblRate.Text = payPlatformInfo.Rate.ToString() + " %";
        LblvMoney.Text = v_amount + Resources.DynamicPageResources.PayOnline_PayOnline_Yuan;
        //submit.Attributes.Add("OnClick", "document.getElementById('form2').action='" + m_PayOnlineProviderUrl + "';");
        LblHiddenValue.Text = m_HiddenValue;
    }

    private static PaymentLogInfo GetpaymentLogInfo(string v_amount, decimal vmoney, int orderId, string userName, string paymentNum, int pointAmount, PayPlatformInfo payPlatformInfo)
    {
        PaymentLogInfo paymentLogInfo = new PaymentLogInfo();
        paymentLogInfo.UserName = userName;
        paymentLogInfo.OrderId = orderId;
        paymentLogInfo.PaymentNum = paymentNum;
        paymentLogInfo.PlatformId = payPlatformInfo.PayPlatformId;
        paymentLogInfo.MoneyPay = vmoney;
        paymentLogInfo.MoneyTrue = DataConverter.ToDecimal(v_amount);
        paymentLogInfo.PayTime = DateTime.Now;
        paymentLogInfo.Status = 1;
        paymentLogInfo.PlatformInfo = "";
        paymentLogInfo.Remark = "";
        paymentLogInfo.SuccessTime = null;
        paymentLogInfo.Point = pointAmount;
        paymentLogInfo.TradeNum = "";
        return paymentLogInfo;
    }

    private decimal GetMoneyByPointAmount(decimal vmoney, int payPlatformId, string userName, int pointAmount)
    {
        if (string.IsNullOrEmpty(userName))
        {
            Response.Redirect("../User/Login.aspx?ReturnUrl=" + HttpUtility.UrlEncode("../PayOnline/PayOnline.aspx?PayPlatformId=" + payPlatformId.ToString() + "&vMoney=" + vmoney.ToString()));
        }
        if (pointAmount > 0)
        {
            double moneyExchangePointByPoint = SiteConfig.UserConfig.MoneyExchangePointByPoint;
            if (moneyExchangePointByPoint <= 0)
            {
                moneyExchangePointByPoint = 1;
            }
            double pointPrice = SiteConfig.UserConfig.MoneyExchangePointByMoney / moneyExchangePointByPoint;
            vmoney = DataConverter.ToDecimal(pointPrice * pointAmount);
        }
        else
        {
            vmoney = DataConverter.ToDecimal(Request["vMoney"]);
        }
        return vmoney;
    }

    private decimal GetMoneyByOrserId(decimal vmoney, int orderId)
    {
        OrderInfo orderInfo = Order.GetOrderById(orderId);
        if (orderInfo.IsNull)
        {
            WriteErrMsg(Resources.DynamicPageResources.PayOnline_PayOnline_NoOrdersInfoErr, "");
        }
        if (orderInfo.MoneyReceipt >= orderInfo.MoneyTotal)
        {
            if (RequestString("AddOrder") == "success")
            {
                if (orderInfo.CouponId == 0)
                {
                    WriteSuccessMsg(Resources.DynamicPageResources.PayOnline_PayOnline_OrdersSubmit, "../User/Shop/ShowOrder.aspx?OrderID=" + orderId);
                }
            }
            else
            {
                WriteErrMsg(Resources.DynamicPageResources.PayOnline_PayOnline_OrdersYesToPay, "../User/Shop/ShowOrder.aspx?OrderID=" + orderId);
            }
        }
        vmoney = orderInfo.MoneyTotal - orderInfo.MoneyReceipt;
        return vmoney;
    }
    /// <summary>
    /// 添加参数,惹参数值不为空串,则添加。反之,不添加。
    /// </summary>
    private StringBuilder AddParameter(StringBuilder buf, String parameterName, String parameterValue)
    {
        if (null == parameterValue || "".Equals(parameterValue))
        {
            return buf;
        }

        if ("".Equals(buf.ToString()))
        {
            buf.Append(parameterName);
            buf.Append("=");
            buf.Append(parameterValue);
        }
        else
        {
            buf.Append("&");
            buf.Append(parameterName);
            buf.Append("=");
            buf.Append(parameterValue);
        }
        return buf;
    }

    /// <summary>
    /// 得到IP
    /// </summary>
    /// <returns></returns>
    private string getRealIp()
    {
        string UserIP;
        if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) //得到穿过代理服务器的ip地址
        {
            UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else
        {
            UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        }
        return UserIP;
    }

    /// 创建Get方式提交的支付请求串--西部支付
    ///merchantId 商户ID
    ///keyValue 商户密钥
    public static string CreateBuyUrl(string merchantId, string keyValue, string p2_Order, string p3_Amt, string p4_Cur, string p5_Pid, string p6_Pcat, string p7_Pdesc, string p8_Url, string p9_SAF, string pa_MP, string pd_FrpId, string pr_NeedRespone)
    {
        string sbOld = "";

        sbOld += "Buy";
        sbOld += merchantId;
        sbOld += p2_Order;
        sbOld += p3_Amt;
        sbOld += p4_Cur;

        sbOld += p5_Pid;
        sbOld += p6_Pcat;
        sbOld += p7_Pdesc;
        sbOld += p8_Url;
        sbOld += p9_SAF;

        sbOld += pa_MP;
        sbOld += pd_FrpId;
        sbOld += pr_NeedRespone;

        string hmac = HmacSign(sbOld, keyValue);

        string result = "";

        result += "?p0_Cmd=Buy";
        result += "&p1_MerId=" + merchantId;
        result += "&p2_Order=" + HttpUtility.UrlEncode(p2_Order, System.Text.Encoding.GetEncoding("gb2312"));
        result += "&p3_Amt=" + p3_Amt;

        result += "&p4_Cur=" + p4_Cur;
        result += "&p5_Pid=" + HttpUtility.UrlEncode(p5_Pid, System.Text.Encoding.GetEncoding("gb2312"));
        result += "&p6_Pcat=" + HttpUtility.UrlEncode(p6_Pcat, System.Text.Encoding.GetEncoding("gb2312"));
        result += "&p7_Pdesc=" + HttpUtility.UrlEncode(p7_Pdesc, System.Text.Encoding.GetEncoding("gb2312"));
        result += "&p8_Url=" + HttpUtility.UrlEncode(p8_Url, System.Text.Encoding.GetEncoding("gb2312"));

        result += "&p9_SAF=" + p9_SAF;
        result += "&pa_MP=" + HttpUtility.UrlEncode(pa_MP, System.Text.Encoding.GetEncoding("gb2312"));
        result += "&pd_FrpId=" + pd_FrpId;
        result += "&pr_NeedResponse=" + pr_NeedRespone;
        result += "&hmac=" + hmac;

        return result;
    }
    public static string HmacSign(string aValue, string aKey)
    {
        byte[] k_ipad = new byte[64];
        byte[] k_opad = new byte[64];
        byte[] keyb;
        byte[] Value;
        keyb = Encoding.UTF8.GetBytes(aKey);
        Value = Encoding.UTF8.GetBytes(aValue);

        for (int i = keyb.Length; i < 64; i++)
            k_ipad[i] = 54;

        for (int i = keyb.Length; i < 64; i++)
            k_opad[i] = 92;

        for (int i = 0; i < keyb.Length; i++)
        {
            k_ipad[i] = (byte)(keyb[i] ^ 0x36);
            k_opad[i] = (byte)(keyb[i] ^ 0x5c);
        }

        HmacMD5 md = new HmacMD5();

        md.update(k_ipad, (uint)k_ipad.Length);
        md.update(Value, (uint)Value.Length);
        byte[] dg = md.finalize();
        md.init();
        md.update(k_opad, (uint)k_opad.Length);
        md.update(dg, 16);
        dg = md.finalize();

        return toHex(dg);
    }
    public static string toHex(byte[] input)
    {
        if (input == null)
            return null;

        StringBuilder output = new StringBuilder(input.Length * 2);

        for (int i = 0; i < input.Length; i++)
        {
            int current = input[i] & 0xff;
            if (current < 16)
                output.Append("0");
            output.Append(current.ToString("x"));
        }

        return output.ToString();
    }
    public class HmacMD5
    {
        private uint[] count;
        private uint[] state;
        private byte[] buffer;
        private byte[] Digest;

        public HmacMD5()
        {
            count = new uint[2];
            state = new uint[4];
            buffer = new byte[64];
            Digest = new byte[16];
            init();
        }

        public void init()
        {
            count[0] = 0;
            count[1] = 0;
            state[0] = 0x67452301;
            state[1] = 0xefcdab89;
            state[2] = 0x98badcfe;
            state[3] = 0x10325476;
        }

        public void update(byte[] data, uint length)
        {
            uint left = length;
            uint offset = (count[0] >> 3) & 0x3F;
            uint bit_length = (uint)(length << 3);
            uint index = 0;

            if (length <= 0)
                return;

            count[0] += bit_length;
            count[1] += (length >> 29);
            if (count[0] < bit_length)
                count[1]++;

            if (offset > 0)
            {
                uint space = 64 - offset;
                uint copy = (offset + length > 64 ? 64 - offset : length);
                System.Buffer.BlockCopy(data, 0, buffer, (int)offset, (int)copy);

                if (offset + copy < 64)
                    return;

                transform(buffer);
                index += copy;
                left -= copy;
            }

            for (; left >= 64; index += 64, left -= 64)
            {
                System.Buffer.BlockCopy(data, (int)index, buffer, 0, 64);
                transform(buffer);
            }

            if (left > 0)
                System.Buffer.BlockCopy(data, (int)index, buffer, 0, (int)left);

        }

        private static byte[] pad = new byte[64] {
													 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
													 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
													 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
													 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        public byte[] finalize()
        {
            byte[] bits = new byte[8];
            encode(ref bits, count, 8);
            uint index = (uint)((count[0] >> 3) & 0x3f);
            uint padLen = (index < 56) ? (56 - index) : (120 - index);
            update(pad, padLen);
            update(bits, 8);
            encode(ref Digest, state, 16);

            for (int i = 0; i < 64; i++)
                buffer[i] = 0;

            return Digest;
        }

        public string md5String()
        {
            string s = "";

            for (int i = 0; i < Digest.Length; i++)
                s += Digest[i].ToString("x2");

            return s;
        }

        #region Constants for MD5Transform routine.

        private const uint S11 = 7;
        private const uint S12 = 12;
        private const uint S13 = 17;
        private const uint S14 = 22;
        private const uint S21 = 5;
        private const uint S22 = 9;
        private const uint S23 = 14;
        private const uint S24 = 20;
        private const uint S31 = 4;
        private const uint S32 = 11;
        private const uint S33 = 16;
        private const uint S34 = 23;
        private const uint S41 = 6;
        private const uint S42 = 10;
        private const uint S43 = 15;
        private const uint S44 = 21;
        #endregion

        private void transform(byte[] data)
        {
            uint a = state[0];
            uint b = state[1];
            uint c = state[2];
            uint d = state[3];
            uint[] x = new uint[16];

            decode(ref x, data, 64);

            // Round 1
            FF(ref a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */
            FF(ref d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */
            FF(ref c, d, a, b, x[2], S13, 0x242070db); /* 3 */
            FF(ref b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */
            FF(ref a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */
            FF(ref d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */
            FF(ref c, d, a, b, x[6], S13, 0xa8304613); /* 7 */
            FF(ref b, c, d, a, x[7], S14, 0xfd469501); /* 8 */
            FF(ref a, b, c, d, x[8], S11, 0x698098d8); /* 9 */
            FF(ref d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */
            FF(ref c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
            FF(ref b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
            FF(ref a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
            FF(ref d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
            FF(ref c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
            FF(ref b, c, d, a, x[15], S14, 0x49b40821); /* 16 */

            // Round 2 
            GG(ref a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */
            GG(ref d, a, b, c, x[6], S22, 0xc040b340); /* 18 */
            GG(ref c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
            GG(ref b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */
            GG(ref a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */
            GG(ref d, a, b, c, x[10], S22, 0x2441453); /* 22 */
            GG(ref c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
            GG(ref b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */
            GG(ref a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */
            GG(ref d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
            GG(ref c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */
            GG(ref b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */
            GG(ref a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
            GG(ref d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */
            GG(ref c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */
            GG(ref b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */

            // Round 3
            HH(ref a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */
            HH(ref d, a, b, c, x[8], S32, 0x8771f681); /* 34 */
            HH(ref c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
            HH(ref b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
            HH(ref a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */
            HH(ref d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */
            HH(ref c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */
            HH(ref b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
            HH(ref a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
            HH(ref d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */
            HH(ref c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */
            HH(ref b, c, d, a, x[6], S34, 0x4881d05); /* 44 */
            HH(ref a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */
            HH(ref d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
            HH(ref c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
            HH(ref b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */

            // Round 4
            II(ref a, b, c, d, x[0], S41, 0xf4292244); /* 49 */
            II(ref d, a, b, c, x[7], S42, 0x432aff97); /* 50 */
            II(ref c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
            II(ref b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */
            II(ref a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
            II(ref d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */
            II(ref c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
            II(ref b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */
            II(ref a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */
            II(ref d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
            II(ref c, d, a, b, x[6], S43, 0xa3014314); /* 59 */
            II(ref b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
            II(ref a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */
            II(ref d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
            II(ref c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */
            II(ref b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */

            state[0] += a;
            state[1] += b;
            state[2] += c;
            state[3] += d;

            for (int i = 0; i < 16; i++)
                x[i] = 0;
        }

        #region encode - decode
        private void encode(ref byte[] output, uint[] input, uint len)
        {
            uint i, j;
            if (System.BitConverter.IsLittleEndian)
            {
                for (i = 0, j = 0; j < len; i++, j += 4)
                {
                    output[j] = (byte)(input[i] & 0xff);
                    output[j + 1] = (byte)((input[i] >> 8) & 0xff);
                    output[j + 2] = (byte)((input[i] >> 16) & 0xff);
                    output[j + 3] = (byte)((input[i] >> 24) & 0xff);
                }
            }
            else
            {
                for (i = 0, j = 0; j < len; i++, j += 4)
                {
                    output[j + 3] = (byte)(input[i] & 0xff);
                    output[j + 2] = (byte)((input[i] >> 8) & 0xff);
                    output[j + 1] = (byte)((input[i] >> 16) & 0xff);
                    output[j] = (byte)((input[i] >> 24) & 0xff);
                }
            }
        }

        private void decode(ref uint[] output, byte[] input, uint len)
        {
            uint i, j;
            if (System.BitConverter.IsLittleEndian)
            {
                for (i = 0, j = 0; j < len; i++, j += 4)
                    output[i] = ((uint)input[j]) | (((uint)input[j + 1]) << 8) |
                        (((uint)input[j + 2]) << 16) | (((uint)input[j + 3]) << 24);
            }
            else
            {
                for (i = 0, j = 0; j < len; i++, j += 4)
                    output[i] = ((uint)input[j + 3]) | (((uint)input[j + 2]) << 8) |
                        (((uint)input[j + 1]) << 16) | (((uint)input[j]) << 24);
            }
        }
        #endregion

        private uint rotate_left(uint x, uint n)
        {
            return (x << (int)n) | (x >> (int)(32 - n));
        }

        #region F, G, H and I are basic MD5 functions.
        private uint F(uint x, uint y, uint z)
        {
            return (x & y) | (~x & z);
        }

        private uint G(uint x, uint y, uint z)
        {
            return (x & z) | (y & ~z);
        }

        private uint H(uint x, uint y, uint z)
        {
            return x ^ y ^ z;
        }

        private uint I(uint x, uint y, uint z)
        {
            return y ^ (x | ~z);
        }
        #endregion

        #region  FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
        private void FF(ref uint a, uint b, uint c, uint d, uint x, uint s, uint ac)
        {
            a += F(b, c, d) + x + ac;
            a = rotate_left(a, s) + b;
        }

        private void GG(ref uint a, uint b, uint c, uint d, uint x, uint s, uint ac)
        {
            a += G(b, c, d) + x + ac;
            a = rotate_left(a, s) + b;
        }

        private void HH(ref uint a, uint b, uint c, uint d, uint x, uint s, uint ac)
        {
            a += H(b, c, d) + x + ac;
            a = rotate_left(a, s) + b;
        }

        private void II(ref uint a, uint b, uint c, uint d, uint x, uint s, uint ac)
        {
            a += I(b, c, d) + x + ac;
            a = rotate_left(a, s) + b;
        }
        #endregion
    }
</script>
