?
Solved

XMLHTTP and HTTPWebRequest

Posted on 2004-08-25
8
Medium Priority
?
2,105 Views
Last Modified: 2008-07-30
is XMLHTTP or HTTPWeb Request better for submitting data to authorize.net credit card processing?

or is XMLHTTP not available in asp.net 1.1?

am using ASP.NET 1.1... need some sample code in C# to see how to setup the object and send the data.

thanks!
0
Comment
Question by:loyaliser
  • 3
  • 3
  • 2
8 Comments
 
LVL 10

Expert Comment

by:jnhorst
ID: 11897894
Don't know much about authorize.net, but I can provide code for HTTPWebRequest if you need to post XML to an URL.

John
0
 
LVL 10

Assisted Solution

by:jnhorst
jnhorst earned 600 total points
ID: 11897984

// this assumes an XmlDocument variable named xmlDoc has been loaded with the XML.
string url = "{the url to whic you will post"};
WebRequest req = HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentLength = xmlDoc.outerXml.Length;
req.ContentType = "text/xml";

// write xml to the request stream.
StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write(xmlDoc.OuterXml);
sw.Flush;
sw.Close();

// assign credentials if you need to authenticate to the url.
req.Credentials = new NetworkCredentials("username", "password");

// get response.
WebResponse resp = req.GetResponse();

// read response into a stream. this assumes the target will respond with xml.
StreamReader sr = new StreamReader(resp.GetResponseStream());
string xmlRespString = sr.ReadToEnd();
sr.Close();

// load up the response and do whatever with it.
XmlDocument xmlRespDoc = new XmlDocument();
xmlRespDoc.LoadXML(xmlRespString);

John
0
 
LVL 17

Accepted Solution

by:
AerosSaga earned 1400 total points
ID: 11898102
I agree with John we use this process for Authorize.net as well as all of our shipping transaction modules at work.  I think the HttpWebRequest is the best option because all needed mechancisms for the transactions are easily exposed.  I'll give you mine for a more complete example:

Public Class AuthorizeNet

#Region " Definitions "
    Private _Login As String = "XXXXX"
    Private _Password As String = "XXXXX"
    Private _TranKey As String

    Private _TestRequest As Boolean

    Private _BillingAddress As New Address
    Private _ShippingAddress As New Address
    Private _AdditionalInfo As PaymentCustomerInformation

    Private _CreditCard As CreditCard
    Private _ElectronicFundsTransfer As BankTransfer
    Private _TransactionType As TransactionFlow

    Private _Amount As Single
    Private _Tax As Single
    Private _Freight As Single

    Private _AuthCode As String
    Private _TransID As String
#End Region

#Region " Types "
    Public Enum TransactionFlow
        Capture
        Credit
    End Enum
#End Region

#Region " Properties "
    Public Property Login() As String
        Get
            Return _Login
        End Get
        Set(ByVal Value As String)
            _Login = Login
        End Set
    End Property
    Public Property Password() As String
        Get
            Return _Password
        End Get
        Set(ByVal Value As String)
            _Password = Password
        End Set
    End Property
    Public Property TranKey() As String
        Get
            Return _TranKey
        End Get
        Set(ByVal Value As String)
            _TranKey = Value
        End Set
    End Property
    Public Property TestRequest() As Boolean
        Get
            Return _TestRequest
        End Get
        Set(ByVal Value As Boolean)
            _TestRequest = True
        End Set
    End Property
    Public ReadOnly Property CreditCard() As CreditCard
        Get
            Return _CreditCard
        End Get
    End Property
    Public ReadOnly Property ElectronicFundsTransfer() As BankTransfer
        Get
            Return _ElectronicFundsTransfer
        End Get
    End Property
    Public ReadOnly Property AuthCode() As String
        Get
            Return _AuthCode
        End Get
    End Property
    Public ReadOnly Property TransID() As String
        Get
            Return _TransID
        End Get
    End Property
    Public ReadOnly Property BillingAddress() As Address
        Get
            Return _BillingAddress
        End Get
    End Property
    Public Property ShippingAddress() As Address
        Get
            Return _ShippingAddress
        End Get
        Set(ByVal Value As Address)
            _ShippingAddress = Value
        End Set
    End Property
    Public Property TransactionType() As TransactionFlow
        Get
            Return _TransactionType
        End Get
        Set(ByVal Value As TransactionFlow)
            _TransactionType = Value
        End Set
    End Property
    Public Property AdditionalInfo() As PaymentCustomerInformation
        Get
            Return _AdditionalInfo
        End Get
        Set(ByVal Value As PaymentCustomerInformation)
            _AdditionalInfo = Value
        End Set
    End Property

    Public Property Amount() As Single
        Get
            Return _Amount
        End Get
        Set(ByVal Value As Single)
            _Amount = Value
        End Set
    End Property
    Public Property Tax() As Single
        Get
            Return _Tax
        End Get
        Set(ByVal Value As Single)
            _Tax = Value
        End Set
    End Property
    Public Property Freight() As Single
        Get
            Return _Freight
        End Get
        Set(ByVal Value As Single)
            _Freight = Value
        End Set
    End Property
