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_send : System.Web.UI.Page
{

    #region 参数定义
    //人民币网关账户号
    ///请登录快钱系统获取用户编号，用户编号后加01即为人民币网关账户号。
    public string merchantAcctId = "";

    //字符集.固定选择值。可为空。
    ///只能选择1、2、3.
    ///1代表UTF-8; 2代表GBK; 3代表gb2312
    ///默认值为1
    public string inputCharset = "";

    //接受支付结果的页面地址.与[bgUrl]不能同时为空。必须是绝对地址。
    ///如果[bgUrl]为空，快钱将支付结果Post到[pageUrl]对应的地址。
    ///如果[bgUrl]不为空，并且[bgUrl]页面指定的<redirecturl>地址不为空，则转向到<redirecturl>对应的地址
    public string pageUrl = "";

    //服务器接受支付结果的后台地址.与[pageUrl]不能同时为空。必须是绝对地址。
    ///快钱通过服务器连接的方式将交易结果发送到[bgUrl]对应的页面地址，在商户处理完成后输出的<result>如果为1，页面会转向到<redirecturl>对应的地址。
    ///如果快钱未接收到<redirecturl>对应的地址，快钱将把支付结果post到[pageUrl]对应的页面。
    public string bgUrl = "";

    //网关版本.固定值
    ///快钱会根据版本号来调用对应的接口处理程序。
    ///本代码版本号固定为v2.0
    public string version = "";

    //语言种类.固定选择值。
    ///只能选择1、2、3
    ///1代表中文；2代表英文
    ///默认值为1
    public string language = "";

    //签名类型.固定值
    ///1代表MD5签名
    ///当前版本固定为1
    public string signType = "";

    //支付人姓名
    ///可为中文或英文字符
    public string payerName = "";

    //支付人联系方式类型.固定选择值
    ///只能选择1
    ///1代表Email
    public string payerContactType = "";

    //支付人联系方式
    ///只能选择Email或手机号
    public string payerContact = "";

    //商户订单号
    ///由字母、数字、或[-][_]组成
    public string orderId = "";

    //订单金额
    ///以分为单位，必须是整型数字
    ///比方2，代表0.02元
    public string orderAmount = "";

    //订单提交时间
    ///14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
    ///如；20080101010101
    public string orderTime = "";

    //订单提交时间
    ///14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
    ///如；20080101010101
    public string stringorderTime = "";

    //商品名称
    ///可为中文或英文字符
    public string productName = "";

    //商品数量
    ///可为空，非空时必须为数字
    public string productNum = "";

    //商品代码
    ///可为字符或者数字
    public string productId = "";

    //商品描述
    public string productDesc = "";

    //扩展字段1
    ///在支付结束后原样返回给商户
    public string ext1 = "";

    //扩展字段2
    ///在支付结束后原样返回给商户
    public string ext2 = "";

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

    //银行代码
    ///实现直接跳转到银行页面去支付,只在payType=10时才需设置参数
    ///具体代码参见 接口文档银行代码列表
    public string bankId = "";

    //同一订单禁止重复提交标志
    ///固定选择值： 1、0
    ///1代表同一订单号只允许提交1次；0表示同一订单号在没有支付成功的前提下可重复提交多次。默认为0建议实物购物车结算类商户采用0；虚拟产品类商户采用1
    public string redoFlag = "0";

    //快钱的合作伙伴的账户号
    ///如未和快钱签订代理合作协议，不需要填写本参数
    public string pid = "";

    //签名串
    /// 
    public string signMsg = "";

    #endregion


    protected void Page_Load(object sender, EventArgs e)
    {
        #region 参数赋值
        inputCharset = Request["inputCharset"].ToString().Trim();
        bgUrl = Request["bgUrl"].ToString().Trim();
        pageUrl = Request["pageUrl"].ToString().Trim();
        version = Request["version"].ToString().Trim();
        language = Request["language"].ToString().Trim();
        signType = Request["signType"].ToString().Trim();
        signMsg = Request["signMsg"].ToString().Trim();
        merchantAcctId = Request["merchantAcctId"].ToString().Trim();
        payerName = Request["payerName"].ToString().Trim();
        payerContactType = Request["payerContactType"].ToString().Trim();
        payerContact = Request["payerContact"].ToString().Trim();
        orderId = Request["orderId"].ToString().Trim();
        orderAmount = Request["orderAmount"].ToString().Trim();
        orderTime = Request["orderTime"].ToString().Trim();
        productName = Request["productName"].ToString().Trim();
        productNum = Request["productNum"].ToString().Trim();
        productId = Request["productId"].ToString().Trim();
        productDesc = Request["productDesc"].ToString().Trim();
        ext1 = Request["ext1"].ToString().Trim();
        ext2 = Request["ext2"].ToString().Trim();
        payType = Request["payType"].ToString().Trim();
        bankId = Request["bankId"].ToString().Trim();
        redoFlag = Request["redoFlag"].ToString().Trim();
        pid = Request["pid"].ToString().Trim();
        #endregion


        if (Request["orderId"] == null)
        {
            Response.Redirect("..\\");
            return;

        }
        else
        {

            #region 加密处理
            merchantAcctId = merchantAcctId;

            inputCharset = "1";

            //pageUrl = @"http://" + HttpContext.Current.Request.Url.Authority.ToString().Trim() + @"/payment/99bill/receive.aspx";
            pageUrl = pageUrl;

            //bgUrl = @"http://" + HttpContext.Current.Request.Url.Authority.ToString().Trim() + @"/payment/99bill/receive.aspx";
            bgUrl = bgUrl;

            version = "v2.0";

            language = "1";

            signType = "4";



            payerName = payerName;


            payerContactType = "1";


            payerContact = "";


            orderId = orderId;//DateTime.Now.ToString("yyyyMMddHHmmss");


            orderAmount = orderAmount;//将元转换成分


            orderTime = DateTime.Now.ToString("yyyyMMddHHmmss");


            productName = productName;


            productNum = "1";


            productId = "";

            productDesc = productDesc;

            ext1 = "";


            ext2 = "";


            payType = "00";


            bankId = "";


            redoFlag = "0";


            pid = "";

            //生成加密签名串
            ///请务必按照如下顺序和规则组成加密串！
            string signMsgVal = "";
            signMsgVal = appendParam(signMsgVal, "inputCharset", inputCharset);
            signMsgVal = appendParam(signMsgVal, "pageUrl", pageUrl);
            signMsgVal = appendParam(signMsgVal, "bgUrl", bgUrl);
            signMsgVal = appendParam(signMsgVal, "version", version);
            signMsgVal = appendParam(signMsgVal, "language", language);
            signMsgVal = appendParam(signMsgVal, "signType", signType);
            signMsgVal = appendParam(signMsgVal, "merchantAcctId", merchantAcctId);
            signMsgVal = appendParam(signMsgVal, "payerName", payerName);
            signMsgVal = appendParam(signMsgVal, "payerContactType", payerContactType);
            signMsgVal = appendParam(signMsgVal, "payerContact", payerContact);
            signMsgVal = appendParam(signMsgVal, "orderId", orderId);
            signMsgVal = appendParam(signMsgVal, "orderAmount", orderAmount);
            signMsgVal = appendParam(signMsgVal, "orderTime", orderTime);
            signMsgVal = appendParam(signMsgVal, "productName", productName);
            signMsgVal = appendParam(signMsgVal, "productNum", productNum);
            signMsgVal = appendParam(signMsgVal, "productId", productId);
            signMsgVal = appendParam(signMsgVal, "productDesc", productDesc);
            signMsgVal = appendParam(signMsgVal, "ext1", ext1);
            signMsgVal = appendParam(signMsgVal, "ext2", ext2);
            signMsgVal = appendParam(signMsgVal, "payType", payType);
            signMsgVal = appendParam(signMsgVal, "bankId", bankId);
            signMsgVal = appendParam(signMsgVal, "redoFlag", redoFlag);
            signMsgVal = appendParam(signMsgVal, "pid", pid);

            string prikey_path = HttpContext.Current.Server.MapPath("") + "\\certificate\\tester-rsa.pfx";//商户私钥证书路径
            string CertificatePW = "logang";//商户私钥密钥
            signMsg = CerRSASignature(signMsgVal, prikey_path, CertificatePW, 2);

            string a = signMsg;

            #endregion

            #region 自动提交form表单
            Response.Write("<form name=kqPay id=kqPay method=post action=https://www.99bill.com/gateway/recvMerchantInfoAction.htm>");
            Response.Write("<input type=hidden name=inputCharset  value=" + inputCharset + ">");
            Response.Write("<input type=hidden name=bgUrl  value=" + bgUrl + ">");
            Response.Write("<input type=hidden name=pageUrl  value=" + pageUrl + ">");
            Response.Write("<input type=hidden name=version  value=" + version + ">");
            Response.Write("<input type=hidden name=language  value=" + language + ">");
            Response.Write("<input type=hidden name=signType  value=" + signType + ">");
            Response.Write("<input type=hidden name=signMsg  value=" + signMsg + ">");
            Response.Write("<input type=hidden name=merchantAcctId  value=" + merchantAcctId + ">");
            Response.Write("<input type=hidden name=payerName  value=" + payerName + ">");
            Response.Write("<input type=hidden name=payerContactType  value=" + payerContactType + ">");
            Response.Write("<input type=hidden name=payerContact  value=" + payerContact + ">");
            Response.Write("<input type=hidden name=orderId  value=" + orderId + ">");
            Response.Write("<input type=hidden name=orderAmount  value=" + orderAmount + ">");
            Response.Write("<input type=hidden name=orderTime  value=" + orderTime + ">");
            Response.Write("<input type=hidden name=productName  value=" + productName + ">");
            Response.Write("<input type=hidden name=productNum  value=" + productNum + ">");
            Response.Write("<input type=hidden name=productId  value=" + productId + ">");
            Response.Write("<input type=hidden name=productDesc  value=" + productDesc + ">");
            Response.Write("<input type=hidden name=ext1  value=" + ext1 + ">");
            Response.Write("<input type=hidden name=ext2  value=" + ext2 + ">");
            Response.Write("<input type=hidden name=payType  value=" + payType + ">");
            Response.Write("<input type=hidden name=bankId  value=" + bankId + ">");
            Response.Write("<input type=hidden name=redoFlag  value=" + redoFlag + ">");
            Response.Write("<input type=hidden name=pid  value=" + pid + ">");
            Response.Write("</form>");
            Response.Write("<scr" + "ipt language='javascript'>kqPay.submit();</scr" + "ipt>");
            #endregion
        }
    }

    public static string CerRSASignature(string OriginalString, string prikey_path, string CertificatePW, int SignType)
    {
        byte[] OriginalByte = System.Text.Encoding.UTF8.GetBytes(OriginalString);
        X509Certificate2 x509_Cer1 = new X509Certificate2(prikey_path, CertificatePW);
        RSACryptoServiceProvider rsapri = (RSACryptoServiceProvider)x509_Cer1.PrivateKey;
        RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsapri);
        byte[] result;
        switch (SignType)
        {
            case 1:
                f.SetHashAlgorithm("MD5");//摘要算法MD5
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                result = md5.ComputeHash(OriginalByte);//摘要值
                break;
            default:
                f.SetHashAlgorithm("SHA1");//摘要算法SHA1
                SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                result = sha.ComputeHash(OriginalByte);//摘要值
                break;
        }
        string SignData = System.Convert.ToBase64String(f.CreateSignature(result)).ToString();

        return SignData;
    }


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


}
