1. 程式人生 > >工行線上支付介面實戰開發流程及原始碼

工行線上支付介面實戰開發流程及原始碼

前期準備

支付元件註冊(PS:當時工行技術根本沒有給我這個元件,被坑了,當時還想罵那個技術一下,簽名什麼的,難道我隨便按照自己的想法籤一個也可以?後來終於給我了)

元件註冊說明

一、API配置說明:

1.將ICBCEBankUtil.dll和infosecapi.dll兩個dll檔案拷貝到系統system32目錄下(其中,如果是64位系統,則拷貝到SysWOW64目錄下);
2.開啟DOS視窗,進入system32目錄/SysWOW64目錄;
3.執行“regsvr32 ICBCEBankUtil.dll”命令註冊控制元件;

二、函式說明:

1、初始化
init(
BSTR certFN,銀行證書檔名
BSTR certFNM,商戶證書檔名
BSTR keyFN,私鑰檔名
BSTR key私鑰保護口令
)
返回值:
-100:銀行證書檔名傳遞錯
-101:商戶證書檔名傳遞錯
-102:私鑰檔名傳遞錯
-103:私鑰保護口令傳遞錯
-110:開啟銀行證書檔案錯
-111:開啟商戶證書檔案錯
-112:開啟私鑰檔案錯
2、簽名
signC(
BSTR src,明文字串
int srcLen,明文長度
)
返回值:
如果成功則返回BASE64編碼後的簽名串,否則返回空串
如果返回空串,可呼叫getRC取得錯誤碼
3、獲取錯誤碼(只在出錯時有效)
getRC
返回值
-100:明文字串傳遞錯誤
-1:明文錯誤
-2:私鑰錯
-3:私鑰解密錯
-4:私鑰保護口令錯
4、驗證簽名
verifySignC(
BSTR src,明文字串
int srcLen,明文字串長度
BSTR sSrc,簽名BASE64編碼字串
int sSrcLen簽名BASE64編碼字串長度
)
返回值:
0:成功
-1:驗證失敗
-2:解碼失敗
-100:明文字串傳遞有誤
-101:簽名字串傳遞有誤
5、獲取證書
getCert(
int which證書型別:0銀行證書,1商戶證書
)
返回值:BASE64編碼後的證書
註冊好以後將infosecapi.dll引用到專案中。
2.證書引用
然後將public.crt、商戶.crt、商戶.key 這三個檔案放到專案某個資料夾下

開發階段

1.首先必須細讀:《中國工商銀行網上銀行新B2C線上支付介面說明V1.0.0.11》這個文件(PS:工行人員當時沒有給我這個文件,打電話過去問技術,技術讓我細讀這個文件,根本沒有這個文件,還說他發給客戶了的,問客戶也說沒有發過,當時真的是被坑好多,後來網上找到了一個)。
2.以下是原始碼:

