using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SqlClient;

public partial class payment_99bill_receive : System.Web.UI.Page
{


    #region 功能函数

    //功能函数。将变量值不为空的参数组成字符串
    public string appendParam(string returnStr, string paramId, string paramValue)
    {
        if (returnStr != "")
        {
            if (paramValue != "")
            {
                returnStr += "&" + paramId + "=" + paramValue;
            }
        }
        else
        {
            if (paramValue != "")
            {
                returnStr = paramId + "=" + paramValue;
            }
        }
        return returnStr;
    }
    //功能函数。将变量值不为空的参数组成字符串。结束


    /// <summary>
    /// 引用证书非对称加/解密RSA-公钥验签【OriginalString：原文；SignatureString：签名字符；pubkey_path：证书路径；CertificatePW：证书密码；SignType：签名摘要类型（1：MD5，2：SHA1）】
    /// </summary>
    public static bool CerRSAVerifySignature(string OriginalString, string SignatureString, string pubkey_path, string CertificatePW, int SignType)
    {
        byte[] OriginalByte = System.Text.Encoding.UTF8.GetBytes(OriginalString);
        byte[] SignatureByte = Convert.FromBase64String(SignatureString);
        X509Certificate2 x509_Cer1 = new X509Certificate2(pubkey_path, CertificatePW);
        RSACryptoServiceProvider rsapub = (RSACryptoServiceProvider)x509_Cer1.PublicKey.Key;
        rsapub.ImportCspBlob(rsapub.ExportCspBlob(false));
        RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsapub);
        byte[] HashData;
        switch (SignType)
        {
            case 1:
                f.SetHashAlgorithm("MD5");//摘要算法MD5
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                HashData = md5.ComputeHash(OriginalByte);
                break;
            default:
                f.SetHashAlgorithm("SHA1");//摘要算法SHA1
                SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                HashData = sha.ComputeHash(OriginalByte);
                break;
        }
        if (f.VerifySignature(HashData, SignatureByte))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    #endregion

    public string rtnOk = "";//定义是否重复通知标志
    public string rtnUrl = "";//定义显示结果show页面地址


