Skip to main content

Integrating MIGS eGate Payment gateway using C# for Oz businesses (Server-Hosted Payment method)

If you ever wanted to include the eGate payment gateway in your ASP.Net site and want to save yourself the time in creating the class, here’s how to do it.
First things first you will need a merchant account with ANZ who will give you the following
·         Merchant Account
·         User name
·         password
The details could be downloaded from the ANZ web site
I am doing this for an Aus base client thus the process might be different to your own country. Please check with the issuing bank for details.

Have a read of the Merchant Admin guide. Login to the merchant account and create an operator ID, Login as the operator and obtain the access code. I will not going to the details as this is all documented in the admin guide.

What you will need for the implementation would be
vpc_AccessCode
vpc_Merchan
MIGS gateway URL:https://migs.mastercard.com.au/vpcdps


The site has numerous examples of the PHP, HTTP post and Asp examples. The class was based on the provided implementation.


Include the following in the web config file.
<configuration>
       <appSettings>

  <add key="vpc_version" value="1"/>
  <add key="vpc_command" value="pay"/>
  <add key="vpc_AccessCode" value="AccesscodeforYourAccount/>
  <add key="vpc_Merchant" value="MerchantLoginID"/>
  
   <add key="proxyIP" value="YourProxyServer:Port"/>
   <add key="proxyUser" value="UserName"/>
   <add key="proxyPassword" value="Password"/>
   <add key="proxyDomain" value="yourDomian"/>


Create a class called eGate.cs
Add the following code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Net;
/// <summary>
/// ANZ eGATE connection claas
/// Author: Krishang
/// Remark: This class takes in all the parameters and does a post and a return and the details are passed via the interface
/// All other details to be handled outside this class.
/// eGate payment processing class.
/// </summary>
public  class eGate
{
    public string vpc_Amount;
    public string vpc_BatchNo;
    public string vpc_Command;

    public string vpc_CardNum;
    public string vpc_OrderInfo;
    public string vpc_ReceiptNo;

    public string vpc_AuthorizeId;
    public string vpc_MerchTxnRef;
    public string vpc_TransactionNo;
    public string vpc_AcqResponseCode;

    public string vpc_CardExp;
    public string vpc_CardSecurityCode;
    public string vpc_Version;
    private string virtualPaymentClientURL;
    private string ProxyIP;
    private string ProxyUser;
    private string ProxyPassword;
    private string ProxyDoamin;

    public string vpc_Merchant;
    public string vpc_AccessCode;
    public string vpc_TicketNo;



      // Get the standard receipt data from the parsed response
    public string responseAmount;
    public string responseBatchNo;
    public string responseCommand;
    public string responseVersion;
    public string responseCardType;
    public string responseOrderInfo;
    public string responseReceiptNo;
    public string responseMerchantID;
    public string responseAuthorizeID;
    public string responseMerchTxnRef;
    public string responseTransactionNo;
    public string responseAcqResponseCode;
    public string responseCode;
    public string ResponseCodeDesc;
    public string AvsResponseCodeDesc;
    public string AvsResponseCode;
    public string CscResponseCodeDesc;
    public string CscResponseCode;

       private string message = ""

       public  eGate(string pUser,string pPwd,string pDomain, string pIP )
       {
              //
              // TODO: Add constructor logic here
              //
        virtualPaymentClientURL = "https://migs.mastercard.com.au/vpcdps";
        ProxyUser = pUser;
        ProxyPassword = pPwd;
        ProxyDoamin = pDomain;
        ProxyIP = pIP;
       }

  
   
