Click here to Skip to main content
15,904,935 members
Articles / Web Development / HTML

How to Implement eWay Client Side Encription in Windows Form Application

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
22 Aug 2020CPOL3 min read 2.7K   2  
My solution that can work with eWay payments from Windows Form Applications
This is an easy implementation to create Token and manage the payments for the CST STAFF at my work place.

In this post, I would like to share with all developers my solution that can work with eWay payments from Windows Form Applications.

I created this solution as an easy implementation to create the Token and manage the payments for the CST STAFF in a company where I am working now. I hope it will be helpful for you.

Integrate Web Page in Windows Form

If you already use eWay on your web page, you know it's very easy to use, because you can use all the JavaScripts and HTML Tags, but if you are using Windows Form Application to implement the payment or for creating a token, you cannot execute these tools directly.

So, the first step is to search how to use a Web Form like a Windows Form. You can use System.Windows.Form.WebBrowser and show a web page for making a transaction. But if you need some value from this web page, you cannot get it directly from the Windows Form.

If you create the web page, you can set an element for later query with a WebBrowser and get the value. But it is like 2 steps and is not my idea. I would like directly from my Windows Form to send the transaction and get the TransactionID or my CustomerToken and continue with my process on the Form.

If you like, do it in two steps, create the HTML file, on a web server or in your local folder, and execute myWebBrowser.Navigate([file route]); after inputting the data and clicking on Submit and your code showing the result on some HTML tag like span or div, you can get this value from your Windows Form with myWebBrowser.Document.GetElementById("[Element Id]").InnerText (for a span tag) or myWebBrowser.Document.GetElementById("[Element Id]").InnerHtml (for a div tag). So now, you have your data to continue the process.

My Transparent Solution

But for me, I don't like to use two steps, because it is not good that the user has a WebBrowser on the Windows Form. So I prefer abstract to the user and full manage from an independence process. And also, I can reuse again from other Windows Form. Of course, I need to use a WebBrowser Control, but there is no need to show on the Form. Because I already write how to do, directly I go to show the code and comment later.

C#
        private class EncriptData
        {
            private System.Windows.Forms.WebBrowser webBrowser = 
            new System.Windows.Forms.WebBrowser(); //create the web browser object
            //share variables
            private string number;
            private string cvn;
            private string number_encripted;
            private string cvn_encripted;
            //function to call from the Form
            public string[] EncriptCreditCard(string Number, string Cvn)
            {
                //create the webbrowser object     
                webBrowser.DocumentCompleted += 
                     new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler
                     (webBrowser_DocumentCompleted);
                webBrowser.ScriptErrorsSuppressed = true;
                this.number = Number;
                this.cvn = Cvn;
                string clave;
                //MERCHANT CLIENT SIDE ENCRYPTION KEY STRING
#if DEBUG
            clave = "[YOUR SANDBOX KEY]";
#else
            clave = "[YOUR LIVE KEY]";
#endif
                //create the page
                string html = @"
                            < html >
                                < head >            
                                    < script src=
                                    ""https://secure.ewaypayments.com/scripts/eCrypt.min.js"">
                                    < /script >                       
                                    < script >
                                        function EncriptData(param) {
                                            var params = param.split(';');
                                            var setValue = 
                                                document.getElementById('card_number');
                                            setValue.value = params[0];
                                            var setEncrypt = document.getElementById
                                                             ('card_number_encripted');
                                            setEncrypt.innerText = eCrypt.encryptValue
                                                                   (setValue.value); 
                                            setValue = document.getElementById('card_cvn');
                                            setValue.value = params[1];
                                            setEncrypt = document.getElementById
                                                         ('card_cvn_encripted');
                                            setEncrypt.innerText = eCrypt.encryptValue
                                                                   (setValue.value);   
                                        }
                                    < /script >
                                < /head >
                                < body >
                                    < form data-eway-encrypt-key=""" + clave + @""" >
                                        < label>Card Number
                                        < input type=""text"" id=""card_number"" 
                                          data-eway-encrypt-name=""card_number""/>
                                        < label>CVV
                                        < input type=""text"" id=""card_cvn"" 
                                          data-eway-encrypt-name=""card_cvn"" />
                                    < /form>     
                                    < span id=""card_number_encripted"">

                                    < span id=""card_cvn_encripted"">
                                < /body>
                            < /html>";
                archivos a = new archivos();                   //file management
                string web = a.guardaDato("eway.html", html);  //create a file HTML
                webBrowser.Navigate(web);                      //execute the page 
                                                               //on the web browser control
                while (webBrowser.ReadyState != 
                System.Windows.Forms.WebBrowserReadyState.Complete|| //wait until full load 
                                                                     //the page
                    (string.IsNullOrEmpty(this.number_encripted) && 
                     string.IsNullOrEmpty(this.cvn_encripted)))      //if is load but 
                                         // not execute the script wait until get the data    
                {
                    System.Windows.Forms.Application.DoEvents();
                }
                a.borrarArchivo(web);               //optional, delete the file after use
                a = null;
                return new string[] { this.number_encripted, this.cvn_encripted };
            }
            //get the values for send the transaction
            private void webBrowser_DocumentCompleted
            (object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
            {
                //repeat until can get the values
                int counter = 0;
                do
                {
                    if (counter < 100)
                    {
                        webBrowser.Document.InvokeScript("EncriptData", new string[] 
                         { this.number + ";" + this.cvn }); //execute the JavaScript
                                                            //get the values encrypted
                        this.number_encripted = webBrowser.Document.GetElementById
                                                ("card_number_encripted").InnerText;
                        this.cvn_encripted = webBrowser.Document.GetElementById
                                             ("card_cvn_encripted").InnerText;
                    }
                    else
                    {
                        //control the script can't execute
                        this.number_encripted = "FAIL";
                        this.cvn_encripted = "FAIL";
                    }
                    counter++;
                } while ((string.IsNullOrEmpty(this.number_encripted) && 
                          string.IsNullOrEmpty(this.cvn_encripted)));
            }
        }
  1. Create a WebBrowser Object.
  2. Declare some variables to share.
  3. Function to return the values encrypted, get the credit card number and credit CVN, because this is the data we need to encrypt.
  4. Inside the function, create the EventHandler to know when the web document is complete and can execute the script to encrypt the data.
  5. Set the values to share with the Event.
  6. Create HTML file.
  7. In the web browser object, navigate to the file.
  8. Here, we need to wait until the page is already loaded.
  9. In the Event Function when the page is loaded, call the script to encrypt the data.
  10. Set the values to share with the encrypted data.
  11. Delete the temp file.

Controls To Do

At point 8 is where we need control if the share variables don't have a value because the script is not complete, or because the page is not full charge. This can be when you execute the page from a live web server, don't create the local file, or because the script failed or didn't return a value.

Also in the Event need control the script really execute after charge the page. For that, we need to repeat the script until get some data. To control unlimited loops, because the page is not charged, for example, I control max 100 loops and set the share variable with "FAIL" for it can go out of all the loops.

Get the Customer Token

This is an example to use this function to setup a CustomerTokenID that can make transactions later with Direct Connection.

C#
/// Get new Token from the customer
///
/// Customer data object
///
public MyTransaction SetToken(MyCustomer myCustomer)
{
MyTransaction myTransaction = new MyTransaction();

string APIKEY;
string PASSWORD;
string ENDPOINT;

try
{
//using the function to encript a data
EncriptData e = new EncriptData();
string[] encriptCreditCard = e.EncriptCreditCard
(myCustomer.CardDetails.Number, myCustomer.CardDetails.CVN);
e = null;

IRapidClient eway = RapidClientFactory.NewRapidClient(APIKEY, PASSWORD, ENDPOINT);
eway.SetVersion(40);

//without token need insert all data for the customer
//create a customer info
Customer customer;
customer = new Customer()
{
Reference = myCustomer.Reference,
FirstName = myCustomer.FirstName,
LastName = myCustomer.LastName,
CompanyName = myCustomer.CompanyName,
Phone = myCustomer.Phone,
Mobile = myCustomer.Mobile,
Email = myCustomer.Email,
Address = new Address()
{
Street1 = myCustomer.Street,
City = myCustomer.City,
State = myCustomer.Street,
PostalCode = myCustomer.PostalCode,
Country = myCustomer.Country
},
CardDetails = new CardDetails()
{
Name = myCustomer.CardDetails.Name,
Number = encriptCreditCard[0],
ExpiryMonth = myCustomer.CardDetails.ExpiryMonth,
ExpiryYear = myCustomer.CardDetails.ExpiryYear,
CVN = encriptCreditCard[1]
}
};
try
{
CreateCustomerResponse getToken = eway.Create(PaymentMethod.Direct, customer);

if (getToken.Errors == null) {
myTransaction.token = getToken.Customer.TokenCustomerID;
myTransaction.result = true;
myTransaction.error = string.Empty;
}
else
{
List errores = getToken.Errors;
myTransaction.error = string.Empty;
myTransaction.token = string.Empty;
myTransaction.result = false;
foreach (string errorCode in errores)
{
myTransaction.error += errorCode + ": " + eWayErrorCode(errorCode) + Environment.NewLine;
}
}
}
catch (Exception ex)
{
myTransaction.token = string.Empty;
myTransaction.result = false;
myTransaction.error = ex.ToString();
}
}
catch (Exception ex)
{
myTransaction.token = string.Empty;
myTransaction.result = false;
myTransaction.error = ex.ToString();
}
return myTransaction;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DrUalcman
Philippines Philippines
I am a programmer with skill in c#, VB, MVC, .NET CORE, JAVASCRPT, HTML, ASP, CSS, windows forms, windows app.

I like help the dev community with my experiencies, and sharing my code to everybody.

Comments and Discussions

 
-- There are no messages in this forum --