programming tips and tricks for asp.net

Learn Stuff

Simple ASP.NET & VB.NET example code for Authorize.net's AIM API

SIMPLE DISCLAIMER! This code is what worked for my purposes when evaluating Authorize.net's VB.NET sample code of the AIM API. If you use it, it's your responsibility to implement it properly and securely!

This code sample is for anybody who's looked over the ASP.NET/Visual Basic.NET code sample provided by Authorize.net for their Advanced Integration Method (AIM) API and thought, "I just wanted to look at an .ASPX page and its corresponding code-behind .VB file to see some sample code! But this example contains 18 different files scattered throughout 8 different directories. Which do I need to evaluate?"

More typical output for an ASP.NET web app

So, I've taken the "AIM - VB.NET" sample from from http://developer.authorize.net/samplecode and simplified it a bit and left most of their original comments in it. However, I've also added some explanatory notes and changed the code to output the results via simple Response.Write statements. The original sample was stuffing the output into a span's InnerHtml attribute, which is a bit odd for ASP.NET code. I thought about sending the output to a Label or Literal server control, but decided not to, so as to keep the ASPX file as simple as possible. There are things you'd likely want to do to really use this code, like perhaps abstracting it into a separate SUB or Method, and also create classes for the Submission and Response values to pass around. But that's not the point here. The point is to simplify, explain, and 'VB.NET'-ify the sample Authorize.net provided.

Not as simple, but more secure storage of Login & Transaction Keys

By the way, I'm storing the Login and Transaction Key values as AppSettings in the web.config instead of the .VB file. I realize this flies in the face of simplifying the code, but it's more secure to use the web.config, so I'm doing it that way out of (healthy?) paranoia.

Note: I've created a zip that you can download containing the web.config, default.aspx, default.aspx.vb, and an accompanying readme.txt here.

And so without further gilding the lily and with no more ado, I give to you, the simplified, slightly more ASP.NET/VB.NET-orthodox version of Authorize.net's sample code for the AIM API:

Web.Config

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="AuthorizeNetLogin" value="XXXX" />
        <add key="AuthorizeNetTransactionKey" value="XXXXXXXXX" />
    </appSettings>
    <system.web>
        <compilation debug="false" strict="false" explicit="true" targetFramework="4.0" />
    </system.web>
</configuration>

 

Default.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Authorize.net AIM Example on ASP.NET, Using VB.NET</title>
</head>
<body>
    <form id="form1" runat="server"></form>
</body>
</html>

 

Default.aspx.vb

Imports System.Net
Imports System.IO

Partial Class _Default
  Inherits System.Web.UI.Page

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' By default, this sample code is designed to post to our test server for
    ' developer accounts: https://test.authorize.net/gateway/transact.dll
    ' for real accounts (even in test mode), please make sure that you are
    ' posting to: https://secure.authorize.net/gateway/transact.dll

    Dim post_url As String
    post_url = "https://secure.authorize.net/gateway/transact.dll"

    Dim post_values As New Dictionary(Of String, String)
    'the API Login ID and Transaction Key must be replaced with valid values
    '
    'zolmedia-MERCHANT INFO
    ' NOTE: I know I promised to keep this sample as simple as possible.
    ' However, storing the Authorize.net login and transaction keys in the .vb code-behind makes me nervous.
    ' That's why they're stored in the web.config instead as AppSettings.
    ' IIS/ASP.NET goes to greater lengths to protect the web.config file.
    post_values.Add("x_login", ConfigurationManager.AppSettings("AuthLogin"))
    post_values.Add("x_tran_key", ConfigurationManager.AppSettings("AuthTranKey"))

    'zolmedia-TRANSACTION INFO
    ' Toggling between "TRUE" and "FALSE" for the "x_test_request" values is the equivalent to logging into "Mechant Login" and switching between "TEST" and "LIVE" modes.
    ' Changing the "x_test_request" value is much quicker than logging into the account, however.
    ' Note that submissions performed while in Test mode will not show up as a transaction in Authorize.net.
    ' After changing to LIVE mode, your transactions will show up. You'll have to use a real credit card though, not the 4111111111111111 test number.
    ' To find the transactions in LIVE mode, go to "Unsettled Transactions". Be sure to void your test transactions too (before that day's "settlement" time).
    post_values.Add("x_test_request", "TRUE")

    post_values.Add("x_version", "3.0") 'zolmedia-The AIM Developer guide says it's best to explicitly set this instead of relying on the default value
    post_values.Add("x_type", "AUTH_CAPTURE")

    post_values.Add("x_delim_data", "TRUE")
    post_values.Add("x_delim_char", "|")
    post_values.Add("x_relay_response", "FALSE")

    post_values.Add("x_method", "CC")
    'CUSTOMER INFO
    post_values.Add("x_card_num", "4111111111111111") 'zolmedia-This is the "special" test number for VISA
    post_values.Add("x_exp_date", "1220")

    post_values.Add("x_amount", "0.01")
    post_values.Add("x_description", "Test Purchase")

    post_values.Add("x_first_name", "John")
    post_values.Add("x_last_name", "Doe")
    post_values.Add("x_address", "1 Main Street")
    post_values.Add("x_state", "WA")
    post_values.Add("x_zip", "98004")
    ' Additional fields can be added here as outlined in the AIM integration
    ' guide at: http://developer.authorize.net

    ' This section takes the input fields and converts them to the proper format
    ' for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
    Dim post_string As String = ""
    For Each field As KeyValuePair(Of String, String) In post_values
      post_string &= field.Key & "=" & HttpUtility.UrlEncode(field.Value) & "&"
    Next
    post_string = Left(post_string, Len(post_string) - 1)

    ' The following section provides an example of how to add line item details to
    ' the post string.  Because line items may consist of multiple values with the
    ' same key/name, they cannot be simply added into the above array.
    '
    ' This section is commented out by default.
    'Dim line_items() As String = { _
    '    "item1<|>golf balls<|><|>2<|>18.95<|>Y", _
    '    "item2<|>golf bag<|>Wilson golf carry bag, red<|>1<|>39.99<|>Y", _
    '    "item3<|>book<|>Golf for Dummies<|>1<|>21.99<|>Y"}
    '
    'For Each value As String In line_items
    '   post_string += "&x_line_item=" + HttpUtility.UrlEncode(value)
    'Next

    ' create an HttpWebRequest object to communicate with Authorize.net
    Dim objRequest As HttpWebRequest = CType(WebRequest.Create(post_url), HttpWebRequest)
    objRequest.Method = "POST"
    objRequest.ContentLength = post_string.Length
    objRequest.ContentType = "application/x-www-form-urlencoded"

    ' post data is sent as a stream
    Dim myWriter As StreamWriter = Nothing
    myWriter = New StreamWriter(objRequest.GetRequestStream())
    myWriter.Write(post_string)
    myWriter.Close()

    ' returned values are returned as a stream, then read into a string
    Dim objResponse As HttpWebResponse = CType(objRequest.GetResponse(), HttpWebResponse)
    Dim responseStream As New StreamReader(objResponse.GetResponseStream())
    Dim post_response As String = responseStream.ReadToEnd()
    responseStream.Close()

    ' the response string is broken into an array
    Dim response_array As Array = Split(post_response, post_values("x_delim_char"), -1)

    'zolmedia-I'm using Response.Write statements instead of stuffing the span's InnerHtml attribute with the output (what was done in the Authorize.net example)
    Dim i As Integer = 0
    For Each value In response_array
      i += 1 '(shorthand for i = i + 1)
      Response.Write(i & ") " & value & "<br />" & vbCrLf)
    Next
    ' individual elements of the array could be accessed to read certain response
    ' fields.  For example, response_array(0) would return the Response Code,
    ' response_array(2) would return the Response Reason Code.
    ' for a list of response fields, please review the AIM Implementation Guide
  End Sub

End Class

Originally published on 10/1/2010.

Register  |  Login