Wednesday 6 July 2016

How to integrate citrus payment gateway in ASP.NET


How to integrate citrus payment gateway in ASP.NET



Description:
  • generally online payment gateway flow as follows.
    • When customers are ready to pay, they enter their payment information and click the payment button on your website.
    • The payment gateway encrypts data and securely sends it through the payment processing network.
    • The transaction is reviewed for authorization or decline, and the results are sent back through the Payflow payment gateway.
    • Your customer receives a confirmation receipt and you fulfill the order.
    • Once the transaction is processed, funds are transferred from the customer’s bank account to your merchant bank account.



So now, how to integrate onsite citrus payment integration in asp.net with c#.
Pre requisites : 
    • Citrus Account
    • Vanity Url
    • ​Security creadentials 
​Login to sandbox (in case of Testing) or production (in case of Live) using the user ID and password received from Citruspay.

How to Get Vanity URL :

 After login to your citrus account and go to checkout page setting tab in right panel.


How to Get Security Credentials :




Payment Request Parameters : 

  Before go further please make sure your payment paramters as per below discription.



1. Create a sample request page to post a transaction request to citrus. (Refer PaymentRedirect.aspx Page.)
2. Create a sample response page to receive the response on your website.(Refer PaymentRespose.aspx page)

Once user click on Make payment button redirect them to ​PaymentRedirect.aspx with your session variables.

Create a sample request page to post a transaction request to citrus.
Page: PaymentRedirect.aspx

PaymentRedirect.aspx:
​​
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PaymentRedirect.aspx.cs"
    Inherits="PaymentRedirect" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Payment Redirect</title>   
    <script type="text/javascript">
        function myfunc() {
            var frm = document.all("formpayment");
            frm.submit();
        }
        window.onload = myfunc;
    </script>
</head>
<body>   
    <table class="divWaiting" width="100%">
        <tr>
            <td height="200px">
                 
            </td>
        </tr>
        <tr>
            <td align="center">
                <img alt="Processing" src="Images/updateprogress.gif" />
            </td>
        </tr>
        <tr>
            <td align="center"
                   style="color: black; font-family: Calibri; font-size: 22px;">
                Please wait while we are redirect you to payment gateway for precessing...
                <br />
                Please do not press <strong>Stop</strong>,
                   <strong>Back</strong> or <strong>Refresh</strong>
                button or <strong>Close</strong> this window."
            </td>
        </tr>
    </table>
    <form id="formpayment" method="post" action="<%=formPostUrl%>">
    <input type="hidden" id="merchantTxnId" name="merchantTxnId" value="<%=merchantTxnId%>" />
    <input type="hidden" id="orderAmount" name="orderAmount" value="<%=orderAmount%>" />
    <input type="hidden" id="currency" name="currency" value="<%=currency%>" />
    <input type="hidden" name="returnUrl" value="<%=returnUrl %>" />
    <input type="hidden" id="notifyUrl" name="notifyUrl" value="<%=notifyUrl%>" />
    <input type="hidden" id="secSignature" name="secSignature" value="<%=securitySignature%>" />
    </form>
</body>
</html>


​​​

PaymentRedirect.aspx.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Net;
using System.Text;
using System.IO;


public partial class PaymentRedirect : System.Web.UI.Page
{
    LogErrorToLogFile logFile = new LogErrorToLogFile();

    protected string formPostUrl = "";
    protected string currency = "";
    protected string returnUrl = "";
    protected string notifyUrl = "";