/// <summary>
    /// 工商銀行簽名驗證類
    /// </summary>
    public class ICBCTest
    {
        string strCertFN = @"f:\aa\ahhfycYQHLTEST.pfx";
        string strCertFNM = @"f:\aa\ahhfyc.crt";
        string strKeyFN = @"f:\aa\ahhfyc.key";
 
 
        //string strCertFN = System.Web.HttpContext.Current.Server.MapPath(@"user\user.crt");
        //string strCertFNM = System.Web.HttpContext.Current.Server.MapPath(@"user\user.crt");
        //string strKeyFN = System.Web.HttpContext.Current.Server.MapPath(@"user\user.key");
        //string strKey = "12345678";
        string strKey = "12345678";
 
        /// <summary>
        /// 獲取工商銀行驗證資訊
        /// </summary>
        /// <returns></returns>
        public ICBC GetCheckInfo(ICBC argIcbc)
        {
            string strMerSignMsg = string.Empty;
            B2CUtil icbcObj = new B2CUtil();
 
            if (icbcObj.init(strCertFN, strCertFNM, strKeyFN, strKey) == 0)
            {
                //對訂單資料進行簽名,得到訂單簽名資料 MerSignMsg
                argIcbc.MerSignMsg = icbcObj.signC(argIcbc.TranData, argIcbc.TranData.Length);
 
                //證書公鑰   商戶用二進位制方式讀取證書公鑰檔案後,進行BASE64編碼後產生的字串
                argIcbc.MerCert = icbcObj.getCert(1);
                argIcbc.TranData = Base64Encode(argIcbc.TranData);
            }
            else
            {
                return null;
            }
            return argIcbc;
        }
 
        /// <summary>
        /// 獲取工商銀行驗證資訊
        /// </summary>
        /// <returns></returns>
        public ICBC GetCheckReturnInfo(ICBC argIcbc)
        {
            string strMerSignMsg = string.Empty;
            B2CUtil icbcObj = new B2CUtil();
 
            if (icbcObj.init(strCertFN, strCertFNM, strKeyFN, strKey) == 0)
            {
                argIcbc.TranData = Base64Decode(argIcbc.TranData);
 
                if (icbcObj.verifySignC(argIcbc.TranData, argIcbc.TranData.Length, argIcbc.MerSignMsg, argIcbc.MerSignMsg.Length) == 0) //判斷驗證銀行簽名是否成功
                {
                    argIcbc.IsCheck = true;
                }
                else
                    argIcbc.IsCheck = true;
            }
            else
            {
                argIcbc.IsCheck = false;
            }
            return argIcbc;
        }
 
 
        ///<summary>
 
        ///轉成Base64形式的System.String
 
        ///</summary>
 
        ///<param name="str"></param>
 
        ///<returns></returns>
 
        public static string Base64Encode(string str)
        {
 
            byte[] b = System.Text.Encoding.Default.GetBytes(str);
 
            //轉成Base64形式的System.String
 
            return Convert.ToBase64String(b);
 
        }
 
        public static string Base64Encode(Byte[] b)
        {
 
            ///轉成Base64形式的System.String
 
            return Convert.ToBase64String(b);
 
        }
 
        ///<summary>
 
        /// Base64轉回到原來的 System.String
 
        ///</summary>
 
        ///<param name="str"></param>
 
        ///<returns></returns>
 
        public static string Base64Decode(string str)
        {
 
            byte[] c = Convert.FromBase64String(str);
 
            //轉回到原來的 System.String
 
            return System.Text.Encoding.Default.GetString(c);
 
        }
    }
/// <summary>
    /// 工行實體資訊類
    /// </summary>
    public class ICBC
    {
        //private string _orderPostUrl = "https://mybank.icbc.com.cn/servlet/ICBCINBSEBusinessServlet";
        //private string _orderPostUrl = "https://mybank3.dccnet.com.cn/servlet/NewB2cMerPayReqServlet";
        private string _orderPostUrl = "https://myipad.dccnet.com.cn/servlet/ICBCINBSEBusinessServlet";
        //private string _interfaceName = "ICBC_PERBANK_B2C";
        private string _interfaceName = "ICBC_PERBANK_B2C";
        private string _interfaceVersion = "1.0.0.11";
        private string _orderid;
        private string _amount;
        private string _curType = "001";
        //private string _merID = "1302EC23361694";
        private string _merID = "1302EC23928826";
        //private string _merAcct = "1302010119022149867";
        private string _merAcct = "1302010119022141605";
        private string _verifyJoinFlag = "0";
        private string _notifyType = "HS";
        private string _merURL;
        private string _resultType = "1";
        private string _orderDate = DateTime.Now.ToString("yyyyMMddHHmmss");
        private string _merSignMsg;
        private string _merCert;
        private string _goodsID = "10021";
        private string _goodsName = "XXXX";
        private string _goodsNum;
        private string _carriageAmt;
        private string _remark1;
        private string _remark2;
        private string _merHint;
        private string _tranData;
        private string _merReference = "www.XXX.com";
        //private string _merReference = "localhost";
 
        private bool _isCheck = false;
 
        /// <summary>
        /// 是否檢測成功
        /// </summary>
        public bool IsCheck
        {
            get { return _isCheck; }
            set { _isCheck = value; }
        }
 
        public string MerReference
        {
            get { return _merReference; }
            set { _merReference = value; }
        }
 
        /// <summary>
        /// 報文資料
        /// </summary>
        public string TranData
        {
            get { return _tranData; }
            set { _tranData = value; }
        }
 
        /// <summary>
        /// 工商支付介面路徑
        /// </summary>
        public string OrderPostUrl
        {
            get { return _orderPostUrl; }
            set { _orderPostUrl = value; }
        }
 
        /// <summary>
        /// 介面名稱
        /// </summary>
        public string InterfaceName
        {
            get { return _interfaceName; }
            set { _interfaceName = value; }
        }
 
        /// <summary>
        /// 介面版本號
        /// </summary>
        public string InterfaceVersion
        {
            get { return _interfaceVersion; }
            set { _interfaceVersion = value; }
        }
 
        /// <summary>
        /// 訂單號
        /// </summary>
        public string Orderid
        {
            get { return _orderid; }
            set { _orderid = value; }
        }
 
        /// <summary>
        /// 訂單金額
        /// </summary>
        public string Amount
        {
            get { return _amount; }
            set { _amount = value; }
        }
 
        /// <summary>
        /// 支付幣種 RMB:001
        /// </summary>
        public string CurType
        {
            get { return _curType; }
            set { _curType = value; }
        }
 
        /// <summary>
        /// 商戶程式碼
        /// </summary>
        public string MerID
        {
            get { return _merID; }
            set { _merID = value; }
        }
 
        /// <summary>
        /// 商戶賬號         /// </summary>
        public string MerAcct
        {
            get { return _merAcct; }
            set { _merAcct = value; }
        }
 
        /// <summary>
        /// 檢驗聯名標誌
        /// 取值“1”:客戶支付時,網銀判斷該客戶是否與商戶聯名,是則按上送金額扣帳,否則展現未聯名錯誤;
        /// 取值“0”:不檢驗客戶是否與商戶聯名,按上送金額扣帳。
        /// </summary>
        public string VerifyJoinFlag
        {
            get { return _verifyJoinFlag; }
            set { _verifyJoinFlag = value; }
        }
 
        /// <summary>
        /// 通知型別
        /// 取值“HS”:在交易完成後實時將通知資訊以HTTP協議POST方式,主動傳送給商戶,傳送地址為商戶端隨訂單資料提交的接收工行支付結果的URL即表單中的merURL欄位;
        /// 取值“AG”:在交易完成後不通知商戶。商戶需使用瀏覽器登入工行的B2C商戶服務網站,或者使用工行提供的客戶端程式API主動獲取通知資訊。
        /// </summary>
        public string NotifyType
        {
            get { return _notifyType; }
            set { _notifyType = value; }
        }
 
        /// <summary>
        /// 返回商戶URL
        /// </summary>
        public string MerURL
        {
            get { return _merURL; }
            set { _merURL = value; }
        }
 
        /// <summary>
        /// 結果傳送型別
        /// </summary>
        public string ResultType
        {
            get { return _resultType; }
            set { _resultType = value; }
        }
 
        /// <summary>
        /// 交易日期時間
        /// </summary>
        public string OrderDate
        {
            get { return _orderDate; }
            set { _orderDate = value; }
        }
        /// <summary>
        /// 訂單簽名資料
        /// </summary>
        public string MerSignMsg
        {
            get { return _merSignMsg; }
            set { _merSignMsg = value; }
        }
 
        /// <summary>
        /// 商城證書公鑰
        /// </summary>
        public string MerCert
        {
            get { return _merCert; }
            set { _merCert = value; }
        }
 
        /// <summary>
        /// 商品編號
        /// </summary>
        public string GoodsID
        {
            get { return _goodsID; }
            set { _goodsID = value; }
        }
 
        /// <summary>
        /// 商品名稱
        /// </summary>
        public string GoodsName
        {
            get { return _goodsName; }
            set { _goodsName = value; }
        }
 
        /// <summary>
        /// 商品數量
        /// </summary>
        public string GoodsNum
        {
            get { return _goodsNum; }
            set { _goodsNum = value; }
        }
 
        /// <summary>
        /// 已含運費金額
        /// </summary>
        public string CarriageAmt
        {
            get { return _carriageAmt; }
            set { _carriageAmt = value; }
        }
 
        /// <summary>
        /// 備註欄位1
        /// </summary>
        public string Remark1
        {
            get { return _remark1; }
            set { _remark1 = value; }
        }
 
        /// <summary>
        /// 備註欄位2
        /// </summary>
        public string Remark2
        {
            get { return _remark2; }
            set { _remark2 = value; }
        }
 
        /// <summary>
        /// 商城提示
        /// </summary>
        public string MerHint
        {
            get { return _merHint; }
            set { _merHint = value; }
        }
    }