#End Region

#Region " Constructors "
    Public Sub New(ByVal CreditCard As CreditCard, ByVal BillingAddress As Address, _
        ByVal Amount As Single, ByVal TransactionType As TransactionFlow, _
        Optional ByVal AdditionalInfo As PaymentCustomerInformation = Nothing)
        _CreditCard = CreditCard
        _BillingAddress = BillingAddress
        _Amount = Amount
        _TransactionType = TransactionType
        If Not AdditionalInfo Is Nothing Then
            _AdditionalInfo = New PaymentCustomerInformation
            _AdditionalInfo = AdditionalInfo
        End If

        _ElectronicFundsTransfer = Nothing
    End Sub

    Public Sub New(ByVal ElectronicFundsTransfer As BankTransfer, _
        ByVal BillingAddress As Address, ByVal Amount As Single, _
        ByVal TransactionType As TransactionFlow, _
        Optional ByVal AdditionalInfo As PaymentCustomerInformation = Nothing)
        _ElectronicFundsTransfer = ElectronicFundsTransfer
        _BillingAddress = BillingAddress
        _Amount = Amount
        _TransactionType = TransactionType
        If Not AdditionalInfo Is Nothing Then
            _AdditionalInfo = New PaymentCustomerInformation
            _AdditionalInfo = AdditionalInfo
        End If

        _CreditCard = Nothing
    End Sub
#End Region