    protected string merchantTxnId = "";
    protected string secret_key = "";
    protected string vanityUrl = "";
    protected string orderAmount = "0.00";
    protected string securitySignature = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
       //Get All Payment Related Details from Database server. or set details in
         web.config file.
            DataTable dtPaymentInformation = null;
            DevCommon.Select("SPSelectApplicationPaymentDetailByApplicationFormId",
        ref dtPaymentInformation, Convert.ToInt64(Session["ApplicationFormId"]));
            if (dtPaymentInformation != null && dtPaymentInformation.Rows.Count > 0)
            {
    
            currency = Convert.ToString(dtPaymentInformation.Rows[0]["currency"]);
            returnUrl = Convert.ToString(dtPaymentInformation.Rows[0]["returnUrl"]);
            notifyUrl = Convert.ToString(dtPaymentInformation.Rows[0]["notifyUrl"]);
           // Will provide unique for every request to citrus.    
            merchantTxnId = Convert.ToString(Session["TransactionReferenceNo"]); 
           
            secret_key = Convert.ToString(dtPaymentInformation.Rows[0]["secret_key"]);
            vanityUrl = Convert.ToString(dtPaymentInformation.Rows[0]["vanityUrl"]);
            formPostUrl = "https://www.citruspay.com/" + vanityUrl;
                
            orderAmount = Convert.ToString(dtPaymentInformation.Rows[0]["AdminCharges"]);
       // For testing we have set order amount 1 rupees.
            orderAmount = "1";
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
            string data = vanityUrl + orderAmount + merchantTxnId + currency;

            System.Security.Cryptography.HMACSHA1 myhmacsha1 = new
       System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));
            System.IO.MemoryStream stream = new
       System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
            securitySignature =
       BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();

        }
        catch (Exception ex)
        {
            logFile.LogError(ex);
            return;
        }
    }
}
​​

Create a sample response page to receive the response on your website.

Create Page PaymentRespose.aspx and paste below code in .cs file.

PaymentRespose.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;

public partial class PaymentResponse : System.Web.UI.Page
{
    LogErrorToLogFile logFile = new LogErrorToLogFile();
    string txnId = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string data = "";
            txnId = Request["TxId"];
            string TxRefNo = Request["TxRefNo"];
            string txnStatus = Request["TxStatus"];
            string amount = Request["amount"];
            string TxMsg = Request["TxMsg"];           
            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 resSignature = Request["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;
            }
      
            // Get a secret key from web.config or database server.
            //string secret_key = ConfigurationManager.AppSettings["secret_key"].ToString();

            DataTable dtPaymentInfo = null;
            string secret_key = "";
            DevCommon.Select("SPSelectApplicationPaymentDetailByTxId",
       ref dtPaymentInfo, Convert.ToString(txnId));
            if (dtPaymentInfo != null && dtPaymentInfo.Rows.Count > 0)
            {
                secret_key = Convert.ToString(dtPaymentInfo.Rows[0]["secret_key"]);
            }
            System.Security.Cryptography.HMACSHA1 myhmacsha1 = new
       System.Security.Cryptography.HMACSHA1(
            System.Text.Encoding.ASCII.GetBytes(secret_key));
            System.IO.MemoryStream stream = new
            System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes(data));
            string signature =
       BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();

            if (resSignature != null && !signature.Equals(resSignature))
            {
                flag = false;
            }

            if (flag)
            {
                DataTable datatable = null;
                object[] objPara = new object[14];
                objPara[0] = Convert.ToInt32(Session["ApplicationFormId"]);
                objPara[1] = txnId;
                objPara[2] = TxRefNo;
                objPara[3] = txnStatus;
                objPara[4] = amount;
                objPara[5] = TxMsg;
                objPara[6] = pgTxnId;
                objPara[7] = issuerRefNo;
                objPara[8] = authIdCode;
                objPara[9] = firstName;
                objPara[10] = lastName;
                objPara[11] = pgRespCode;
                objPara[12] = zipCode;
                objPara[13] = signature;
           

                   // Update transaction status in database and make sure your database
                   //amount and tansaction amount both are same while update transaction
                //status(eg. SUCCESS).
                DevCommon.InsertUpdate("SPUpdatePaymentDetails", ref datatable, objPara);
                if (datatable != null && datatable.Rows.Count > 0 &&
                   Convert.ToInt64(datatable.Rows[0][0]) > 0)
                {
                      // after successful update redirect to payment receipt for payment details.
                   //create payment reciept page as your requirement.
                    Response.Redirect("PaymentReceipt.aspx?txnId=" +
                       EncryptDecrypt.Encrypt(Convert.ToString(txnId), "P@ssw0rd"),false);
                }
            }
            else
            {
                Response.Redirect("default.aspx");
            }
        }
        catch (Exception ex)
        {
            // mail to Admin if fail to update status in database and redirect
       // to another page.           
            Response.Redirect("default.aspx");
        }

    }
}





3 comments:

  1. Hi,
    It Shows an Error
    DevCommon Like the name 'DevCommon' does not exist in current context.

    ReplyDelete