以下為支付頁面邏輯程式碼:

public partial class trainpay : System.Web.UI.Page
    {
        public ICBC icmcModel = new ICBC();
        ICBCTest it = new ICBCTest();
        BLL.PXBCourse bllPXBCourse = new BLL.PXBCourse();
        public string money;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (pxbID != 0 && courseID != "" && UserId != "")
            {
 
                //string ccid = Request.QueryString["cid"];
                //Random rnd = new Random();
                //int n = rnd.Next(1000, 9999);
                //string orderId = DateTime.Now.ToString("yyyyMMddHHmmss") + n.ToString();//訂單號
                string datetime = DateTime.Now.AddDays(-1).ToString("yyyyMMddHHmmss");
               
 
                //總價
                try
                {
                    //string ii = bllPXBCourse.Getbymoney(courseID,pxbID);
                    string ii = "1";
 
                    if (ii != "")
                    {
                        //money = ii + "00";
                        money = ii;
                    }
                    else
                    {
                        //money = "0.01";
                        Response.Write("金額出錯,請聯絡管理員!");
                        Response.End();
                    }
                }
                catch
                {
                    Response.Write("金額出錯,請聯絡管理員!");
                    Response.End();
                }
                //資料處理
                StringBuilder strXml = new StringBuilder();
 
                strXml.Append("<?xml version=\"1.0\" encoding=\"GBK\" standalone=\"no\"?>");
                strXml.Append("<B2CReq>");
                //介面名稱
                strXml.Append("<interfaceName>" + icmcModel.InterfaceName + "</interfaceName>");
                //介面版本號
                strXml.Append("<interfaceVersion>" + icmcModel.InterfaceVersion + "</interfaceVersion>");
                //訂單資訊
                strXml.Append("<orderInfo>");
                //交易日期時間
                strXml.Append("<orderDate>" + icmcModel.OrderDate + "</orderDate>");
                //支付幣種
                strXml.Append("<curType>" + icmcModel.CurType + "</curType>");
                //商戶程式碼
                strXml.Append("<merID>" + icmcModel.MerID + "</merID>");
                //訂單資訊列表
                strXml.Append("<subOrderInfoList>");
                //訂單資訊
                strXml.Append("<subOrderInfo>");
                //訂單編號
                strXml.Append("<orderid>" + OrderId + "</orderid>");
                //訂單金額
                strXml.Append("<amount>" + money + "</amount>");
                //分期付款期數 1代表全額付款
                strXml.Append("<installmentTimes>1</installmentTimes>");
                //商戶賬號
                strXml.Append("<merAcct>" + icmcModel.MerAcct + "</merAcct>");
                //商品編號
                strXml.Append("<goodsID>" + DateTime.Now.ToString("yyyyMMddHHmmss").ToString() + "</goodsID>");
                //商品名稱
                strXml.Append("<goodsName>" + GetPxbname(pxbID) + "</goodsName>");
                //商品數量
                strXml.Append("<goodsNum>1</goodsNum>");
                //已含運費金額
                strXml.Append("<carriageAmt>0</carriageAmt>");
                strXml.Append("</subOrderInfo>");
 
                strXml.Append("</subOrderInfoList>");
                strXml.Append("</orderInfo>");
                strXml.Append("<custom>");
                //檢驗聯名標誌 取值“1”:客戶支付時,網銀判斷該客戶是否與商戶聯名
                strXml.Append("<verifyJoinFlag>" + icmcModel.VerifyJoinFlag + "</verifyJoinFlag>");
                //語言版本 取值:“EN_US”為英文版;取值:“ZH_CN”或其他為中文版
                strXml.Append("<Language>ZH_CN</Language>");
                strXml.Append("</custom>");
                strXml.Append("<message>");
                //支援訂單支付的銀行卡種類
                strXml.Append("<creditType>2</creditType>");
                //通知型別
                strXml.Append("<notifyType>HS</notifyType>");
                //結果傳送型別
                strXml.Append("<resultType>1</resultType>");
                //商戶reference
                strXml.Append("<merReference>" + icmcModel.MerReference + "</merReference>");
                //客戶端IP 當商戶reference項送空時,該項必輸
                strXml.Append("<merCustomIp></merCustomIp>");
                //虛擬商品/實物商品標誌位 取值“0”:虛擬商品 取值“1”,實物商品
                strXml.Append("<goodsType>1</goodsType>");
 
                //買家使用者號   
                strXml.Append("<merCustomID>" + UserId + "</merCustomID>");
                //買家聯絡電話
                strXml.Append("<merCustomPhone>110</merCustomPhone>");
                //收貨地址
                strXml.Append("<goodsAddress></goodsAddress>");
                //訂單備註
                strXml.Append("<merOrderRemark></merOrderRemark>");
                //商城提示
                strXml.Append("<merHint></merHint>");
                //備註欄位1
                strXml.Append("<remark1></remark1>");
                //備註欄位2
                strXml.Append("<remark2></remark2>");
                //返回商戶URL
                strXml.Append("<merURL>http://www.XXX.com/pay/PayReturn.aspx</merURL>");
                //返回商戶變數
                //strXml.Append("<merVAR>" + OrderId + "," + UserId + "," + pxbID + "," + courseID + "</merVAR>");
                strXml.Append("<merVAR>" + OrderId + "," + UserId + "</merVAR>");
                strXml.Append("</message>");
                strXml.Append("</B2CReq>");
 
 
 
              
 
                icmcModel.TranData = strXml.ToString();
                icmcModel = it.GetCheckInfo(icmcModel);
 
                //Payment paymo = new Payment();
                //PaymentBLL paybll = new PaymentBLL();
                //paymo.oid = OrderId;
                //paymo.uid = UserId;
                //paymo.pid = pxbID.ToString();
                //paymo.cid = courseID;
                //paymo.ispay = 0;//0初始化訂單,1支付成功,2支付失敗,3簽名失敗,4資料異常
                //paymo.nopay = 1;//線上1,線下2
                //paymo.ordertime = DateTime.Now;
                //paybll.Add(paymo);
 
            }
            else
            {
                Response.Write("資料非法提交,請正常付費!");
                Response.End();
            }
        }
 
 
        //使用者
        public string UserId
        {
            get
            {
                VerifyUser vuser = new VerifyUser();
                return vuser.GetUserID;
            }
        }
 
        //訂單號
        public string OrderId
        {
            get
            {
                string sid = string.Empty + Request.QueryString["oid"];
               
                return sid;
            }
        }
 
        private BLL.PaymentBLL paymentBll = new PaymentBLL();
        //培訓班
        public int pxbID
        {
            get
            {
 
                //string sid = string.Empty + Request.QueryString["pid"];
                Payment payment = paymentBll.GetModelbyoid(OrderId);
                string sid = payment.pid.ToString();
                int id = 0;
                if (!int.TryParse(sid, out id))
                    return 0;
                return id;
            }
        }
        //課程編號
        public string courseID
        {
            get
            {
                //string cid = Request.QueryString["cid"];
                Payment payment = paymentBll.GetModelbyoid(OrderId);
                string cid = payment.cid;
                cid = cid.Replace("x", ",");
                return cid;
            }
        }
        //培訓班名稱
        public string GetPxbname(int pxbid)
        {
            Community.BLL.PXB bll = new BLL.PXB();
            string name = "";
            Community.Model.PXB model = bll.GetModel(pxbid);
            if (model != null)
            {
                name = model.Name;
            }
            return name;
        }
    }

