Tuesday, April 8, 2014

C# HDFC Payment Gateway ( UMI Method ) Implementation

  1. Payment Request Page

    protected void Page_Load(object sender, EventArgs e)
    {

    #region UMI Method Implementation

    string TranTrackid = string.Empty;
    string TranAmount = string.Empty;

    TranTrackid = YOUR TRANSACTION ID;
    TranAmount = PAYMENT AMOUNT;

    string ReqTranportalId = string.Empty;
    string ReqTranportalPassword = string.Empty;
    ReqTranportalId = "id=" + TRANSPORTAL ID PROVIDED BY BANK + "&";
    ReqTranportalPassword = "password=" + TRANSPORTAL PASSWORD PROVIDED BY BANK + "&";

    string ReqAction = "action=" + "1" + "&";
    string ReqLangid = "langid=" + "USA" + "&";
    string ReqCurrency = "currencycode=" + "356" + "&";
    //356 FOR INR
    string ReqAmount = "amt=" + TranAmount + "&";

    int pos = Request.Url.AbsoluteUri.LastIndexOf('/');
    string strURL = Request.Url.AbsoluteUri.Substring(0, pos + 1) + "PaymentResponseHDFC.aspx";
    //RESPONSE PAGE URL
    string strErrorURL = Request.Url.AbsoluteUri.Substring(0, pos + 1) + "PaymentError.aspx";
    //ERROR PAGE URL
    string ReqResponseUrl = "responseURL=" + strURL + "&";
    string ReqErrorUrl = "errorURL=" + strErrorURL + "&";

    string ReqTrackId = "trackid=" + TranTrackid + "&";

    string HDFCPayURL = string.Empty;
    HDFCPayURL = SECUREPG; //SECUREPGTEST for UAT and SECUREPG for PRODUCTION

    string ReqUdf1 = string.Empty;
    string ReqUdf2 = string.Empty;
    string ReqUdf3 = string.Empty;
    string ReqUdf4 = string.Empty;
    string ReqUdf5 = string.Empty;

    ReqUdf1 = "udf1=" + FirstName + "&";            // UDF1 values                                                               
    ReqUdf2 = "udf2=" + PersonalEmailID + "&";        // UDF2 values                                                                   
    ReqUdf3 = "udf3=" + MobileNumber + "&";             // UDF3 values
    ReqUdf4 = "udf4=" + City +"&";                 // UDF4 values       
    ReqUdf5 = "udf5=" + UserIdentifier + "&";        // UDF5 values 

    try
    {
        string TranResponse = "";//Declaration of variable
        string TranRequest = ReqTranportalId + ReqTranportalPassword + ReqAction + ReqLangid + ReqCurrency + ReqAmount + ReqResponseUrl + ReqErrorUrl + ReqTrackId + ReqUdf1 + ReqUdf2 + ReqUdf3 + ReqUdf4 + ReqUdf5;
        string TranUrl = "https://" + HDFCPayURL + ".fssnet.co.in/pgway/servlet/PaymentInitHTTPServlet";
        System.IO.StreamWriter myWriter = null;

        // it will open a http connection with provided url
        System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(TranUrl);//send data using objxmlhttp object
        objRequest.Method = "POST";
        objRequest.ContentLength = TranRequest.Length;
        objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
        myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
        myWriter.Write(TranRequest);//send data
        myWriter.Close();//closed the myWriter object

        System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
        //receive the responce from objxmlhttp object
        using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
        {
        TranResponse = sr.ReadToEnd();

        string[] ErrorCheck = GetStringInBetween(TranResponse, "!", "!-", false, false);//This line will find Error Keyword in TranResponse   

        if (ErrorCheck[0] != "ERROR")//This block will check for Error in TranResponce
        {
            // Merchant MUST map (update) the Payment ID received with the merchant Track Id in his database at this place.
            string payid = TranResponse.Substring(0, TranResponse.IndexOf(":http"));
            string payURL = TranResponse.Substring(TranResponse.IndexOf("http"));
            // here redirecting the customer browser from ME site to Payment Gateway Page with the Payment ID

            //UPDATE THE payid(PAYMENT ID) IN DB
            //
            //CODE FOR UPDATE PAYMENT ID
            //

            //REDIRECT ON payURL(PAYMENT GATEWAY URL)
            string TranRedirect = payURL + "?PaymentID=" + payid;
            Response.Redirect(TranRedirect);
        }
        else
        {
            string TranErrorUrl = strErrorURL + "?Message=Transaction Failed&ResTrackId=" + TranTrackid + "&ResAmount=" + TranAmount + "&ResError=" + TranResponse;
       
            //REDIRECT TO ERROR PAGE   
            Response.Redirect(TranErrorUrl);
        }

        }
    }
    catch (Exception ex)// any excpetion occurred for above code exception throws here
    {
        //REDIRECT ON ERROR PAGE IN CASE OF ERROR
    }

    }

    #endregion

    }

    public static string[] GetStringInBetween(string strSource, string strBegin, string strEnd, bool includeBegin, bool includeEnd)
        {
            string[] result = { "", "" };
            int iIndexOfBegin = strSource.IndexOf(strBegin);
            if (iIndexOfBegin != -1)
            {
                // include the Begin string if desired

                if (includeBegin)
                {
                    iIndexOfBegin -= strBegin.Length;
                }
                strSource = strSource.Substring(iIndexOfBegin + strBegin.Length);
                int iEnd = strSource.IndexOf(strEnd);
                if (iEnd != -1)
                {  // include the End string if desired
                    if (includeEnd)
                    { iEnd += strEnd.Length; }
                    result[0] = strSource.Substring(0, iEnd);
                    // advance beyond this segment
                    if (iEnd + strEnd.Length < strSource.Length)
                    { result[1] = strSource.Substring(iEnd + strEnd.Length); }
                }
            }
            else
            // stay where we are
            { result[1] = strSource; }
            return result;
        }//String function end
  2. Payment Response Page


    protected void Page_Load(object sender, EventArgs e)
    {

        #region UMI Method Implementation

        string strResponceIP, TranInqResponse, ResPaymentId, ResResult, ResErrorText, ResPosdate, ResTranId, ResAuth, ResAVR, ResAmount, ResErrorNo, ResTrackID, ResRef, Resudf1, Resudf2, Resudf3, Resudf4, Resudf5, EMI;

        strResponceIP = HttpContext.Current.Request.UserHostAddress;
        int pos = Request.Url.AbsoluteUri.LastIndexOf('/');

        VALIDATE THE IP ADDRESS


        if ( ( (HOSTED ON PRODUCTION) && strResponceIP != "221.134.101.187" && strResponceIP != "221.134.101.175" && strResponceIP != "221.134.101.166" && strResponceIP.Trim() != "10.1.40.2")
            || ( (HOSTED ON UAT) && strResponceIP != "221.134.101.174" && strResponceIP != "221.134.101.169" && strResponceIP.Trim() != "10.1.40.2"))
        {
            //REDIRECT TO ERROR PAGE IF IP DOES NOT MATCH
        }
        else
        {
            // IP MATCHED
           
            ResErrorText = Request["ErrorText"];        //Error Text/message
            ResPaymentId = Request["paymentid"];        //Payment Id
            ResTrackID = Request["trackid"];            //Merchant Track ID
            ResErrorNo = Request["Error"];            //Error Number

            //To collect transaction result
            ResResult = Request["result"];            //Transaction Result
            ResPosdate = Request["postdate"];            //Postdate
            //To collect Payment Gateway Transaction ID, this value will be used in dual verification request
            ResTranId = Request["tranid"];            //Transaction ID
            ResAuth = Request["auth"];                //Auth Code       
            ResAVR = Request["avr"];                //TRANSACTION avr                   
            ResRef = Request["ref"];                //Reference Number also called Seq Number
            //To collect amount from response
            ResAmount = Request["amt"];                //Transaction Amount

            Resudf1 = Request["udf1"];                //UDF1
            Resudf2 = Request["udf2"];                //UDF2
            Resudf3 = Request["udf3"];                //UDF3
            Resudf4 = Request["udf4"];                //UDF4
            Resudf5 = Request["udf5"];                //UDF5

            try
            {
            // LOG THE RESPONSE FIRST
            string strRemarks = "Paymentid: " + ResPaymentId + " Result: " + ResResult + " ResErrorText:" + ResErrorText + " ResErrorNo:" + ResErrorNo + " ResAVR:" + ResAVR + " ResAmount:" + ResAmount + " ResRef:" + ResRef + " Postdate: " + ResPosdate + " PGTransactionID: " + ResTranId + " TransactionID: " + ResTrackID + " auth: " + ResAuth + " Resudf1: " + Resudf1 + " Resudf1: " + Resudf2 + " Resudf3: " + Resudf3 + " Resudf4: " + Resudf4 + " Resudf5: " + Resudf5;
            GlbFunctions.LogEvent(Page, "3.Response Page Param values: " + strRemarks + " Response Time: " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"), "S");
            }
            catch (Exception ex)
            {
            GlbFunctions.LogError("Payment Verify - Logging result", "Message: " + ex.Message + " StackTrace: " + ex.StackTrace, "WEBAPPLN_UI_TRANSACTIONS_PaymentResponseHDFC", "Page_Load", "UI", "-1");
            }

            if (ResErrorNo == null)
            {   
            //check result is captured or approved i.e. successful
            if (ResResult == "CAPTURED" || ResResult == "APPROVED")//If resulr is CAPTURED or APPROVED then below Code is execute for dual inquiry
            {
                //Validate parameters   
                if (ResPaymentId == null || ResTrackID == null || ResTranId == null || ResAuth == null || ResRef == null || ResAmount == null)
                {
                // REDIRECT TO ERROR PAGE IF REQUIRED PARAMETERS ARE NULL
                Response.Clear();
                Response.Write("REDIRECT=" + Request.Url.AbsoluteUri.Substring(0, pos + 1) + "PaymentError.aspx?Message=PARMETER VALIDATION FAILED");
                Response.End();
                }
                else
                {
                string ReqTranportalId = string.Empty;
                string ReqTranportalPassword = string.Empty;
               
                //DUAL VERIFIACTION URL, this is test environment URL, contact bank for production DUAL Verification URL
                string INQUrl = "https://" + PAYMENT GATE WAY URL(SECUREPG / SECUREPGTEST) + ".fssnet.co.in/pgway/servlet/TranPortalXMLServlet";
                ReqTranportalId = "<id>" + TRANSPORTAL ID PROVIDED BY BANK + "</id>";
                ReqTranportalPassword = "<password>" + TRANSPORTAL PASSWORD PROVIDED BY BANK + "</password>";
               
                // Pass DUAL VERIFICATION action code, always pass "8" for DUAL VERIFICATION
                string INQAction = "<action>8</action>";
                //Pass PG Transaction ID for Dual Verification
                string INQTransId = "<transid>" + ResTranId + "</transid>";
                //create string for request of input parameters
                string INQRequest = ReqTranportalId + ReqTranportalPassword + INQAction + INQTransId;

                try
                {
                    //create a SSL connection xmlhttp formated object server-to-server
                    System.IO.StreamWriter myWriter = null;
                    // it will open a http connection with provided url
                    System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(INQUrl);//send data using objxmlhttp object

                    objRequest.Method = "POST";
                    objRequest.ContentLength = INQRequest.Length;
                    objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
                    myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());

                    myWriter.Write(INQRequest);//send data
                    myWriter.Close();//closed the myWriter object

                    System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

                    //receive the responce from objxmlhttp object
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
                    {
                    TranInqResponse = sr.ReadToEnd();
                    string[] INQCheck = GetStringInBetween(TranInqResponse, "<result>", "</result>", false, false);//This line will check if any error in TranInqResponse        

                    if (INQCheck[0] == "CAPTURED" || INQCheck[0] == "APPROVED" || INQCheck[0] == "SUCCESS")
                    {
                        string[] INQResResult = GetStringInBetween(TranInqResponse, "<result>", "</result>", false, false);//It will give DualInquiry Result
                        string[] INQResAmount = GetStringInBetween(TranInqResponse, "<amt>", "</amt>", false, false);//It will give Amount
                        string[] INQResTrackId = GetStringInBetween(TranInqResponse, "<trackid>", "</trackid>", false, false);//It will give TrackID ENROLLED
                        string[] INQResPayid = GetStringInBetween(TranInqResponse, "<payid>", "</payid>", false, false);//It will give payid
                        string[] INQResRef = GetStringInBetween(TranInqResponse, "<ref>", "</ref>", false, false);//It will give Ref.NO.
                        string[] INQResTranid = GetStringInBetween(TranInqResponse, "<tranid>", "</tranid>", false, false);//It will give tranid                                  


                        //UPDATE THE PAYMENT RESPONSE IN DB BASED ON PAYMENT STATUS   
                        //switch (INQCheck[0].Trim())
                        //{
                        //    case "CAPTURED":
                        //    break;
                        //    case "APPROVED":
                        //    break;
                        //    case "SUCCESS":
                        //    break;
                        //    default:
                        //    break;
                        //}

                        Response.Clear();
                       
                        //REDIRECT TO OTHER PAGE OR SHOW THE PAYMENT STATUS ON THE SAME PAGE
                        Response.Write("REDIRECT=" + strURL);
                        Response.End();           
                      
                    }
                    else
                    {
                        // PAYMENT NOT SUCCESSFUL
                        // REDIRECT TO ERROR PAGE              
                    }
                    }
                }
                catch (Exception ex)
                {
                    // REDIRECT TO ERROR PAGE IN CASE OF ANY ERROR
                }
                }
            }
            else
            {
                // REDIRECT TO ERROR PAGE IF PAYMENT IS NOT SUCCEEDED
            }
            }
            else
            {
            // REDIRECT TO ERROR PAGE IF THE ERROR MESSAGE IS NOT NULL
            }
        }

        #endregion

    }

    public static string[] GetStringInBetween(string strSource, string strBegin, string strEnd, bool includeBegin, bool includeEnd)
        {
            string[] result = { "", "" };
            int iIndexOfBegin = strSource.IndexOf(strBegin);
            if (iIndexOfBegin != -1)
            {
                // include the Begin string if desired

                if (includeBegin)
                {
                    iIndexOfBegin -= strBegin.Length;
                }
                strSource = strSource.Substring(iIndexOfBegin + strBegin.Length);
                int iEnd = strSource.IndexOf(strEnd);
                if (iEnd != -1)
                {  // include the End string if desired
                    if (includeEnd)
                    { iEnd += strEnd.Length; }
                    result[0] = strSource.Substring(0, iEnd);
                    // advance beyond this segment
                    if (iEnd + strEnd.Length < strSource.Length)
                    { result[1] = strSource.Substring(iEnd + strEnd.Length); }
                }
            }
            else
            // stay where we are
            { result[1] = strSource; }
            return result;
        }//String function end

2 comments: