Friday, 26 August 2016

Robobank Omnikassa Payment Processing with ASP.NET MVC5 C#

Many websites are using RoboBank Omnikassa Payment Processing. It is very easy to use with your ASP.NET MVC application. Simply follow the following steps and get ready.

Download Code from Here

Step 1:
Create a controller in your web application "RobobankController"
and setup the following constants inside the class

  // Test  
     private const String PostUrl = @"https://payment-webinit.simu.omnikassa.rabobank.nl/paymentServlet";  
     // Production  
     //private const String PostUrl = https://payment-webinit.omnikassa.rabobank.nl/paymentServlet  
     private const String SecurityKey = @"002020000000001_KEY1";  
     private const String MerchantId = @"002020000000001";  
     private const String SecurityKeyVersion = "1";  
     private const String CurrencyCode = "978"; // Euro  
     private const String LanguageCode = "EN"; // Euro    

Step 2:
Create a Modelview inside models "RobobankViewModel"


 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 namespace RoboBankOmniKassa.Models  
 {  
   public class RobobankViewModel  
   {  
     public string OrderID { get; set; }  
     public double Amount { get; set; }  
     public string Response { get; set; }  
   }  
 }  

Step 3:
Create Pay Action

// GET: Robobank
        public ActionResult Pay()
        {
            RobobankViewModel VM = new RobobankViewModel();
            VM.Amount = 500;
            VM.OrderID = DateTime.Now.Ticks.ToString();

            return View(VM);
        }

Step 4: 
Create View for above action.

@model RoboBankOmniKassa.Models.RobobankViewModel

@{
    ViewBag.Title = "Pay";
}

Pay

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() @Html.LabelFor(item => item.Amount) @Html.EditorFor(item => item.Amount) @Html.LabelFor(item => item.OrderID) @Html.EditorFor(item => item.OrderID) < input class="btn btn-default csg_buttonBlue" id="Savedata" type="submit" value="Save" /> }

Step 5:
Handle post request of above view (Create Post Action for Pay)



        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Pay(RobobankViewModel model)
        {
            if(ModelState.IsValid)
            {
                string data = String.Format("merchantId={0}", MerchantId)
              + String.Format("|orderId={0}", model.OrderID)
              + String.Format("|amount={0}", model.Amount)
              + String.Format("|customerLanguage={0}", LanguageCode)
              + String.Format("|keyVersion={0}", SecurityKeyVersion)
              + String.Format("|currencyCode={0}", CurrencyCode)
                    // + String.Format("|PaymentMeanBrandList={0}", "IDEAL")
              + String.Format("|normalReturnUrl={0}", "http://www."+ Request.Url.Host + "/Robobank/RedirectResponse")
              + String.Format("|automaticResponseUrl={0}", "http://www." + Request.Url.Host + "/Robobank/RedirectResponse")
              + String.Format("|transactionReference={0}", model.OrderID + "x" + DateTime.Now.ToString("hhmmss"));

                // Seal-veld berekenen
                SHA256 sha256 = SHA256.Create();
                byte[] hashValue = sha256.ComputeHash(new UTF8Encoding().GetBytes(data + SecurityKey));

                // POST data samenstellen
                NameValueCollection postData = new NameValueCollection();
                postData.Add("Data", data);
                postData.Add("Seal", ByteArrayToHexString(hashValue));
                postData.Add("InterfaceVersion", "HP_1.0");

                // Posten van data 
                byte[] response;
                using (WebClient client = new WebClient())
                    response = client.UploadValues(PostUrl, postData);

                TempData["Response"] = Encoding.UTF8.GetString(response);
                return RedirectToAction("Confirm", "Robobank");

            }

            return View(model);
        }

// Converteer een String naar Hexadecimale waarde
        public string ByteArrayToHexString(byte[] bytes)
        {
            StringBuilder result = new StringBuilder(bytes.Length * 2);
            const string hexAlphabet = "0123456789ABCDEF";

            foreach (byte b in bytes)
            {
                result.Append(hexAlphabet[b >> 4]);
                result.Append(hexAlphabet[b & 0xF]);
            }

            return result.ToString();
        }
        List< KeyValuePair< String, String >> ParseData(String data)
        {
            return (from part in data.Split('|')
                    let key = part.Split('=')[0]
                    let value = part.Split('=')[1]
                    select new KeyValuePair(key, value)).ToList();
        }

        static String GetTransactionStatus(String transactionCode)
        {
            switch (transactionCode)
            {
                case "00":
                    return "SUCCESS";
                case "60":
                    return "PENDING";
                case "97":
                    return "EXPIRED";
                case "17":
                    return "CANCELLED";
            }
            return "FAILED";
        }


Step 6:
Create Confirmation and Return action and Views


        public  ActionResult Confirm(string response)
        {
            ViewBag._Response = TempData["Response"];
            return View();
        }

       
        public ActionResult Report()
        {
            
            return View();
        }

        public ActionResult RedirectResponse()
        {
        
            return View();
        }
        [HttpPost]
        public ActionResult RedirectResponse(string Data,string Seal)
        {
            String data = Data;
            String seal = Seal;

            // Verifieer de Seal
            SHA256 sha256 = SHA256.Create();
            byte[] hashValue = sha256.ComputeHash( new UTF8Encoding( ).GetBytes (data + SecurityKey ) );

            if (seal.ToLower() == ByteArrayToHexString( hashValue).ToLower()) // Seal is goed
            {
                // Lees de gewenste waarden uit de server response
                List< KeyValuePair < String, String >> dataItems = ParseData(data);
                String transactionCode = dataItems.Where(i => i.Key == "transactionReference " ).First().Value;
                var responseCode = dataItems.Where(i => i.Key == "responseCode").First().Value;
                String transactionStatus = GetTransactionStatus( responseCode);
                
                ViewBag._transactionCode = transactionCode;
                ViewBag._transactionStatus = transactionStatus;
            }
            else // Hash BAD
            {
                ViewBag._HashBad = "Invalid response from Rabo OmniKassa server";
            }
            return View();
        }


Step 7:
Create confirm View


    @{
    Layout = null;
    }

    @Html.Raw(ViewBag._Response)


Step 8:
Create Response View



@{
    ViewBag.Title = "RedirectResponse";
}

RedirectResponse

@ViewBag._Url @ViewBag._transactionCode @ViewBag._transactionStatus

@ViewBag._HashBad


Thats all.

Thanks for reading.

Wednesday, 10 February 2016

MS SQL Server Queries

Microsoft SQL Server is a database to store information. Today I am going to spark some light on MS SQL Queries. This article is dedicated to beginners. Please have a look at the queries and cross verify with official documents.

Let's start with basics

1. Create Database: Create a new database with your name

Create database NameofDababase
Create Database SQLDemoDB
2. Use database: Select a database where you want to work.

Use database NameofDatabase
Use database SQLDemoDB
3.  Rename Database: If you want to rename a particular database then use following query

EXEC sp_renamedb 'oldname','newname'
EXEC sp_renamedb 'SQLDemoDB','DemoDB'