以下是支付頁面程式碼:

<body>
    <form name="sendOrder" method="post" action="<%= icmcModel.OrderPostUrl %>" id="order">
    <input type="hidden" name="interfaceName" value="<%= icmcModel.InterfaceName %>">
    <input type="hidden" name="interfaceVersion" value="<%= icmcModel.InterfaceVersion %>">
    <input type="hidden" name="tranData" value="<%= icmcModel.TranData %>">
    <input type="hidden" name="merSignMsg" value="<%= icmcModel.MerSignMsg %>">
    <input type="hidden" name="merCert" value="<%= icmcModel.MerCert %>">
     </form>
    <script type="text/javascript">
        document.order.submit();
    </script>
</body>

以下是支付返回頁面:

public partial class PayReturn : System.Web.UI.Page
    {
        public ICBC icmcModel = new ICBC();
        protected void Page_Load(object sender, EventArgs e)
        {
            ICBCTest it = new ICBCTest();
            if (Request.Form["notifyData"] != null)
            {
                Payment paymo = new Payment();
                PaymentBLL paybll = new PaymentBLL();
 
                try
                {
                    //PaymentBLL paybll = new PaymentBLL();
                    ICBCTest icbcCheck = new ICBCTest();
                    ICBC icbcInfo = new ICBC();
 
                    icbcInfo.TranData = Request.Form["notifyData"];
                    icbcInfo.MerSignMsg = Request.Form["signMsg"].ToString();
 
                    icbcInfo = icbcCheck.GetCheckReturnInfo(icbcInfo);
                    //自定義返回
                    string strOrderSN = Request.Form["merVAR"].ToString();
 
                    string[] arrorder = strOrderSN.Split(',');
 
                    string oid = arrorder[0];
                    string uid = arrorder[1];
                    int pid = Convert.ToInt32(arrorder[2]);
                    string cid = arrorder[3];
 
                    if (icbcInfo.IsCheck)//處理簽名
                    {
                        DataSet myds = new DataSet();
                        StringReader strReader = new StringReader(icbcInfo.TranData);
                        myds.ReadXml(strReader);
                        DataTable mytable = new DataTable();
                        mytable = myds.Tables["bank"];
 
                        if (null != mytable && mytable.Rows.Count > 0)
                        {
                            if (mytable.Rows[0]["tranStat"].ToString().Trim() == "1")
                            {
 
                                //這裡做成功操作
 
                                try
                                {
 
                                    //入庫處理
                                    BLL.PXBCourse bllPXBCourse = new BLL.PXBCourse();
                                    BLL.PXBUsers pxbUser = new BLL.PXBUsers();
 
                                    string b = cid;
                                    string[] arrtemp = b.Split('x');
                                    for (int i = 0; i < arrtemp.Length; i++)
                                    {
                                        int courseid = int.Parse(arrtemp[i]);
 
                                        int addi = bllPXBCourse.Addcoursechoose(uid, courseid, pid);
                                    }
 
                                    //付費成功的同時也報名成功
                                    int res = pxbUser.GetRecordCount(" userid='" + uid + "' and pxbid=" + pid);
                                    if (res == 0)
                                    {
                                        Model.PXBUser user = new Model.PXBUser();
                                        user.PXBID = pid;
                                        user.UserID = uid;
                                        user.BYWay = 1;
                                        user.CJWay = 1;
                                        //如果當前人不在當前培訓班,則報名
                                        pxbUser.Add(user);
 
                                    }
                                    // <param name="nopay">支付方式:1為線上支付,2為線下支付</param>
                                    // <param name="ispay">支付狀態:0初始化訂單,1支付成功,2支付失敗,3簽名失敗,4資料異常,5支付中</param>
                                    // <param name="oid">訂單號</param>
                                    paybll.Updatepay(1,1, oid);//支付成功
 
                                    Response.Write("http://122.225.101.115:444/FirstPage.aspx");
                                    Response.End();
                                }
                                catch
                                {
                                    paybll.Updatepay(1,4, oid);//資料異常
 
                                    Response.Write("資料異常,請聯絡管理員!");
                                    Response.End();
                                }
 
 
                            }
                            else
                            {
                                paybll.Updatepay(1,2, oid);//支付失敗
                                Response.Write("支付失敗,請聯絡管理員!");
                                Response.End();
                            }
                        }
                    }
                    else
                    {
                        paybll.Updatepay(1,3, oid);//簽名失敗
                        Response.Write("簽名失敗,請聯絡管理員!");
                        Response.End();
                    }
                }
                catch
                {
                    Response.Write("資料異常,請聯絡管理員!");
                    Response.End();
                }
            }
            else
            {
                Response.Write("返回失敗,請聯絡管理員!");
                Response.End();
            }
        }
    }

然而,比較重要的一個還有支付查詢頁面,防止比如支付成功了,但由於網路異常等原因沒有返回支付成功資料等情況下使用。

以下是支付查詢頁面邏輯程式碼:

public partial class openpay : System.Web.UI.Page
    {
        /// <summary>
        /// 銀行證書檔案地址
        /// </summary>
        static string strCertFN = System.Web.HttpContext.Current.Server.MapPath(@"user\user.crt");
 
        /// <summary>
        /// 商戶證書檔案地址
        /// </summary>
        static string strCertFNM = System.Web.HttpContext.Current.Server.MapPath(@"user\user.crt");
 
        /// <summary>
        /// 私鑰檔名
        /// </summary>
        //static string strKeyFN = System.Web.HttpContext.Current.Server.MapPath(@"user\user.key");
        static string strKeyFN = System.Web.HttpContext.Current.Server.MapPath(@"user\kjks-sy.key");
 
        /// <summary>
        /// 私鑰口令
        /// </summary>
        static string strKey = "12345678";
       // static string api_url = "https://corporbank.icbc.com.cn/servlet/ICBCINBSEBusinessServlet";
        //static string api_url = "https://corporbank3.dccnet.com.cn/servlet/ICBCINBSEBusinessServlet";
        static string api_url = "https://myipad.dccnet.com.cn/servlet/ICBCINBSEBusinessServlet";
        //static string post_params = "APIName=EAPI&APIVersion=001.001.002.001&MerReqData=";
        static string post_params = "APIName=kjks.y.1302&APIVersion=0.0.1.0&MerReqData=";
        static string cert_path = HttpContext.Current.Server.MapPath("~/..");
 
        protected void Page_Load(object sender, EventArgs e)
        {
            string outMess;
            string mess = CheckOrder("201408041357171136 ", "20140804", "1302EC23361694", "1302010119022149867", out outMess);
 
        }
        /// <summary>
        /// 查詢訂單
        /// </summary>
        /// <param name="strOrderNum">訂單號</param>
        /// <param name="strTranDate">交易日期</param>
        /// <param name="strShopCode">商家程式碼</param>
        /// <param name="strShopAccount">商城賬號</param>
        /// <param name="errInfo"></param>
        /// <returns></returns>
        public static string CheckOrder(string strOrderNum, string strTranDate, string strShopCode, string strShopAccount, out string errInfo)
        {
            try
            {
                errInfo = string.Empty;
                StringBuilder sb = new StringBuilder();
                sb.Append("<?xml  version=\"1.0\" encoding=\"GBK\" standalone=\"no\" ?><ICBCAPI><in><orderNum>");
                sb.Append(strOrderNum);
                sb.Append("</orderNum><tranDate>");
                sb.Append(strTranDate);
                sb.Append("</tranDate><ShopCode>");
                sb.Append(strShopCode);
                sb.Append("</ShopCode><ShopAccount>");
                sb.Append(strShopAccount);
                sb.Append("</ShopAccount></in></ICBCAPI>");
                string post_data = post_params + sb.ToString();
                string retruenstring = PostDataBySSL(post_data, api_url, cert_path, strKey, out errInfo);
                //var result = SpringFactory.BusinessFactory.GetBusinessAnonymousUser();
                //result.AddLogs("返回3:" + (retruenstring.Length > 400 ? retruenstring.Substring(0, 400) : retruenstring));
                if (retruenstring.Length <= 5)
                {
                    return retruenstring;
                }
                return HttpUtility.UrlDecode(retruenstring);
            }
            catch
            {
 
                errInfo = "查詢繳費介面失敗";
 
                return "99";
 
            }
        }
 
        /// <summary>
        /// 傳送SSL加密請求
        /// </summary>
        /// <param name="post_data"></param>
        /// <param name="url"></param>
        /// <param name="cert_path"></param>
        /// <param name="cert_password"></param>
        /// <param name="errInfo"></param>
        /// <returns></returns>
        public static string PostDataBySSL(string post_data, string url, string cert_path, string cert_password, out string errInfo)
        {
            errInfo = string.Empty;
            try
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(post_data);
                if (cert_path != string.Empty)
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
 
                WebRequest webRequest = WebRequest.Create(url);
                HttpWebRequest httpRequest = webRequest as HttpWebRequest;
 
                if (cert_path.ToLower().EndsWith(".cer"))
                {
                    httpRequest.ClientCertificates.Add(X509Certificate.CreateFromCertFile(cert_path));
                }
 
                else
                {
                    //SpringFactory.BusinessFactory.GetBusinessAnonymousUser().AddLogs(cert_path);
                    httpRequest.ClientCertificates.Add(new X509Certificate2(cert_path, cert_password, X509KeyStorageFlags.MachineKeySet));
 
 
                }
                httpRequest.KeepAlive = true;
                httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)";
                httpRequest.ContentType = "application/x-www-form-urlencoded";
                httpRequest.Method = "POST";
 
                httpRequest.ContentLength = data.Length;
                Stream requestStream = httpRequest.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();
                Stream responseStream = null;
                responseStream = httpRequest.GetResponse().GetResponseStream();
                string stringResponse = string.Empty;
                if (responseStream != null)
                {
                    using (StreamReader responseReader =
                        new StreamReader(responseStream, Encoding.GetEncoding("GBK")))
                    {
                        stringResponse = responseReader.ReadToEnd();
                    }
                    responseStream.Close();
                }
                return stringResponse;
            }
            catch (Exception e)
            {
                errInfo = e.Message;
 
                // SpringFactory.BusinessFactory.GetBusinessAnonymousUser().AddLogs(e.Message);
                return string.Empty;
            }
        }
 
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
 
    }

三、注意事項

1.在支付傳送資料時,支付金額應該是以“分”為單位,也就是金額是一個整數。

2.在進行測試的時候,訂單提交時間必須和他們伺服器時間一致,而他們,工行測試伺服器時間是被他們設定了的,根本不是正常時間,最重要的一點是,時間每天都在變化,比如今天是2016年8月22號,明天可能是2016年8月26號之類的,之前他們沒有直接誒告訴我,被坑死了。時間不對,支付不了。

3.在測試時,支付成功後不會跳轉到我們的支付返回地址,這個也必須注意一下,這也是他們測試伺服器的原因,本人在這裡也是被坑了,這樣的話我們也無法更新本地訂單支付狀態表。

轉載自個人—波霸38(泥沙)的部落格