Wednesday, April 9, 2014

C# ATOM Payment Gateway Implementation

  1. Payment Request Page

    protected void Page_Load(object sender, EventArgs e)
    {
    try
    {           
        string ATOMPaymentIP = ATOMPaymentIP // PROVIDED BY ATOM //203.114.240.183--Stage
        string ATOMLogin = ATOMLogin // PROVIDED BY ATOM
        string ATOMPassword = ATOMPassword // PROVIDED BY ATOM
        string ATOMTransactionType = ATOMTransactionType // PROVIDED BY ATOM
        string ATOMProductId = ATOMProductId // PROVIDED BY ATOM

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + ATOMPaymentIP + "/paynetz/epi/fts");

        request.Method = "POST";

        request.ContentType = "application/x-www-form-urlencoded";
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; CK={CVxk71YSfgiE6+6P6ftT7lWzblrdvMbRqavYf/6OcMIH8wfE6iK7TNkcwFAsxeChX7qRAlQhvPWso3KI6Jthvnvls9scl+OnAEhsgv+tuvs=}; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        int pos = Request.Url.AbsoluteUri.LastIndexOf('/');
       
        // PAYMENT RESPONSE PAGE
        string strURL = Request.Url.AbsoluteUri.Substring(0, pos + 1) + "PaymentResponseATOM.aspx";
       
        string postData = "custacc=1234567890&login=" + ATOMLogin + "&pass=" + ATOMPassword + "&ttype=" + ATOMTransactionType + "&prodid=" + ATOMProductId + "&amt=" + PAYMENT AMOUNT + "&txncurr=INR&txnscamt=0&clientcode=" + CLIENT CODE(USER DEFINED) + "=&txnid=" + TRANSACTION ID + "&date=" + DateTime.Now.ToString("dd/mm/yyyy hh:mm:ss") + "&ru=" + strURL + "&udf1=" + FIRST NAME + "&udf2=" + EMAIL OF CUSTOMER + "&udf3=" + CUSTOMER MOBILE + "&udf4=" + CUSTOMER ADDRESS + "&udf5=" + EMI OPTION IF REQUIRED(BANK NAME) + "&udf6=" + EMI OPTION IF REQUIRED;

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";

        request.ContentLength = byteArray.Length;
        request.AllowAutoRedirect = true;

        request.Proxy.Credentials = CredentialCache.DefaultCredentials;

        Stream dataStream = request.GetRequestStream();

        dataStream.Write(byteArray, 0, byteArray.Length);

        dataStream.Close();

        WebResponse response = request.GetResponse();

        XmlDocument objXML = new XmlDocument();

        dataStream = response.GetResponseStream();

        objXML.Load(dataStream);

        string TxnId = objXML.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes[2].InnerText;

        string Token = objXML.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes[3].InnerText;
        string txnData = "ttype=NBFundTransfer&txnStage=1&tempTxnId=" + TxnId + "&token=" + Token;

        dataStream.Close();
        response.Close();
        Response.Redirect("http://" + ATOMPaymentIP + "/paynetz/epi/fts?" + txnData);
    }
    catch (Exception ex)
    {
        HANDLE ERROR   
    }
    }
  2. Payment Response Page

    protected void Page_Load(object sender, EventArgs e)
    {
    try
    {
        if (!IsPostBack)
        {
        NameValueCollection nvc = Request.Form;
        string mmp_Transaction = nvc["mmp_txn"].ToString();
        string PaymentStatus = nvc["f_code"].ToString();
        string MerchantTransactionId = Request.Form["mer_txn"];

        string Amount = Request.Form["amt"];
        string Product = Request.Form["prod"];
        string TransactionDate = Request.Form["date"];
        string BankTransactionId = Request.Form["bank_txn"];
        string ClientCode = Request.Form["clientcode"]; // Encrypted User Information
        string BankName = Request.Form["bank_name"];

        //User Details
        string Udf1 = Request.Form["udf1"]; //First Name
        string Udf2 = Request.Form["udf2"]; //Email
        string Udf3 = Request.Form["udf3"]; //Mobile
        string Udf4 = Request.Form["udf4"]; //Address
        string Udf5 = Request.Form["udf5"]; //Bank Name
        string Udf6 = Request.Form["udf6"]; //EMI Option

        string strResponceIP = HttpContext.Current.Request.UserHostAddress;
        string strRemarks = "txnId:" + MerchantTransactionId + ", txnStatus:" + PaymentStatus + ", amount:" + Amount + ", pgTxnId:" + mmp_Transaction + ", BankTransactionId:" + BankTransactionId + ", Udf1:" + Udf1 + ", Udf2:" + Udf2 + ", Udf3:" + Udf3 + ", Udf4:" + Udf4 + ", Udf5:" + Udf5 + ", Udf6:" + Udf6;

       
        string ATOMPaymentIP = ConfigurationManager.AppSettings["ATOMPaymentIP"].ToString();//203.114.240.183--Stage
        //Verify the Response Server
        if (Request.UrlReferrer.Host.Trim() != ATOMPaymentIP)
        {
            // REDIRECT TO ERROR PAGE IF RESPONSE IP IS NOT VERIFIED
        }

        // CHECK THE PAYMENT STATUS AND VALIDATE THE TRANSACTION ID
        if (PaymentStatus.ToUpper().Trim() == "OK" && transactionid.Trim()==MerchantTransactionId.Trim())
        {
            //"Transaction proceed successfully."

            // UPDATE THE TRANSACTION STATUS IN DB
            //
            // CODE FOR UPDATE STATUS
            //
            //
           
            // REDIRECT TO SUCCESS PAGE OR SHOW THE PAYMENT RESPONSE ON SAME PAGE   

        }
        else
        {
            // PAYMENT STATUS IS NOT SUCCESS OR TRANSACTION ID IS NOT VERIFIED
            // REDIRECT TO ERROR PAGE
        }
        }
    }
    catch (Exception ex)
    {
        // HANDLE ERROR
    }
    }

C# ccAvenue Payment Gateway Implementation

  1. Payment Request Page ( ASPX )


    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <script src="../js/jquery.min.js" type="text/javascript"></script>
        <script>
            jQuery(document).ready(function () {
                jQuery("#btnSubmit").click();
                //Custom.init();
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table style="display: none;">
            <tr>
                <td>
                    OrderId:
                </td>
                <td>
                    <asp:Label ID="lblOrderId" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    Amount:
                </td>
                <td>
                    <asp:Label ID="lblAmount" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    MerchantId:
                </td>
                <td>
                    <asp:Label ID="lblMerchantId" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    RedirectURL:
                </td>
                <td>
                    <asp:Label ID="lblRedirectUrl" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    BillingCustomerName:
                </td>
                <td>
                    <asp:Label ID="lblCustomerName" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    BillingCustomerAddress:
                </td>
                <td>
                    <asp:Label ID="lblCustAddr" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    BillingCustomerCountry:
                </td>
                <td>
                    <asp:Label ID="lblCustCountry" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    BillingCustomerTelephone:
                </td>
                <td>
                    <asp:Label ID="lblCustPhone" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    BillingCustomerEmail:
                </td>
                <td>
                    <asp:Label ID="lblCustEmail" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    BillingCustomerState:
                </td>
                <td>
                    <asp:Label ID="lblCustState" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    BillingCustomerCity:
                </td>
                <td>
                    <asp:Label ID="lblCustCity" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    ZipCode:
                </td>
                <td>
                    <asp:Label ID="lblZipCode" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    CustomerNotes:
                </td>
                <td>
                    <asp:Label ID="lblCustNotes" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    DeliveryCustomerName:
                </td>
                <td>
                    <asp:Label ID="lblDelCustName" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    DeliveryCustomerAddress:
                </td>
                <td>
                    <asp:Label ID="lblDelCustAddr" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    DeliveryCustomerCountry:
                </td>
                <td>
                    <asp:Label ID="lblDelCustCntry" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    DeliveryCustomerTelephone:
                </td>
                <td>
                    <asp:Label ID="lblDelCustTel" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    DeliveryCustomerState:
                </td>
                <td>
                    <asp:Label ID="lblDelCustState" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    DeliveryCustomerCity:
                </td>
                <td>
                    <asp:Label ID="lblDelCustCity" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    DeliveryCustomerZipCode:
                </td>
                <td>
                    <asp:Label ID="lblDelZipCode" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    MerchantParam:
                </td>
                <td>
                    <asp:Label ID="lblMerchantParam" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <asp:Label ID="lblPayType" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" PostBackUrl="http://www.ccavenue.com/shopzone/cc_details.jsp" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:HiddenField ID="Merchant_Id" runat="server" />
                    <asp:HiddenField ID="encRequest" runat="server" />
                </td>
            </tr>
        </table>
        <center>
            <asp:Label ID="lb_Message" Style="color: Red; display: block; margin-top: 35px;"
                runat="server" Text=""></asp:Label>
        </center>
        </form>
    </body>
    </html>
  2. Payment Request Page ( ASPX.CS )

    CCACrypto chkSum = new CCACrypto();
    string MerchantId = ccAvenueMerchantId // PROVIDED By ccAvenue
    string WorkingKey = ccWorkingKey // Provided By ccAvenue
       
    protected void Page_Load(object sender, EventArgs e)
    {           
        if (IsPostBack == false)
        {
        //PAYMENT RESPONSE PAGE
        string ResponseUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                    HttpContext.Current.Request.ApplicationPath + "Payment/PaymentResponse.aspx";
        //Get Payment Details from Session

            lblOrderId.Text = TRANSACTION ID
            lblAmount.Text = PAYMENT AMOUNT
            lblMerchantId.Text = MerchantId;
            lblRedirectUrl.Text = ResponseUrl;
            lblCustomerName.Text = CUSTOMER NAME
            lblCustAddr.Text = CUSTOMER ADDRESS
            lblCustCountry.Text = CUSTOMER COUNTRY
            lblCustPhone.Text = CUSTOMER PHONE
            lblCustEmail.Text = CUSTOMER EMAIL
            lblCustState.Text = CUSTOMER STATE
            lblCustCity.Text = CUSTOMER CITY
            lblZipCode.Text = CUSTOMER ZIP
            lblCustNotes.Text = CUSTOMER NOTES
            lblDelCustName.Text = CUSTOMER DELIVERY NAME
            lblDelCustAddr.Text = CUSTOMER DELIVERY ADDRESS
            lblDelCustCntry.Text = CUSTOMER DELIVERY COUNTRY
            lblDelCustTel.Text = CUSTOMER DELIVERY PHONE
            lblDelCustState.Text = CUSTOMER DELIVERY STATE
            lblDelCustCity.Text = CUSTOMER DELIVERY CITY
            lblDelZipCode.Text = CUSTOMER DELIVERY ZIP
            lblMerchantParam.Text = MERCHANT EXTRA PARAMETERS
            lblPayType.Text = PAYMENT TYPE(Credit Card/ Debit Card/ Net Banking)

            string Res = chkSum.getchecksum(MerchantId, lblOrderId.Text, objPaymentDetails.PaymentAmount.ToString(),
                            ResponseUrl, WorkingKey);
            string billingPageHeading = "";
            string ToEncrypt = "Order_Id=" + lblOrderId.Text + "&Amount=" + objPaymentDetails.PaymentAmount + "&Merchant_Id=" + MerchantId + "&Redirect_Url=" + ResponseUrl +
            "&Checksum=" + Res + "&billing_cust_name=" + objPaymentDetails.Cust_Name + "&billing_cust_address=" + objPaymentDetails.Cust_Add + "&billing_cust_country=" + lblCustCountry.Text +
            "&billing_cust_tel=" + objPaymentDetails.Cust_Mobile + "&billing_cust_email=" + objPaymentDetails.Cust_Email + "&billing_cust_state=" + lblCustState.Text +
            "&billing_cust_city=" + lblCustCity.Text + "&billing_zip_code=" + lblZipCode.Text + "&billing_cust_notes=" + lblCustNotes.Text +
            "&delivery_cust_name=" + objPaymentDetails.Cust_Name + "&delivery_cust_address=" + objPaymentDetails.Cust_Add + "&delivery_cust_country=" + lblDelCustCntry.Text +
            "&delivery_cust_tel=" + objPaymentDetails.Cust_Mobile + "&delivery_cust_state=" + lblDelCustState.Text + "&delivery_cust_city=" + lblDelCustCity.Text +
            "&delivery_zip_code=" + lblDelZipCode.Text + "&Merchant_Param=" + lblMerchantParam.Text + "&billingPageHeading=" + billingPageHeading + "&payType=" + lblPayType.Text;

            string Encrypted;
            Encrypted = chkSum.Encrypt(ToEncrypt, WorkingKey);

            Merchant_Id.Value = MerchantId;
            encRequest.Value = Encrypted;

            lb_Message.Text = "Wait... Redirecting to Payment Gateway.";

        }
        else
        {
            lb_Message.Text = "Error on Payment Gateway. Kindly try again.";
        }
        }
    }
  3. Payment Response Page

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
        string WorkingKey = ccWorkingKey // PROVIDED BY ccAvenue
        CCACrypto func = new CCACrypto();
        string encResponse = Request.Form.ToString();

        NameValueCollection Params = new NameValueCollection();
        string[] segments = encResponse.Split('&');
        foreach (string seg in segments)
        {
            string[] parts = seg.Split('=');
            if (parts.Length > 0)
            {
            string Key = parts[0].Trim();
            string Value = parts[1].Trim();

            Params.Add(Key, Value);
            }
        }
        try
        {                    
            //Verify with ccAvenue
            string strVerify = func.verifychecksum(Params["Merchant_Id"].ToString(), Params["Order_Id"].ToString(), Params["Amount"].ToString(), Params["AuthDesc"].ToString(), WorkingKey, Params["Checksum"].ToString());

            if (strVerify.ToUpper() == "TRUE")
            {
            if (objPaymentDetails != null)
            {
                // UPDATE THE PAYMENT STATUS IN DB

                //Update the Payment Status in DB
                //if (Params["AuthDesc"].ToString().Trim() == "Y")
                //    SUCCESS
                //else
                //    FAIL
           
               // REDIRECT TO SUCCESS PAGE OR SHOW THE PAYMENT RESPONSE ON SAME PAGE

            }
            else
            {
                // PAYMENT IS FAIL
                // REDIRECT TO ERROR PAGE
            }
            }
            else
            {
            // PAYMENT VERIFICATION IS FAILED
            // REDIRECT TO ERROR PAGE
            }           
        }
        catch (Exception ex)
        {
            // ERROR IN PROCESSING
            // REDIRECT TO ERROR PAGE
        }
        }
    }

C# Tech Process Payment Gateway Implementation

  1. Payment Request Page

    #region Tech Process Code
    COM.TPSLUtil1 objTPSLUtil1 = new COM.TPSLUtil1();
    COM.CheckSumRequestBean objCheckSumRequestBean = new COM.CheckSumRequestBean();

    objCheckSumRequestBean.MerchantTranId = YOUR TRANSACTION ID;
    objCheckSumRequestBean.MarketCode = CURRENCY CODE;
    objCheckSumRequestBean.AccountNo = BANK ACCOUNT CODE
    objCheckSumRequestBean.Amt = PAYMENT AMOUNT
    objCheckSumRequestBean.BankCode = "240";
    objCheckSumRequestBean.PropertyPath = "C:\\MerchantDetails.property";

    string strMsg = objTPSLUtil1.transactionRequestMessage(objCheckSumRequestBean);

    if (!strMsg.Equals(""))
    {
        Response.Redirect("https://www.tpsl-india.in/PaymentGateway/TransactionRequest.jsp?msg=" + strMsg);
    }
    #endregion
  2. Payment Response Page

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {

            COM.CheckSumResponseBean objCheckSumResponseBean = new COM.CheckSumResponseBean();
            TPSLUtil1 objTPSLUtil1 = new TPSLUtil1();
            String strResponseMsg = Request["msg"] == null ? "" : Request["msg"].Trim();
              
            string strResponceIP = HttpContext.Current.Request.UserHostAddress;
            string strLogDesc = string.Empty;

            String[] token = strResponseMsg.Split('|');
            string txtchecksum, txtauthstatus, txterrordesc, txtsettlementtype, txtaddtninfo1, txtaddtninfo2, txtaddtninfo3, txterrorstatus;
           
            if (token.Length == 26)
            {
                txtchecksum = token[25].ToString();
                txtauthstatus = token[14].ToString();
                txterrordesc = token[24].ToString();
                txtauthstatus = token[14].ToString();
                txtsettlementtype = token[15].ToString();
                txtaddtninfo1 = token[16].ToString();
                txtaddtninfo2 = token[17].ToString();
                txtaddtninfo3 = token[18].ToString();
                txterrorstatus = token[23].ToString();

                if (txtauthstatus == "0399")
                {
                // ERROR IN PAYMENT
                // REDIRECT TO ERROR PAGE   
                return;
                }
            }
            else
            {
                // NOT VALID RESPONSE
                // REDIRECT TO ERROR PAGE
                return;
            }

            string strRemarks = "Merchant Id:" + token[0].ToString() + ", Subscriber Id:" + token[1].ToString() + ", Ref No:" + token[2].ToString() + ", Bank Ref No:" + token[3].ToString() + ", Amount:" + token[4].ToString() + ", Bank Id:" + token[5].ToString() + ", Bank Merchant Id:" + token[6].ToString() + ", cntype:" + token[7].ToString() + ", Currency:" + token[8].ToString() + ", temCode:" + token[9].ToString() + ", Security Type:" + token[10].ToString() + ", Security ID:" + token[11].ToString() + ", Security Pass:" + token[12].ToString() + ", Date:" + token[13].ToString() + ", Status:" + token[14].ToString() + ", Settellement Type:" + token[15].ToString() + ", Add Info1:" + token[16].ToString() + ", Add Info2:" + token[17].ToString() + ", Add Info3:" + token[18].ToString() + ", Add Info4:" + token[19].ToString() + ", Add Info5:" + token[20].ToString() + ", Add Info6:" + token[21].ToString() + ", Add Info7:" + token[22].ToString() + ", Error Status:" + token[23].ToString() + ", Error Desc:" + token[24].ToString() + ", Check Sum:" + token[25].ToString();

            objCheckSumResponseBean.MSG = strResponseMsg;
            objCheckSumResponseBean.PropertyPath = "C:\\TechProcess-Interface\\NLMerchantDetails.property";
           
            string strCheckSumValue = string.Empty;
           
            strCheckSumValue = objTPSLUtil1.transactionResponseMessage(objCheckSumResponseBean);

            if (!strCheckSumValue.Equals(""))
            {
                if (!txtchecksum.Equals(strCheckSumValue))
                {
                txtauthstatus = "0399";
                // Transaction Failed due to checksum mismatch
                // REDIRECT TO ERROR PAGE

                }
                else
                {
                //0300 // SUCCESS CODE
                try
                {
                    // UPDATE THE TRANSACTION STATUS IN DB
                    //
                    // CODE FOR UPDATE STATUS
                    //
                    //
           
                    // REDIRECT TO OTHER PAGE OR SHOW THE PAYMENT RESPONSE ON SAME PAGE
                }
                catch (Exception ex)
                {
                    // INVALID RESPONSE CODE
                    // REDIRECT TO ERROR PAGE
                }
                }
            }
            else
            {
                // INVALID RESPONSE CODE
                // REDIRECT TO ERROR PAGE
            }

            }
        }
        catch (Exception ex)
        {
            // ERROR OCCURED
            // REDIRECT TO ERROR PAGE
        }

    }

C# CITRUS Payment Gateway Implementation

  1. Payment Request Page (ASPX)

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">

        <script src="../../RESOURCES/js/accordion/jquery.min.js" type="text/javascript"></script>
        <title>Redirecting...</title>
         <script type="text/javascript">

             $(document).ready(function () {
                 $('#FName').val($('#hdnFname').val());
                 $('#LName').val($('#hdnLname').val());
                 $('#Email').val($('#hdnEmail').val());
                 $('#Address').val($('#hdnAddress').val());
                 $('#City').val($('#hdnCity').val());
                 $('#AddressZip').val($('#hdnZip').val());
                 $('#State').val($('#hdnState').val());
                 $('#Mobile').val($('#hdnMobile').val());
                 $('#returnUrl').val($('#hdnReturnUrl').val());
                 //alert($('#FName').val());
                 merchantURLPart = $('#hdnPaymentURL').val();
                 $('#btnSubmit').click();
             });

             var merchantURLPart = '';
         //"https://sandbox.citruspay.com/CLIENTID"; -- CLIENTID WILL BE PROVIDED BY CITRUS
            
         var vanityURLPart = "";
             var reqObj = null;
             function generateHMAC() {
                 if (window.XMLHttpRequest) {
                     reqObj = new XMLHttpRequest();
                 } else {
                     reqObj = new ActiveXObject("Microsoft.XMLHTTP");
                 }
                 if (merchantURLPart.lastIndexOf("/") != -1) {
                     vanityURLPart = merchantURLPart.substring(merchantURLPart.lastIndexOf("/") + 1)
                 }
                 var orderAmount = document.getElementById("orderAmount").value;
                 var merchantTxnId = document.getElementById("merchantTxnId").value;
                 var currency = document.getElementById("currency").value;
                 var param = "merchantId=" + vanityURLPart + "&orderAmount=" + orderAmount
                    + "&merchantTxnId=" + merchantTxnId + "&currency=" + currency;
                 reqObj.onreadystatechange = process;
                 reqObj.open("POST", "hmac_signature.aspx?" + param, false);
                 reqObj.send(null);
             }
             function process() {
                 if (reqObj.readyState == 4) {
                     document.getElementById("secSignature").value = reqObj.responseText;
                     submitForm();
                 }
             }

             function submitForm() {
                 document.paymentForm.action = merchantURLPart;
                 document.paymentForm.method = 'POST';
                 document.paymentForm.submit();
             }
           
        </script>
    </head>
    <body>
    <form name="paymentForm" runat="server" id="paymentForm">
    <div>
    <div>
    <div style="text-align:center;">
    <br />
    <center>
    <b>Please wait... Redirecting...</b>
    </center>                   
    </div>

    <ul style="display:none;">
        <li class="clearfix">
        <label width="125px;">
            Transaction Number:</label>
        <input type="text" id="merchantTxnId" runat="server" name="merchantTxnId" value="" />
        </li>
        <li class="clearfix">
        <label width="125px;">
            Order Amount:</label>
        <input type="text" id="orderAmount"  runat="server" name="orderAmount" value="" />
        </li>
        <li class="clearfix">
        <label width="125px;">
            Currency:</label>
        <input type="text" id="currency"  name="currency" value="INR" />
        </li>
        <li class="clearfix">
        <label width="125px;">
            First Name :</label>
        <input type="text" id="FName" name="firstName" value="" />
        </li>
        <li class="clearfix">
        <label width="125px;">
            Last Name :</label>
        <input type="text" id="LName" name="lastName" value="" />
        </li>
        <li class="clearfix">
        <label width="125px;">
            Email :</label>
        <input type="text" id="Email" name="email" value="" />
        </li>
        <p>
        Address Details</p>
        <li class="clearfix">
        <label width="125px;">
            Address :</label>
        <input type="text" id="Address" name="addressStreet1" value="" />
        </p>                               
        <li class="clearfix">
            <label width="125px;">
            City :</label>
            <input type="text" id="City" name="addressCity" value="" />
        </li>
        <li class="clearfix">
            <label width="125px;">
            Zip Code :</label>
            <input type="text" id="AddressZip" name="addressZip" value="" />
        </li>
        <li class="clearfix">
            <label width="125px;">
            State :</label>
            <input type="text" id="State"  name="addressState" value="" />
        </li>
                       
        <!-- <input type="hidden" class="text" name="addressCountry" value="INDIA" /> -->
                       
        <li class="clearfix">
            <label width="125px;">
            Mobile No:</label>
            <input type="text" id="Mobile"  name="phoneNumber" value="" />
        </li>
       
        <input type="hidden" name="paymentMode" value="NET_BANKING" />
        <input type="hidden" name="issuerCode" value="ISS008" />                               
          
        <%--<input type="hidden" id="ReturnUrl" name="returnUrl" runat="server" value="http://localhost:1463/sample-site/TestMotoResponse.aspx" />--%>
       
        <input type="text" id="returnUrl" name="returnUrl" value="" />
       
        <input type="hidden" id="secSignature" name="secSignature" value="" />
        <input type="hidden" name="reqtime" id="reqtime" value="<%=System.DateTime.Now.Ticks / 10000 %>" />
        <input id="btnSubmit" type="button" value="Make Payment" onclick="JavaScript:generateHMAC();"></input>
       
       
        <input type="hidden" id="hdnFname" runat="server"/>                               
        <input type="hidden" id="hdnLname" runat="server"/>                               
        <input type="hidden" id="hdnEmail" runat="server"/>                               
        <input type="hidden" id="hdnAddress" runat="server"/>                               
        <input type="hidden" id="hdnCity" runat="server"/>                               
        <input type="hidden" id="hdnZip" runat="server"/>                               
        <input type="hidden" id="hdnState" runat="server"/>                               
        <input type="hidden" id="hdnMobile" runat="server"/>    
        <input type="hidden" id="hdnReturnUrl" runat="server"/>                     
        <input type="hidden" id="hdnPaymentURL" value="123" runat="server"/>                     
       
        </ul>
        </div>
    </div>   
    </form>
    </body>
    </html>
  2. Payment Resquest Page (ASPX.CS)

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {  
            int pos = Request.Url.AbsoluteUri.LastIndexOf('/');
            string strURL = Request.Url.AbsoluteUri.Substring(0, pos + 1) + "PaymentResponseCITRUS.aspx";

            merchantTxnId.Value = YOUR TRANSACTION ID;
            orderAmount.Value = PAYMENT AMOUNT;
            hdnFname.Value = FIRST NAME OF CLIENT;
            hdnLname.Value = LAST NAME OF CLIENT;
            hdnEmail.Value = EMAIL OF CLIENT;
            hdnAddress.Value = ADDRESS OF CLIENT;
            hdnCity.Value = CITY OF CLIENT;
            hdnZip.Value = ZIPCODE OF CLIENT;
            hdnState.Value = STATE OF CLIENT;
            hdnMobile.Value = MOBILE OF CLIENT;
            hdnReturnUrl.Value = strURL; // RESPONSE URL

            //Payment URL
            hdnPaymentURL.Value = https://sandbox.citruspay.com/CLIENTID;
           
        }
        catch (Exception ex)
        {
           // LOG THE ERROR    
        }
    }
  3. hmac_signature.aspx

    <%@ Page Language="C#" AutoEventWireup="true" %>

    <%
    string key = CITRUS SECRET KEY (PROVIDED BY CITRUS)
    string merchantId = Request["merchantId"];
    string orderAmount = Request["orderAmount"];
    string merchantTxnId = Request["merchantTxnId"];
    string currency = Request["currency"];

    string data = merchantId + orderAmount + merchantTxnId + currency;
    try {
    %>
    <%= CitrusPay.MerchantKit.Infrastructure.CitrusPaySignatureRequestor.GenerateHMAC(data, key)%>
    <%
    }catch(Exception e){
           
    }
    %>
  4. Payment Response Page

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            String key = CITRUS SECRET KEY (PROVIDED BY CITRUS)
            String data = "";
            String txnId = Request["TxId"];
            String txnStatus = Request["TxStatus"];
            String amount = Request["amount"];
            String pgTxnId = Request["pgTxnNo"];
            String issuerRefNo = Request["issuerRefNo"];
            String authIdCode = Request["authIdCode"];
            String firstName = Request["firstName"];
            String lastName = Request["lastName"];
            String pgRespCode = Request["pgRespCode"];
            String zipCode = Request["addressZip"];
            String reqSignature = Request["signature"];

            String signature = "";
            bool flag = true;
            if (txnId != null)
            {
            data += txnId;
            }
            if (txnStatus != null)
            {
            data += txnStatus;
            }
            if (amount != null)
            {
            data += amount;
            }
            if (pgTxnId != null)
            {
            data += pgTxnId;
            }
            if (issuerRefNo != null)
            {
            data += issuerRefNo;
            }
            if (authIdCode != null)
            {
            data += authIdCode;
            }
            if (firstName != null)
            {
            data += firstName;
            }
            if (lastName != null)
            {
            data += lastName;
            }
            if (pgRespCode != null)
            {
            data += pgRespCode;
            }
            if (zipCode != null)
            {
            data += zipCode;
            }
            signature = CitrusPay.MerchantKit.Infrastructure.CitrusPaySignatureRequestor.GenerateHMAC(data, key);   

            if (reqSignature != null && !signature.Equals(reqSignature))
            {
            flag = false;
            }
            if (flag)
            {
            try
            {
                //Check the Status
                if (txnStatus.Trim().ToUpper() == "SUCCESS")
                {
                // UPDATE THE TRANSACTION STATUS IN DB
                //
                // CODE FOR UPDATE STATUS
                //

                // REDIRECT TO SUCCESS PAGE OR SHOW THE PAYMENT RESPONSE ON SAME PAGE
                }
                else
                {
                // PAYMENT IS NOT SUCCESSFUL
                // REDIRECT TO ERROR PAGE
                }
            }
            catch (Exception ex)
            {
                // ERROR OCCURED WHILE PAYMENT
                // REDIRECT TO ERROR PAGE
            }
            }
            else
            {
            // SIGNATURE VALIDATION IS WRONG
            // REDIRECT TO ERROR PAGE    
            }

        }
        catch (Exception ex)
        {
            // ERROR OCCURED WHILE PAYMENT
            // REDIRECT TO ERROR PAGE   
        }
    }

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

C# Convert Linq to Data Table


  1. Use the Following Method to Convert your Linq object to Datatable.
public static DataTable LinqToDataTable<T>(IEnumerable<T> varlist)
        {
            DataTable dt = null;

            if (varlist == null)
                return dt;
            else
                dt = new DataTable();

            PropertyInfo[] props = null;

            foreach (T row in varlist)
            {
                if (props == null)
                {
                    props = ((Type)row.GetType()).GetProperties();

                    foreach (PropertyInfo pi in props)
                    {
                        dt.Columns.Add(pi.Name, typeof(String));
                    }
                }

                DataRow dr = dt.NewRow();

                foreach (PropertyInfo pi in props)
                {
                    dr[pi.Name] = pi.GetValue(row, null) == null ? DBNull.Value : pi.GetValue(row, null);
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }