Authorize .Net


Authorize .Net Integration with ASP.NET


Online Payments is a common way of accepting payments these days. In this article i will explain how to Integrate Authorize .Net with C# ASP .NET and accept Payments online.

Introduction
Authorize.Net is a payment gateway that enables merchants to accept credit card and electronic check payments via Web sites, retail stores, mail order/telephone order (MOTO) call centers and mobile devices. In other words, Authorize.Net replaces the traditional credit card swipe machine you find in the physical retail world. Authorize.net captures merchant’s customers’ payment data, including card number and expiration date, from checkout form and securely communicate with the appropriate financial institutions for processing and automatic deposit into your account.

Setting up a Test Account
Since you do not want to test and play with real money, you will need to create a test account. You can create a test account from Authorize.Net Developer Website .


Fill up the form and press the Sign Up Button. On the next page you will get API Login ID and Transaction Key. Save it for the future Usage.



In this article i will explain how to receive payments without the user leaving your website. This is actually done using test account but the same is the case when using live account.

Payment through Your own Website

Create a page and drop textbox controls on the page so that all required information is filled. Which include First Name, Last Name, Address, City, State, Postal Code, Country, Phone, Email, Credit Card Number, CCV, Amount and DropDownList controls for Expiration Month and Expiration Year (for Credit Card). Also add a Button to submit payment and one CustomValidator control on top of it to show the error message in case the transaction fails. A Sample HTML Code for the aspx page is as follows:
<body>
   

    <form id="form1" runat="server">
    <div id="content">
        <div style="text-align: left;">
            <asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="Authorize" />
            <br />
            <table border="0" cellpadding="5" cellspacing="0" width="500">
                <tr>
                    <td style="width: 167px">
                        <asp:Label ID="lblfname" runat="server" Text="First Name"></asp:Label><br />
                        <asp:TextBox ID="FirstNameTextBox" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="FirstNameTextBox"
                            runat="server" ErrorMessage="First Name is a Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="FirstNameTextBox"
                            ErrorMessage="Please limit the length of the content entered to 40 characters"
                            ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,40}$">*</asp:RegularExpressionValidator>
                    </td>
                    <td>
                        <asp:Label ID="lbllname" runat="server" Text="Last Name"></asp:Label><br />
                        <asp:TextBox ID="LastNameTextBox" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="LastNameTextBox"
                            runat="server" ErrorMessage="Last Name is a Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="LastNameTextBox"
                            ErrorMessage="Please limit the length of the content entered to 40 characters"
                            ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,40}$">*</asp:RegularExpressionValidator>
                    </td>
                    <td colspan="2" rowspan="2">
                        <!-- (c) 2006. Authorize.Net is a registered trademark of Lightbridge, Inc. -->

                        <script type="text/javascript" language="javascript">
                            var ANS_customer_id = "1ae28d18-9cbf-488c-a5a3-3fdce9333f50";</script>

                        <script type="text/javascript" language="javascript" src="//VERIFY.AUTHORIZE.NET/anetseal/seal.js"></script>

                        <!--   End Seal  -->
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <asp:Label ID="lblAddress" runat="server" Text="Address"></asp:Label><br />
                        <asp:TextBox ID="AddressTextBox" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" ControlToValidate="AddressTextBox"
                            runat="server" ErrorMessage="Address is a Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ControlToValidate="AddressTextBox"
                            ErrorMessage="Please limit the length of the content entered to 60 characters"
                            ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,60}$">*</asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td style="width: 167px">
                        <asp:Label ID="lblCity" runat="server" Text="City"></asp:Label><br />
                        <asp:TextBox ID="CityTextBox" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" ControlToValidate="CityTextBox"
                            runat="server" ErrorMessage="City is a Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ControlToValidate="CityTextBox"
                            ErrorMessage="Please limit the length of the content entered to 40 characters"
                            ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,40}$">*</asp:RegularExpressionValidator>
                    </td>
                    <td>
                        <asp:Label ID="lblState" runat="server" Text="State"></asp:Label><br />
                        <asp:TextBox ID="StateTextBox" runat="server" MaxLength="30" Text=""></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator11" ControlToValidate="StateTextBox"
                            runat="server" ErrorMessage="State is Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" ControlToValidate="StateTextBox"
                            ErrorMessage="Please limit the length of the content entered to 40 characters"
                            ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,40}$">*</asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td style="width: 167px">
                        <asp:Label ID="lblpcode" runat="server" Text="Postal Code"></asp:Label><br />
                        <asp:TextBox ID="ZipTextBox" runat="server" CssClass="mediumTextBox"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" ControlToValidate="ZipTextBox"
                            runat="server" ErrorMessage="Zip Code Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator5" runat="server" ControlToValidate="ZipTextBox"
                            ErrorMessage="Please limit the length of the content entered to 15 characters"
                            ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,15}$">*</asp:RegularExpressionValidator>
                    </td>
                    <td>
                        <asp:Label ID="lblCountry" runat="server" Text="Country"></asp:Label><br />
                        <asp:TextBox ID="CountryTextBox" runat="server" CssClass="mediumTextBox" Text="USA"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator10" ControlToValidate="CountryTextBox"
                            runat="server" ErrorMessage="Country Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator10" runat="server"
                            ControlToValidate="CountryTextBox" ErrorMessage="Please limit the length of the content entered to 40 characters"
                            ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,40}$">*</asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <asp:Label ID="lblPhone" runat="server" Text="Phone"></asp:Label><br />
                        <asp:TextBox ID="PhoneTextBox" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="PhoneTextBox"
                            runat="server" ErrorMessage="Phone is a Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <asp:Label ID="lblEmail" runat="server" Text="Email"></asp:Label><br />
                        <asp:TextBox ID="EmailTextBox" runat="server" CssClass="xx-largeTextBox">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator7" ControlToValidate="EmailTextBox"
                            runat="server" ErrorMessage="Email is a Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator7" runat="server" ControlToValidate="EmailTextBox"
                            ErrorMessage="Please limit the length of the content entered to 255 characters"
                            ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,255}$">*</asp:RegularExpressionValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator49" runat="server"
                            ControlToValidate="EmailTextBox" ErrorMessage="Please Enter a valid Email Address"
                            ValidationGroup="Authorize" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <asp:Label ID="lblcrdtcrdnum" runat="server" Text="Credit Card Number"></asp:Label><br />
                        <asp:TextBox ID="CreditCardTextBox" runat="server">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator8" ControlToValidate="CreditCardTextBox"
                            runat="server" ErrorMessage="Credit Card is a Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator9" runat="server" ControlToValidate="CreditCardTextBox"
                            ErrorMessage="Please Enter a valid Credit Card Number" ValidationGroup="Authorize"
                            ValidationExpression="^[\s\S]{0,22}$">*</asp:RegularExpressionValidator>
                        <br />
                        <asp:Label ID="lblcrdt" runat="server" Text="111222333444" ForeColor="Red"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="1" style="width: 167px">
                        <asp:Label ID="lblExpMonth" runat="server" Text="Expiration Month"></asp:Label><br />
                        <asp:DropDownList ID="MonthDropDownList" runat="server">
                            <asp:ListItem Value="01" Text="01 - January"></asp:ListItem>
                            <asp:ListItem Value="02" Text="02 - February"></asp:ListItem>
                            <asp:ListItem Value="03" Text="03 - March"></asp:ListItem>
                            <asp:ListItem Value="04" Text="04 - April"></asp:ListItem>
                            <asp:ListItem Value="05" Text="05 - May"></asp:ListItem>
                            <asp:ListItem Value="06" Text="06 - June"></asp:ListItem>
                            <asp:ListItem Value="07" Text="07 - July"></asp:ListItem>
                            <asp:ListItem Value="08" Text="08 - August"></asp:ListItem>
                            <asp:ListItem Value="09" Text="09 - September"></asp:ListItem>
                            <asp:ListItem Value="10" Text="10 - October"></asp:ListItem>
                            <asp:ListItem Value="11" Text="11 - November"></asp:ListItem>
                            <asp:ListItem Value="12" Text="12 - December"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                    <td colspan="1">
                        <asp:Label ID="lblExpYear" runat="server" Text="Expiration Year"></asp:Label><br />
                        <asp:DropDownList ID="YearDropDownList" runat="server">
                            <asp:ListItem Value="08">2008</asp:ListItem>
                            <asp:ListItem Value="09">2009</asp:ListItem>
                            <asp:ListItem Value="10">2010</asp:ListItem>
                            <asp:ListItem Value="11">2011</asp:ListItem>
                            <asp:ListItem Value="12">2012</asp:ListItem>
                            <asp:ListItem Value="13">2013</asp:ListItem>
                            <asp:ListItem Value="14">2014</asp:ListItem>
                            <asp:ListItem Value="15">2015</asp:ListItem>
                            <asp:ListItem Value="16">2016</asp:ListItem>
                        </asp:DropDownList>
                    </td>
                    <td colspan="1">
                        <asp:Label ID="lblccv" runat="server" Text="CCV"></asp:Label><br />
                        <asp:TextBox ID="CCVTextBox" runat="server">
                        </asp:TextBox>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator8" runat="server" ControlToValidate="CCVTextBox"
                            ErrorMessage="Please Enter a valid CCV Number" ValidationGroup="Authorize" ValidationExpression="^[\s\S]{0,4}$">*</asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
                        <asp:Label ID="lblAmount" runat="server" Text="Amount"></asp:Label><br />
                        <asp:TextBox ID="AmountTextBox" runat="server" Text="">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator9" ControlToValidate="AmountTextBox"
                            runat="server" ErrorMessage="Amount is a Required Field" Text="*" ValidationGroup="Authorize"></asp:RequiredFieldValidator>
                        <asp:CompareValidator ID="CompareValidator1" runat="server" Type="Currency" Operator="DataTypeCheck"
                            ValidationGroup="Authorize" ErrorMessage="Invalid Amount, only numbers and '.' allowed"
                            ControlToValidate="AmountTextBox">*</asp:CompareValidator><br />
                    </td>
                </tr>
                <tr>
                    <td style="width: 167px; height: 53px">
                        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="" OnServerValidate="CustomValidator1_ServerValidate"
                            ValidationGroup="Authorize"></asp:CustomValidator><br />
                        <asp:Button ID="SubmitButton" runat="server" Text="Submit Payment" CausesValidation="true"
                            ValidationGroup="Authorize" OnClick="SubmitButton_Click" />
                    </td>
                </tr>
                <tr>
                   
                </tr>
            </table>
            <br />
        </div>
    </div>
   
    </form>
</body>

Create a function in the cs file of the page and name it AuthorizePayment() wih return type of bool and insert the following code in it.

private bool AuthorizePayment()
    {
        CustomValidator1.ErrorMessage = "";
        string AuthNetVersion = "3.1"; // Contains CCV support
        string AuthNetLoginID = "4y5BfuW7jm"; //Set your AuthNetLoginID here
        string AuthNetTransKey = "4cAmW927n8uLf5J8";  // Get this from your authorize.net merchant interface

        WebClient webClientRequest = new WebClient();
        System.Collections.Specialized.NameValueCollection InputObject = new System.Collections.Specialized.NameValueCollection(30);
        System.Collections.Specialized.NameValueCollection ReturnObject = new System.Collections.Specialized.NameValueCollection(30);

        byte[] ReturnBytes;
        string[] ReturnValues;
        string ErrorString;

        InputObject.Add("x_version", AuthNetVersion);
        InputObject.Add("x_delim_data", "True");
        InputObject.Add("x_login", AuthNetLoginID);
        InputObject.Add("x_tran_key", AuthNetTransKey);
        InputObject.Add("x_relay_response", "False");

        //----------------------Set to False to go Live--------------------
        InputObject.Add("x_test_request", "False");
        //---------------------------------------------------------------------
        InputObject.Add("x_delim_char", ",");
        InputObject.Add("x_encap_char", "|");

        //Billing Address
        InputObject.Add("x_first_name", FirstNameTextBox.Text);
        InputObject.Add("x_last_name", LastNameTextBox.Text);
        InputObject.Add("x_phone", PhoneTextBox.Text);
        InputObject.Add("x_address", AddressTextBox.Text);
        InputObject.Add("x_city", CityTextBox.Text);
        InputObject.Add("x_state", StateTextBox.Text);
        InputObject.Add("x_zip", ZipTextBox.Text);
        InputObject.Add("x_email", EmailTextBox.Text);
        InputObject.Add("x_email_customer", "touseef@keystone-services.com");                     //Emails Customer
        InputObject.Add("x_merchant_email", "touseef@keystone-services.com");  //Emails Merchant
        InputObject.Add("x_country", CountryTextBox.Text);
        InputObject.Add("x_customer_ip", Request.UserHostAddress);  //Store Customer IP Address

        //Amount
        InputObject.Add("x_description", "Sample Website " + string.Format("{0:c2}", AmountTextBox.Text));  //Description of Purchase

        //Card Details
        InputObject.Add("x_card_num", CreditCardTextBox.Text);
        InputObject.Add("x_exp_date", MonthDropDownList.Text + "/" + YearDropDownList.Text);
        InputObject.Add("x_card_code", CCVTextBox.Text);

        InputObject.Add("x_method", "CC");
        InputObject.Add("x_type", "AUTH_CAPTURE");
        //InputObject.Add("x_trans_id", "2153777340");
        InputObject.Add("x_amount", string.Format("{0:c2}", Convert.ToDouble(AmountTextBox.Text)));

        // Currency setting. Check the guide for other supported currencies
        InputObject.Add("x_currency_code", "USD");

        try
        {
            //Actual Server
            //Set above Testmode=off to go live
            webClientRequest.BaseAddress = "https://test.authorize.net/gateway/transact.dll";

            ReturnBytes = webClientRequest.UploadValues(webClientRequest.BaseAddress, "POST", InputObject);
            ReturnValues = System.Text.Encoding.ASCII.GetString(ReturnBytes).Split(",".ToCharArray());

            if (ReturnValues[0].Trim(char.Parse("|")) == "1")
            {
                //AuthNetCodeLabel.Text = ReturnValues[4].Trim(char.Parse("|")); // Returned Authorisation Code
                //AuthNetTransIDLabel.Text = ReturnValues[6].Trim(char.Parse("|")); // Returned Transaction ID
                return true;
            }
            else
            {
                // Error!
                ErrorString = ReturnValues[3].Trim(char.Parse("|")) + " (" + ReturnValues[2].Trim(char.Parse("|")) + ")";

                if (ReturnValues[2].Trim(char.Parse("|")) == "44")
                {
                    // CCV transaction decline
                    ErrorString += "Credit Card Code Verification (CCV) returned the following error: ";

                    switch (ReturnValues[38].Trim(char.Parse("|")))
                    {
                        case "N":
                            ErrorString += "Card Code does not match.";
                            break;
                        case "P":
                            ErrorString += "Card Code was not processed.";
                            break;
                        case "S":
                            ErrorString += "Card Code should be on card but was not indicated.";
                            break;
                        case "U":
                            ErrorString += "Issuer was not certified for Card Code.";
                            break;
                    }
                }

                if (ReturnValues[2].Trim(char.Parse("|")) == "45")
                {
                    if (ErrorString.Length > 1)
                        ErrorString += "<br />n";

                    // AVS transaction decline
                    ErrorString += "Address Verification System (AVS) " +
                      "returned the following error: ";

                    switch (ReturnValues[5].Trim(char.Parse("|")))
                    {
                        case "A":
                            ErrorString += " the zip code entered does not match the billing address.";
                            break;
                        case "B":
                            ErrorString += " no information was provided for the AVS check.";
                            break;
                        case "E":
                            ErrorString += " a general error occurred in the AVS system.";
                            break;
                        case "G":
                            ErrorString += " the credit card was issued by a non-US bank.";
                            break;
                        case "N":
                            ErrorString += " neither the entered street address nor zip code matches the billing address.";
                            break;
                        case "P":
                            ErrorString += " AVS is not applicable for this transaction.";
                            break;
                        case "R":
                            ErrorString += " please retry the transaction; the AVS system was unavailable or timed out.";
                            break;
                        case "S":
                            ErrorString += " the AVS service is not supported by your credit card issuer.";
                            break;
                        case "U":
                            ErrorString += " address information is unavailable for the credit card.";
                            break;
                        case "W":
                            ErrorString += " the 9 digit zip code matches, but the street address does not.";
                            break;
                        case "Z":
                            ErrorString += " the zip code matches, but the address does not.";
                            break;
                    }
                }

                // ErrorString contains the actual error
                CustomValidator1.ErrorMessage = ErrorString;
                return false;
            }
        }
        catch (Exception ex)
        {
            CustomValidator1.ErrorMessage = ex.Message;
            return false;
        }
    }
Create a ServerValidate function of the CustomValidator and insert the code so that it should show error message in case of transaction failure or redirect to ThankYou page in case of successful transaction. The code should look like this:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;

        AuthorizePayment();
        if (CustomValidator1.ErrorMessage.Length > 0)
        {
            args.IsValid = false;
        }
        else
        {
            //Processed so send the user to a Thank You Page
            Response.Redirect("ThankYou.aspx");
        }
    }

To avoid amount being changed through the process, write the following code in PageLoad event of the cs file

if (!IsPostBack)
        {
            if (Request.Params["Amount"] != null)  //simple to pass in amount as query string
            {
                AmountTextBox.Text = Convert.ToString(Request.Params["Amount"]);
                AmountTextBox.Enabled = false;
                AmountTextBox.ReadOnly = true;
            }
        }