    protected void Page_Load(object sender, EventArgs e)
    {
        //获取人民币网关账户号
        string merchantAcctId = Request["merchantAcctId"].ToString().Trim();

        //获取网关版本.固定值
        ///快钱会根据版本号来调用对应的接口处理程序。
        ///本代码版本号固定为v2.0
        string version = Request["version"].ToString().Trim();

        //获取语言种类.固定选择值。
        ///只能选择1、2、3
        ///1代表中文；2代表英文
        ///默认值为1
        string language = Request["language"].ToString().Trim();

        //签名类型.固定值
        ///1代表MD5签名
        ///当前版本固定为1
        string signType = Request["signType"].ToString().Trim();

        //获取支付方式
        ///值为：10、11、12、13、14
        ///00：组合支付（网关支付页面显示快钱支持的各种支付方式，推荐使用）10：银行卡支付（网关支付页面只显示银行卡支付）.11：电话银行支付（网关支付页面只显示电话支付）.12：快钱账户支付（网关支付页面只显示快钱账户支付）.13：线下支付（网关支付页面只显示线下支付方式）.14：B2B支付（网关支付页面只显示B2B支付，但需要向快钱申请开通才能使用）
        string payType = Request["payType"].ToString().Trim();

        //获取银行代码
        ///参见银行代码列表
        string bankId = Request["bankId"].ToString().Trim();

        //获取商户订单号
        string orderId = Request["orderId"].ToString().Trim();

        //获取订单提交时间
        ///获取商户提交订单时的时间.14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
        ///如：20080101010101
        string orderTime = Request["orderTime"].ToString().Trim();

        //获取原始订单金额
        ///订单提交到快钱时的金额，单位为分。
        ///比方2 ，代表0.02元
        ///string orderAmount = Request["orderAmount"].ToString().Trim();
        string orderAmount = Convert.ToString(Convert.ToInt32(Request["orderAmount"].ToString().Trim()) / 100).Trim();

		//获取快钱交易号
        ///获取该交易在快钱的交易号
        string dealId = Request["dealId"].ToString().Trim();

        //获取银行交易号
        ///如果使用银行卡支付时，在银行的交易号。如不是通过银行支付，则为空
        string bankDealId = Request["bankDealId"].ToString().Trim();

        //获取在快钱交易时间
        ///14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
        ///如；20080101010101
        string dealTime = Request["dealTime"].ToString().Trim();

        //获取实际支付金额
        ///单位为分
        ///比方 2 ，代表0.02元
        string payAmount = Request["payAmount"].ToString().Trim();

        //获取交易手续费
        ///单位为分
        ///比方 2 ，代表0.02元
        string fee = Request["fee"].ToString().Trim();

        //获取扩展字段1
        string ext1 = Request["ext1"].ToString().Trim();

        //获取扩展字段2
        string ext2 = Request["ext2"].ToString().Trim();

        //获取处理结果
        ///10代表 成功; 11代表 失败
        string payResult = Request["payResult"].ToString().Trim();

        //获取错误代码
        ///详细见文档错误代码列表
        string errCode = Request["errCode"].ToString().Trim();

        //获取加密签名串
        string signMsg = Request["signMsg"].ToString().Trim();



        //生成加密串。必须保持如下顺序。
        string merchantSignMsgVal = "";
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "merchantAcctId", merchantAcctId);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "version", version);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "language", language);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "signType", signType);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "payType", payType);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankId", bankId);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderId", orderId);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderTime", orderTime);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderAmount", orderAmount);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealId", dealId);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankDealId", bankDealId);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealTime", dealTime);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "payAmount", payAmount);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "fee", fee);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext1", ext1);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext2", ext2);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "payResult", payResult);
        merchantSignMsgVal = appendParam(merchantSignMsgVal, "errCode", errCode);


        //商家进行数据处理，并跳转会商家显示支付结果的页面
        ///首先进行签名字符串验证
        ///

        string pubkey_path = HttpContext.Current.Server.MapPath("") + "\\certificate\\99bill.cert.rsa.20140728.cer";//快钱公钥证书路径
        string CertificatePW = "";//存放公钥的证书密码
        if (CerRSAVerifySignature(merchantSignMsgVal, signMsg, pubkey_path, CertificatePW, 2))
        {
            switch (payResult)
            {
                case "10":
                    /*  
                     ' 商户网站逻辑处理，比方更新订单支付状态为成功
                    ' 特别注意：只有signMsg.ToUpper() == merchantSignMsg.ToUpper()，且payResult=10，才表示支付成功！
                     * 因为快钱会重复通知这个页面，首先判断订单是否已经更新，没有更新做更新有则不做更新，
                     * 同时将返回的付款金额payamount与提交订单前的订单金额进行对比校验,如果一致则更新订单。
                    */
                    #region 更新客户付款成功信息到系统。


                    try
                    {
                        string tmp_type = "";
                        string temp_user_id = "";
                        string tmp_old = "";
                        string tmp_Statu = "";

                        SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=jikee.net;User id=allDataBase;Password=#(@*&#*(@$@UEUWUE#)*$*#)(*%&$(*@#$*@)(;");
                        conn.Open();
                        string sql = "select Order_type,Usr_name,Statu,Old_Id from Order_Account where Order_Id='" + orderId + "'";
                        SqlCommand cmd = new SqlCommand(sql, conn);
                        SqlDataReader drDataReader = cmd.ExecuteReader();
                        DataTable dt = new DataTable();
                        dt.Load(drDataReader);
                        foreach (DataRow dr in dt.Rows)
                        {
                            tmp_type = dr["Order_type"].ToString();
                            temp_user_id = dr["Usr_name"].ToString();
                            tmp_old = dr["Old_Id"].ToString();
                            tmp_Statu = dr["Statu"].ToString();

                        }
                        #region 如果订单未付款
                        if (tmp_Statu == "0")
                        {
                            #region 修改订单未付款的状态为已付款
                            string sqltmp_Statu = "update Order_Account set Statu='1' where Order_Id='" + orderId + "'";
                            SqlCommand cmdtmp_Statu = new SqlCommand(sqltmp_Statu, conn);
                            cmdtmp_Statu.ExecuteNonQuery();
                            #endregion

                            #region 获取用户积分添加条件
                            string usergrade = "";
                            string UserName = "";
                            string Sys_web_usergrade = "";
                            string sqlSys_web_usergrade = "Select * from SystemInfo";
                            SqlCommand cmdSys_web_usergrade = new SqlCommand(sqlSys_web_usergrade, conn);
                            SqlDataReader drSys_web_usergrade = cmdSys_web_usergrade.ExecuteReader();
                            DataTable dtSys_web_usergrade = new DataTable();
                            dtSys_web_usergrade.Load(drSys_web_usergrade);
                            foreach (DataRow dr in dtSys_web_usergrade.Rows)
                            {
                                Sys_web_usergrade = dr["web_usergrade"].ToString();
                            }


                            if (usergrade == "" || usergrade == null)
                            {


                                if (Request["usergrade"] != "")
                                {
                                    usergrade = Convert.ToString(Request["usergrade"]);
                                }
                                else
                                {
                                    usergrade = "1";
                                }
                            }


                            if (Session["usergrade"] != "")
                            {
                                usergrade = Convert.ToString(Session["usergrade"]);
                                UserName = Convert.ToString(Session["User_usern"]);
                            }
                            else if (Sys_web_usergrade != "")
                            {
                                usergrade = Sys_web_usergrade;
                                UserName = temp_user_id;
                            }
                            #endregion

                            #region 为用户添加积分
                            double jibielv = 0;
                            double strjibielv = 0;
                            double total_fee = 0;
                            double JiFen = 0;
                            if (usergrade != "")
                            {
                                string sqljibielv = "Select jibielv,total_fee from [user_grade] where ID='" + usergrade + "'";
                                SqlCommand cmdjibielv = new SqlCommand(sqljibielv, conn);
                                SqlDataReader drjibielv = cmdjibielv.ExecuteReader();
                                DataTable dtjibielv = new DataTable();
                                dtjibielv.Load(drjibielv);
                                if (dtjibielv.Rows.Count != 0)
                                {
                                    strjibielv = double.Parse(dtjibielv.Rows[0]["jibielv"].ToString());
                                    total_fee = double.Parse(dtjibielv.Rows[0]["total_fee"].ToString());
                                }
                                else
                                {
                                    strjibielv = 1;
                                }
                                JiFen = Convert.ToDouble(strjibielv * total_fee);
                            }
                            else
                            {
                                jibielv = 1;
                                JiFen = total_fee;
                            }
                            #endregion

                            #region tmp_type == "1"
                            if (tmp_type == "1")
                            {
                                string sql1 = "Select * from OrderBase where OrderID='" + tmp_old + "'";
                                SqlCommand cmd1 = new SqlCommand(sql1, conn);
                                SqlDataReader dr1 = cmd1.ExecuteReader();
                                DataTable dt1 = new DataTable();
                                dt1.Load(dr1);
                                foreach (DataRow dr in dt1.Rows)
                                {
                                    string sql11 = "Update OrderBase set [ShiFuPrice]='" + orderAmount + "',[JiFen]='" + JiFen + "',ShiFuPriceTime='" + DateTime.Now + "',OrderState='3' where OrderID='" + tmp_old + "'";
                                    SqlCommand cmd11 = new SqlCommand(sql11, conn);
                                    cmd11.ExecuteNonQuery();

                                    string sql12 = "insert into OrderOperLog (AdminId,AdminUserName,OrderID,OperLog,Otime) values (0,'" + UserName + "','" + tmp_old + "',' 订单支付成功,支付金额 " + orderAmount + "元 ','" + DateTime.Now + "')";
                                    SqlCommand cmd12 = new SqlCommand(sql12, conn);
                                    cmd12.ExecuteNonQuery();

                                    string sql13 = "Insert into OrderBack(UserID,OrderID,BackMount,Memo,BackFlag) values('" + temp_user_id + "','" + tmp_old + "','" + JiFen + "','订机票，在线支付" + orderAmount + "元,当前积分率为" + jibielv + ",积分为" + JiFen + "。',0)";
                                    SqlCommand cmd13 = new SqlCommand(sql13, conn);
                                    cmd13.ExecuteNonQuery();
                                }
                            }
                            #endregion

                            #region tmp_type == "21"
                            if (tmp_type == "21")
                            {
                                string sql2 = "Select * from OrderBase_I where OrderID='" + tmp_old + "'";
                                SqlCommand cmd2 = new SqlCommand(sql2, conn);
                                SqlDataReader dr2 = cmd2.ExecuteReader();
                                DataTable dt2 = new DataTable();
                                dt2.Load(dr2);
                                foreach (DataRow dr in dt2.Rows)
                                {
                                    string sql21 = "Update OrderBase_I set [ShiFuPrice]='" + orderAmount + "',[JiFen]='" + JiFen + "',ShiFuPriceTime='" + DateTime.Now + "',OrderState='3' where OrderID='" + tmp_old + "'";
                                    SqlCommand cmd21 = new SqlCommand(sql21, conn);
                                    cmd21.ExecuteNonQuery();

                                    string sql22 = "insert into OrderOperLog (AdminId,AdminUserName,OrderID,OperLog,Otime) values (0,'" + UserName + "','" + tmp_old + "',' 订单支付成功,支付金额 " + orderAmount + "元 ','" + DateTime.Now + "')";
                                    SqlCommand cmd22 = new SqlCommand(sql22, conn);
                                    cmd22.ExecuteNonQuery();

                                    string sql23 = "Insert into OrderBack(UserID,OrderID,BackMount,Memo,BackFlag) values('" + temp_user_id + "','" + tmp_old + "','" + JiFen + "','订机票，在线支付" + orderAmount + "元,当前积分率为" + jibielv + ",积分为" + JiFen + "。',0)";
                                    SqlCommand cmd23 = new SqlCommand(sql23, conn);
                                    cmd23.ExecuteNonQuery();
                                }
                            }
                            #endregion

                            #region tmp_type == "6"
                            if (tmp_type == "6")
                            {
                                string sql3 = "Select * from OrderBase where OrderID='" + tmp_old + "'";
                                SqlCommand cmd3 = new SqlCommand(sql3, conn);
                                SqlDataReader dr3 = cmd3.ExecuteReader();
                                DataTable dt3 = new DataTable();
                                dt3.Load(dr3);
                                foreach (DataRow dr in dt3.Rows)
                                {
                                    string sql31 = "Update OrderBase set [ShiFuPrice]=cast(ShiFuPrice as float)+" + orderAmount + ",buchajia='0',[JiFen]=cast(JiFen as float)+" + JiFen + ",ShiFuPriceTime='" + DateTime.Now + "',OrderState='3.12' where OrderID='" + tmp_old + "'";
                                    SqlCommand cmd31 = new SqlCommand(sql31, conn);
                                    cmd31.ExecuteNonQuery();

                                    string sql32 = "insert into OrderOperLog (AdminId,AdminUserName,OrderID,OperLog,Otime) values (0,'" + UserName + "','" + tmp_old + "',' 订单补款成功,补款金额 " + orderAmount + "元 ','" + DateTime.Now + "')";
                                    SqlCommand cmd32 = new SqlCommand(sql32, conn);
                                    cmd32.ExecuteNonQuery();

                                    string sql33 = "Insert into OrderBack(UserID,OrderID,BackMount,Memo,BackFlag) values('" + temp_user_id + "','" + tmp_old + "','" + JiFen + "','订单补款成功，补款金额" + orderAmount + "元,当前积分率为" + jibielv + ",积分为" + JiFen + "。',0)";
                                    SqlCommand cmd33 = new SqlCommand(sql33, conn);
                                    cmd33.ExecuteNonQuery();
                                }
                            }
                            #endregion
                        }
                        #endregion

                        conn.Close();

                    }
                    catch (Exception)
                    {

                    }


                    #endregion

                    //报告给快钱处理结果，并提供将要重定向的地址。
                    Response.Write("<result>1</result>" + "<redirecturl>" + @"http://" + HttpContext.Current.Request.Url.Authority.ToString().Trim() + @"/payment/99bill/show.asp?msg=success" + @"&orderId=" + orderId + @"&orderAmount=" + orderAmount + "</redirecturl>");
                    break;
                default:
                     
                    Response.Write("<result>1</result>" + "<redirecturl>" + @"http://" + HttpContext.Current.Request.Url.Authority.ToString().Trim() + @"/payment/99bill/show.asp?msg=false" + @"&orderId=" + orderId + @"&orderAmount=" + orderAmount + "</redirecturl>");
                    break;
            }
        }
        else//验签失败
        {
            rtnUrl = @"http://" + HttpContext.Current.Request.Url.Authority.ToString().Trim() + @"/payment/99bill/show.asp?msg=error";
            Response.Redirect(rtnUrl); //将快钱返回的结果发送到show.aspx

            //Response.Write("signMsgVal=" + "(" + signMsgVal + ")");
            //Response.Write("</br>" + "signMsg =" + signMsg);
            //Response.Write("</br>" + "错误");

        }
    }
}
