Fixing Authorize.NET’s FormBuilders for ASP.NET MVC

Recently, I was working on a client site and had to implement payment using Authorize.NET. Compared to some other service providers, their documentation and sample code is fairly good. However, when I tried to use their

    @using (new SIMForm(...)) {}

construct, I kept getting forms that looked like crap. It turns out that that class actually writes all its output using Response.Write(). Luckily, they provide code for all of this instead of just a library, so I was able to make a simple modification to provide the functionality I needed. Here is the code I added/copypasta’ed:

    public SIMForm(string returnUrl, decimal amount, string apiLogin, string transactionKey, bool isTest)
        {
            _amount = amount;
            _apiLogin = apiLogin;
            _transactionkey = transactionKey;
            _returnUrl = returnUrl;
            _isTest = isTest;
        }

public string WriteForm()
        {

            var seq = Crypto.GenerateSequence();
            var stamp = Crypto.GenerateTimestamp();

            var fingerPrint = Crypto.GenerateFingerprint(_transactionkey,
                _apiLogin, _amount, seq.ToString(), stamp.ToString());

            var formAction = Gateway.LIVE_URL;

            //for testing
            if (_isTest)
                formAction = Gateway.TEST_URL;
            var output = new StringBuilder();
            output.Append("
\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); return output.ToString(); }

Now, in my view, I can call:

   @{var simForm = new SIMForm(url, amount, ViewData["ApiLogin"].ToString(),
           ViewData["TransactionKey"].ToString(), Convert.ToBoolean(ViewData["IsTest"]));}
   @Html.Raw(simForm.WriteForm())

Hopefully this can help someone figure it out more quickly than I did.

Posted Monday, January 30th, 2012 under ASP.NET MVC.

Tags: , ,

Leave a Reply