    public  void MakePayment()
    {
       string postData;
       System.Collections.Hashtable responseParameters;

        try
        {
      
           postData = System.Web.HttpUtility.UrlEncode("vpc_Version") + "=" + HttpUtility.UrlEncode(vpc_Version) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_Command") + "=" + HttpUtility.UrlEncode(vpc_Command) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_AccessCode") + "=" + HttpUtility.UrlEncode(vpc_AccessCode) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_MerchTxnRef") + "=" + HttpUtility.UrlEncode(vpc_MerchTxnRef) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_MerchTxnRef") + "=" + HttpUtility.UrlEncode(vpc_MerchTxnRef) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_Merchant") + "=" + HttpUtility.UrlEncode(vpc_Merchant) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_OrderInfo") + "=" + HttpUtility.UrlEncode(vpc_OrderInfo) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_Amount") + "=" + HttpUtility.UrlEncode(vpc_Amount) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_CardNum") + "=" + HttpUtility.UrlEncode(vpc_CardNum) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_CardExp") + "=" + HttpUtility.UrlEncode(vpc_CardExp) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_CardSecurityCode") + "=" + HttpUtility.UrlEncode(vpc_CardSecurityCode) + "&" +
               System.Web.HttpUtility.UrlEncode("vpc_TicketNo") + "=" + HttpUtility.UrlEncode(vpc_TicketNo);

            System.Net.WebClient webClient = new System.Net.WebClient();



            if (ProxyIP != "")
            {
                ICredentials Cred = new NetworkCredential(ProxyUser,
                                                          ProxyPassword, ProxyDoamin);

                WebProxy wProxy = new WebProxy(ProxyIP, true, null, Cred);

                webClient.Proxy = wProxy;

            }

            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
       byte[] response = webClient.UploadData(virtualPaymentClientURL, "POST", Encoding.ASCII.GetBytes(postData));

       // Convert the response to a string from a byte array and parse it to extract
       // the data using the splitResponse function. Store results in a hashtable.
        string responseData = System.Text.Encoding.ASCII.GetString(response, 0, response.Length);
        responseParameters = splitResponse(responseData);

        // Get the standard receipt data from the parsed response
        responseAmount = responseParameters.ContainsKey("vpc_Amount") ? responseParameters["vpc_Amount"].ToString() : "Unknown";
        responseBatchNo = responseParameters.ContainsKey("vpc_BatchNo") ? responseParameters["vpc_BatchNo"].ToString() : "Unknown";
        responseCommand = responseParameters.ContainsKey("vpc_Command") ? responseParameters["vpc_Command"].ToString() : "Unknown";
        responseVersion = responseParameters.ContainsKey("vpc_Version") ? responseParameters["vpc_Version"].ToString() : "Unknown";
        responseCardType = responseParameters.ContainsKey("vpc_Card") ? responseParameters["vpc_Card"].ToString() : "Unknown";
        responseOrderInfo = responseParameters.ContainsKey("vpc_OrderInfo") ? responseParameters["vpc_OrderInfo"].ToString() : "Unknown";
        responseReceiptNo = responseParameters.ContainsKey("vpc_ReceiptNo") ? responseParameters["vpc_ReceiptNo"].ToString() : "Unknown";
        responseMerchantID = responseParameters.ContainsKey("vpc_Merchant") ? responseParameters["vpc_Merchant"].ToString() : "Unknown";
        responseAuthorizeID = responseParameters.ContainsKey("vpc_AuthorizeId") ? responseParameters["vpc_AuthorizeId"].ToString() : "Unknown";
        responseMerchTxnRef = responseParameters.ContainsKey("vpc_MerchTxnRef") ? responseParameters["vpc_MerchTxnRef"].ToString() : "Unknown";
        responseTransactionNo = responseParameters.ContainsKey("vpc_TransactionNo") ? responseParameters["vpc_TransactionNo"].ToString() : "Unknown";
        responseAcqResponseCode = responseParameters.ContainsKey("vpc_AcqResponseCode") ? responseParameters["vpc_AcqResponseCode"].ToString() : "Unknown";

        responseCode = responseParameters.ContainsKey("vpc_TxnResponseCode") ? responseParameters["vpc_TxnResponseCode"].ToString() : "Unknown";
        ResponseCodeDesc = getResponseDescription(responseCode);


        string avsResultCode = responseParameters.ContainsKey("vpc_AVSResultCode") ? responseParameters["vpc_AVSResultCode"].ToString() : "Unknown";
        AvsResponseCodeDesc = getAVSDescription(avsResultCode);
        AvsResponseCode = avsResultCode;

        string cscResultCode = responseParameters.ContainsKey("vpc_CSCResultCode") ? responseParameters["vpc_CSCResultCode"].ToString() : "Unknown";
        CscResponseCodeDesc = getCSCDescription(cscResultCode);
        CscResponseCode = cscResultCode;

        if (message.Length == 0)
        {
            message = responseParameters.ContainsKey("vpc_Message") ? responseParameters["vpc_Message"].ToString() : "Unknown";
        }


       
        }
       catch (Exception ex)
        {
            message = "(51) Exception encountered. " + ex.Message;
          //  ResponseCodeDesc = message;

        }
  

       
  



    }

    private System.Collections.Hashtable splitResponse(string rawData)
    {
        /*
         <summary>Parses a HTTP POST to extract the parmaters from the POST data</summary>
         <param name="rawData">The raw data from the body of a HTTP POST.</param>
         <returns>A Hashtable containing the parameters returned in the body of a HTTP POST.</returns>

         <remarks>
         <para>
         This function parses the content of the VPC response to extract the
         individual parameter names and values. These names and values are then
         returned as a Hashtable.
         </para>

         <para>
         The content returned by the VPC is a HTTP POST, so the content will
         be in the format <c>parameter1=value&parameter2=value&parameter3=value</c>,
         i.e. key/value pairs separated by ampersands "&".
         </para>
         </remarks>
         */

        System.Collections.Hashtable responseData = new System.Collections.Hashtable();
        try
        {
            // Check if there was a response containing parameters
            if (rawData.IndexOf("=") > 0)
            {
                // Extract the key/value pairs for each parameter
                foreach (string pair in rawData.Split('&'))
                {
                    int equalsIndex = pair.IndexOf("=");
                    if (equalsIndex > 1 && pair.Length > equalsIndex)
                    {
                        string paramKey = System.Web.HttpUtility.UrlDecode(pair.Substring(0, equalsIndex));
                        string paramValue = System.Web.HttpUtility.UrlDecode(pair.Substring(equalsIndex + 1));
                        responseData.Add(paramKey, paramValue);
                    }
                }
            }
            else
            {
                // There were no parameters so create an error
                responseData.Add("vpc_Message", "The data contained in the response was not a valid receipt.<br/>\nThe data was: <pre>" + rawData + "</pre><br/>\n");
            }
            return responseData;
        }
        catch (Exception ex)
        {
            // There was an exception so create an error
            responseData.Add("vpc_Message", "\nThe was an exception parsing the response data.<br/>\nThe data was: <pre>" + rawData + "</pre><br/>\n<br/>\nException: " + ex.ToString() + "<br/>\n");
            return responseData;
        }
    }

    // _________________________________________________________________________

    private string getResponseDescription(string vResponseCode)
    {
        /*
         <summary>Maps the vpc_TxnResponseCode to a relevant description</summary>
         <param name="vResponseCode">The vpc_TxnResponseCode returned by the transaction.</param>
         <returns>The corresponding description for the vpc_TxnResponseCode.</returns>
         */
        string result = "Unknown";

        if (vResponseCode.Length > 0)
        {
            switch (vResponseCode)
            {
                case "0": result = "Transaction Successful"; break;
                case "1": result = "Transaction Declined"; break;
                case "2": result = "Bank Declined Transaction"; break;
                case "3": result = "No Reply from Bank"; break;
                case "4": result = "Expired Card"; break;
                case "5": result = "Insufficient Funds"; break;
                case "6": result = "Error Communicating with Bank"; break;
                case "7": result = "Payment Server detected an error"; break;
                case "8": result = "Transaction Type Not Supported"; break;
                case "9": result = "Bank declined transaction (Do not contact Bank)"; break;
                case "A": result = "Transaction Aborted"; break;
                case "B": result = "Transaction Declined - Contact the Bank"; break;
                case "C": result = "Transaction Cancelled"; break;
                case "D": result = "Deferred transaction has been received and is awaiting processing"; break;
                case "F": result = "3-D Secure Authentication failed"; break;
                case "I": result = "Card Security Code verification failed"; break;
                case "L": result = "Shopping Transaction Locked (Please try the transaction again later)"; break;
                case "N": result = "Cardholder is not enrolled in Authentication scheme"; break;
                case "P": result = "Transaction has been received by the Payment Adaptor and is being processed"; break;
                case "R": result = "Transaction was not processed - Reached limit of retry attempts allowed"; break;
                case "S": result = "Duplicate SessionID"; break;
                case "T": result = "Address Verification Failed"; break;
                case "U": result = "Card Security Code Failed"; break;
                case "V": result = "Address Verification and Card Security Code Failed"; break;
                default: result = "Unable to be determined"; break;
            }
        }
        return result;
    }


    // _________________________________________________________________________

    private string getAVSDescription(string vAVSResultCode)
    {
        /*
         <summary>Maps the vpc_AVSResultCode to a relevant description</summary>
         <param name="vAVSResultCode">The vpc_AVSResultCode returned by the transaction.</param>
         <returns>The corresponding description for the vpc_AVSResultCode.</returns>
         */
        string result = "Unknown";

        if (vAVSResultCode.Length > 0)
        {
            if (vAVSResultCode.Equals("Unsupported"))
            {
                result = "AVS not supported or there was no AVS data provided";
            }
            else
            {
                switch (vAVSResultCode)
                {
                    case "X": result = "Exact match - address and 9 digit ZIP/postal code"; break;
                    case "Y": result = "Exact match - address and 5 digit ZIP/postal code"; break;
                    case "S": result = "Service not supported or address not verified (international transaction)"; break;
                    case "G": result = "Issuer does not participate in AVS (international transaction)"; break;
                    case "A": result = "Address match only"; break;
                    case "W": result = "9 digit ZIP/postal code matched, Address not Matched"; break;
                    case "Z": result = "5 digit ZIP/postal code matched, Address not Matched"; break;
                    case "R": result = "Issuer system is unavailable"; break;
                    case "U": result = "Address unavailable or not verified"; break;
                    case "E": result = "Address and ZIP/postal code not provided"; break;
                    case "N": result = "Address and ZIP/postal code not matched"; break;
                    case "0": result = "AVS not requested"; break;
                    default: result = "Unable to be determined"; break;
                }
            }
        }
        return result;
    }

    //______________________________________________________________________________

    private string getCSCDescription(string vCSCResultCode)
    {
        /*
         <summary>Maps the vpc_CSCResultCode to a relevant description</summary>
         <param name="vCSCResultCode">The vpc_CSCResultCode returned by the transaction.</param>
         <returns>The corresponding description for the vpc_CSCResultCode.</returns>
         */
        string result = "Unknown";
        if (vCSCResultCode.Length > 0)
        {
            if (vCSCResultCode.Equals("Unsupported"))
            {
                result = "CSC not supported or there was no CSC data provided";
            }
            else
            {

                switch (vCSCResultCode)
                {
                    case "M": result = "Exact code match"; break;
                    case "S": result = "Merchant has indicated that CSC is not present on the card (MOTO situation)"; break;
                    case "P": result = "Code not processed"; break;
                    case "U": result = "Card issuer is not registered and/or certified"; break;
                    case "N": result = "Code invalid or not matched"; break;
                    default: result = "Unable to be determined"; break;
                }
            }
        }
        return result;
    }


 


    //public void Responce(System.Collections.Hashtable responseParameters)
    //{
    
    // // Get the standard receipt data from the parsed response
    //    responseAmount          = responseParameters.ContainsKey("vpc_Amount")?responseParameters["vpc_Amount"].ToString():"Unknown";
    //    responseBatchNo         = responseParameters.ContainsKey("vpc_BatchNo")?responseParameters["vpc_BatchNo"].ToString():"Unknown";
    //    responseCommand         = responseParameters.ContainsKey("vpc_Command")?responseParameters["vpc_Command"].ToString():"Unknown";
    //    responseVersion         = responseParameters.ContainsKey("vpc_Version")?responseParameters["vpc_Version"].ToString():"Unknown";
    //    responseCardType        = responseParameters.ContainsKey("vpc_Card")?responseParameters["vpc_Card"].ToString():"Unknown";
    //    responseOrderInfo       = responseParameters.ContainsKey("vpc_OrderInfo")?responseParameters["vpc_OrderInfo"].ToString():"Unknown";
    //    responseReceiptNo       = responseParameters.ContainsKey("vpc_ReceiptNo")?responseParameters["vpc_ReceiptNo"].ToString():"Unknown";
    //    responseMerchantID      = responseParameters.ContainsKey("vpc_Merchant")?responseParameters["vpc_Merchant"].ToString():"Unknown";
    //    responseAuthorizeID     = responseParameters.ContainsKey("vpc_AuthorizeId")?responseParameters["vpc_AuthorizeId"].ToString():"Unknown";
    //    responseMerchTxnRef     = responseParameters.ContainsKey("vpc_MerchTxnRef")?responseParameters["vpc_MerchTxnRef"].ToString():"Unknown";
    //    responseTransactionNo   = responseParameters.ContainsKey("vpc_TransactionNo")?responseParameters["vpc_TransactionNo"].ToString():"Unknown";
    //    responseAcqResponseCode = responseParameters.ContainsKey("vpc_AcqResponseCode")?responseParameters["vpc_AcqResponseCode"].ToString():"Unknown";

    //    responseCode = responseParameters.ContainsKey("vpc_TxnResponseCode")?responseParameters["vpc_TxnResponseCode"].ToString():"Unknown";
    //    ResponseCodeDesc = getResponseDescription(responseCode);
       

    //    string avsResultCode = responseParameters.ContainsKey("vpc_AVSResultCode")?responseParameters["vpc_AVSResultCode"].ToString():"Unknown";
    //    AvsResponseCodeDesc = getAVSDescription(avsResultCode);
    //    AvsResponseCode = avsResultCode;

    //    string cscResultCode = responseParameters.ContainsKey("vpc_CSCResultCode")?responseParameters["vpc_CSCResultCode"].ToString():"Unknown";
    //    CscResponseCodeDesc = getCSCDescription(cscResultCode);
    //    CscResponseCode = cscResultCode;

    //    if (message.Length == 0)
    //    {
    //        message = responseParameters.ContainsKey("vpc_Message")?responseParameters["vpc_Message"].ToString():"Unknown";
    //    }
       
    //}
 
}


NOW implement the class in your payment page.
I have created a Function with the details.

            eGate MyANZ = new eGate(ConfigurationManager.AppSettings["ProxyUser"].ToString(),
                                    ConfigurationManager.AppSettings["ProxyPassword"].ToString(),
                                    ConfigurationManager.AppSettings["ProxyDomain"].ToString(),
                                    ConfigurationManager.AppSettings["ProxyIP"].ToString()
                );

            MyANZ.vpc_Version = ConfigurationManager.AppSettings["vpc_Version"].ToString();
            MyANZ.vpc_Command = ConfigurationManager.AppSettings["vpc_Command"].ToString();
            MyANZ.vpc_AccessCode = ConfigurationManager.AppSettings["vpc_AccessCode"].ToString();
            MyANZ.vpc_Merchant = ConfigurationManager.AppSettings["vpc_Merchant"].ToString();

            MyANZ.vpc_MerchTxnRef =   OrderInfo.Substring(0, OrderInfo.Length< 133?OrderInfo.Length:133);
            MyANZ.vpc_OrderInfo = OrderInfo.Substring(0, OrderInfo.Length < 133 ? OrderInfo.Length : 133);
            MyANZ.vpc_Amount = this.OrderAmount.ToString("C").Replace(".", "").Replace("$","");
            MyANZ.vpc_CardNum = txtCC.Text.Trim();
            MyANZ.vpc_CardExp = ddlCCYear.SelectedValue + ddlCCMonth.SelectedValue;
            MyANZ.vpc_CardSecurityCode = txtSecurity.Text;

            MyANZ.MakePayment();

            if (MyANZ.responseCode== "0")
            {
//                   Update your database tables with the values write some code…
                                    );
            }
            else
                // Error code do something
 MyANZ.ResponseCodeDesc;
                           
                        
           
              }


Comments

  1. do we actual needed to proxyIP or proxyserver for this one ?

    ReplyDelete
  2. This depends if you have a proxy. Leave this blank otherwise.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment

Popular posts from this blog

Troubleshooting Database Mail: General steps

SQL Server 2008 R2 Other Versions SQL Server "Denali" SQL Server 2008 SQL Server 2005 Troubleshooting Database Mail involves checking the following general areas of the Database Mail system. These procedures are presented in a logical order, but can be evaluated in any order. To determine if Database Mail is enabled In SQL Server Management Studio, connect to an instance of SQL Server by using a query editor window, and then execute the following code: Copy sp_configure 'show advanced', 1; GO RECONFIGURE; GO sp_configure; GO In the results pane, confirm that the run_value for Database Mail XPs is set to 1 . If the run_value is not 1 , Database Mail is not enabled. Database Mail is not automatically enabled to reduce the number of features available for attack by a malicious user. For more information, see Understanding Surface Area Configuration . If you decide that it is appropriate to enable Database Mail, execute the fo...

Using SSRS web services to render a report as a PDF

I have been looking around the net for some decent code which would explain how I could render a report, using SSRS 2008 web services as a PDF.   The need was to extract reports sitting on a SSRS 2008 server sitting on a NT domain on a trusted network, whereas my web server was sitting in a DMZ. Where the only communication allowed by the network admin was port 80. To do this you will need to use the SSRS2008   ReportExecution2005.asmx web service. This could be accesses using the following URL assuming your SSRS server was installed using the default settings. http://YourServerIP/reportserver/reportexecution2005.asmx?wsdl 1.        Create a user on your AD domain with the least amount of privileges (say ReportUser) 2.        Give this account browse access on the reporting server for the desired reports. 3.        To get this working in visual studio 2010 (I am using t...