#Region " Methods "
    Public Sub PostTransaction()

        Dim AuthorizeRequest As New Net.WebClient
        Dim Information As New Collections.Specialized.NameValueCollection(30)
        Dim ReturnInformation As New Collections.Specialized.NameValueCollection(30)
        Dim ReturnBytes As Byte()
        Dim ReturnValues As String()
        Dim ReturnValue, ReturnError As String
        If Login = "" Then Throw New AuthorizeNetException("You must set the login value of the AuthorizeNet class.")

        With Information

            .Add("x_Version", "3.1")
            .Add("x_Delim_Data", "True")
            .Add("x_Login", _Login)
            .Add("x_Password", _Password)
            '.Add("x_Tran_Key", _TranKey)
            .Add("x_Test_Request", "True") '_TestRequest.ToString()

            'A comma is used to seperate the fields while a pipe is used to encapsulate the data.
            '   Authorize.NET doesn't have an escape character for data, so I had to use the pipe to
            '   encapsulate it -- regular expressions up to this point will prevent the pipe symbol
            '   from occuring within the actual data.
            .Add("x_Delim_Char", ",")
            .Add("x_Encap_Char", "|")

            .Add("x_First_Name", BillingAddress.FirstName)
            .Add("x_Last_Name", BillingAddress.LastName)
            .Add("x_Address", BillingAddress.Address)
            .Add("x_City", BillingAddress.City)
            .Add("x_State", BillingAddress.State)
            .Add("x_Zip", BillingAddress.Zip)

            If Not ShippingAddress Is Nothing Then
                .Add("x_Ship_To_First_Name", ShippingAddress.FirstName)
                .Add("x_Ship_To_Last_Name", ShippingAddress.LastName)
                .Add("x_Ship_To_Address", ShippingAddress.Zip)
                .Add("x_Ship_To_City", ShippingAddress.City)
                .Add("x_Ship_To_State", ShippingAddress.State)
                .Add("x_Ship_To_Zip", ShippingAddress.Zip)
            End If

            If Not AdditionalInfo Is Nothing Then
                If AdditionalInfo.Phone <> "" Then .Add("x_Phone", AdditionalInfo.Phone)
                If AdditionalInfo.CustomerID <> 0 Then _
                    .Add("x_Cust_ID", AdditionalInfo.CustomerID.ToString())
                If AdditionalInfo.CustomerIP.ToString() <> "0.0.0.0" Then
                    .Add("x_Customer_IP", AdditionalInfo.CustomerIP.ToString())
                End If
                If AdditionalInfo.EmailAddress <> "" Then .Add("x_Email", AdditionalInfo.EmailAddress)

                If AdditionalInfo.InvoiceNumber.ToString() <> "" Then _
                    .Add("x_Invoice_Num", AdditionalInfo.InvoiceNumber.ToString())
                If AdditionalInfo.Description <> "" Then .Add("x_Description", AdditionalInfo.Description)
            End If

            If Not _CreditCard Is Nothing Then
                'It's a credit card transaction
                .Add("x_Card_Num", _CreditCard.CardNumber)
                .Add("x_Exp_Date", _CreditCard.ExpDate.ToString("MM/yy"))
                .Add("x_Method", "CC")
            ElseIf Not _ElectronicFundsTransfer Is Nothing Then
                'It's an e-check transaction
                .Add("x_Bank_ABA_Code", _ElectronicFundsTransfer.RoutingNumber)
                .Add("x_Bank_Acct_Num", _ElectronicFundsTransfer.AccountNumber)
                Select Case _ElectronicFundsTransfer.AccountType
                    Case BankTransfer.BankAccountType.Savings
                        .Add("x_Bank_Acct_Type", "Savings")
                    Case BankTransfer.BankAccountType.Checking
                        .Add("x_Bank_Acct_Type", "Checking")
                End Select
                .Add("x_Bank_Name", _ElectronicFundsTransfer.BankName)
                .Add("x_Bank_Acct_Name", _ElectronicFundsTransfer.AccountName)
                .Add("x_Method", "ECHECK")
            End If

            Select Case TransactionType
                Case TransactionFlow.Capture
                    'It's a payment to our account
                    .Add("x_Type", "AUTH_CAPTURE")
                Case TransactionFlow.Credit
                    'It's a credit to their account
                    .Add("x_Type", "CREDIT")
            End Select
            .Add("x_Amount", Amount.ToString())

            'Tax and Freight are NOT added onto the total; these values are the tax value (in dollars)
            '   of the transaction and the freight cost of the sale. Again, the total already includes
            '   the sum of the tax and freight.
            If Tax <> 0 Then .Add("x_Tax", Tax.ToString())
            If Freight <> 0 Then .Add("x_Freight", Freight.ToString())

        End With

        AuthorizeRequest.BaseAddress = "https://certification.authorize.net/gateway/transact.dll"
        ReturnBytes = AuthorizeRequest.UploadValues(AuthorizeRequest.BaseAddress, "POST", Information)
        ReturnValues = System.Text.Encoding.ASCII.GetString(ReturnBytes).Split(",".ToCharArray())
               
        If ReturnValues(0).Trim(CChar("|")) = "1" Then
            _AuthCode = ReturnValues(4).Trim(CChar("|"))
            _TransID = ReturnValues(6).Trim(CChar("|"))
        Else
            ReturnError = ReturnValues(3).Trim(CChar("|"))
            If ReturnValues(2).Trim(CChar("|")) = "45" Then
                ReturnError &= " Our Address Verification System (AVS) returned the following error: "
                Select Case ReturnValues(5).Trim(CChar("|"))
                    Case "A"
                        ReturnError &= " the zip code entered does not match the billing address."
                    Case "B"
                        ReturnError &= " no information was provided for the AVS check."
                    Case "E"
                        ReturnError &= " a general error occurred in the AVS system."
                    Case "G"
                        ReturnError &= " the credit card was issued by a non-US bank."
                    Case "N"
                        ReturnError &= " neither the entered street address nor zip code matches the billing address."
                    Case "P"
                        ReturnError &= " AVS is not applicable for this transaction."
                    Case "R"
                        ReturnError &= " please retry the transaction; the AVS system was unavailable or timed out."
                    Case "S"
                        ReturnError &= " the AVS service is not supported by your credit card issuer."
                    Case "U"
                        ReturnError &= " address information is unavailable for the credit card."
                    Case "W"
                        ReturnError &= " the 9 digit zip code matches, but the street address does not."
                    Case "Z"
                        ReturnError &= " the zip code matches, but the address does not."
                End Select
            End If
            Throw New AuthorizeNetException(ReturnError)
        End If

    End Sub
#End Region

End Class

I think this should show you exactly what to do.

Regards,

Aeros
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 1

Author Comment

by:loyaliser
ID: 11898108
with authorize.net i need to send a URL string that is built in the code... it  eventually looks something like this:

https://secure.authorize.net/gateway/transact.dll?username=XYZ&testaccount=123&creditcard=428282828282882

so what changes in the code you provided above? and is WebRequest better than XMLHTTP?
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11898125
ummmmm...no you can't send credit card numbers via url string for obvious reasons, its an http post containing an xml stream.
0
 
LVL 1

Author Comment

by:loyaliser
ID: 11898158
aerosaga

but i have to send the CC number in the url... otherwise how else will authorize.net know which card to charge?

the form we have is ssl secure, and when submitted processes the card info filled out using the webrequest code given above, then retrieves results from authorize.net and displays a thank you page.

or am i mistaken?!
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11898203
I believe you misinterpreted the documentation, the code I gave you does this it takes all the information you are wanting to put into a query string, and creates an xml file per Authorize.NET specs.  It then creates the web request which is actually an http post.  Within this http post is the xml document containing your merchant information, the customers information, credit card numbers, etc.  Authorize.NET parses this xml request and then performs the transaction.  Then they send you a response.  The response is an xml stream just like the one you sent only with your return information such as declined proccessed, etc.  It will also tell you a reson if it failed.  I gave you pretty much the whole routine.

Regards,

Aeros
0
 
LVL 1

Author Comment

by:loyaliser
ID: 11898252
aeros

got it... thanks!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question