[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Form post / receive in code behind

Posted on 2004-10-21
25
Medium Priority
?
234 Views
Last Modified: 2013-11-29
Firstly... sorry if this seems like a strange question for people but I've googled around and I can't seem to find any help. :)

I've been asked to integrate some asp.net pages with an online payment service provider that takes a number of variables in the the form of a post from a page on our site.  I've written this for testing purposes and I've realised that I've got to store some values in the page that I'd rather not be seen (easily) by the user for security reasons.  The basic testing form i'm using is as follows:

<form id="frmDataEnter" method="post" action="https://www.domain.com/dataprocess.cfm">
      <P>
            <INPUT type="hidden" id="LOGIN" name="LOGIN" value="I'd rather the user couldn't view source and see this">
            <INPUT type="hidden" id="INTERNAL" name="INTERNAL" value="This either ideally">
      </P>
      <P>Test Amount: <INPUT id="AMOUNT" name="AMOUNT" value="50.00"></P>
      <P><INPUT type="submit" value="Submit for testing"></P>
</form>

Is there any way I can form the correct POST values together in the backend and submit from there?  I appreciate that there are still ways that the user can view what they submitted, but I'd rather that it was slightly more troublesome than just viewing the source of the pre-process page.  

Related to this - At some point during the process, the payment processing site sends a bunch of data back in a silent post.  The payment processing site then waits for a "200 success" message before allowing the user to continue the process.  At the moment I am collecting this data my means of a standard aspx page that grabs the post values on the form load event (Request.Form("Whatever")) and puts them in a database.  The page doesn't output anything, just simply processes the values and loads blank.  Should I be handling this another way?  Are there any other types of page that I should be using for this functionality?  Or is the fact that the processing site waits for a "200 success" message limiting me to html / aspx.

Again, sorry if this question seems a little unnecessary (It works as it is), but I like to make sure I am doing things properly rather than just hacking my way along!
0
Comment
Question by:Psychotext
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
25 Comments
 
LVL 28

Expert Comment

by:mmarinov
ID: 12370602
Hi Psychotext,

can you clear this:
"Is there any way I can form the correct POST values together in the backend and submit from there?" ?

Regards!
B..M
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12370629
heres a secure xml post class I use for authorize .net:

Public Class AuthorizeNet

#Region " Definitions "
    Private _Login As String =
    Private _Password As String =
    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

Aeros
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12370647
this is the post part you are after I believe:
  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

 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())
0
Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

 
LVL 17

Expert Comment

by:AerosSaga
ID: 12370653
Dim web As New System.Net.WebClient()

web.Headers.Add("Content-Type", "application/x-www-form-urlencoded")

Dim d As Byte() = System.Text.Encoding.ASCII.GetBytes("SEARCHSTRING=test")
Dim res As Byte() = web.UploadData("http://abstractvb.com/search.asp", "POST", d)

Console.Write(System.Text.Encoding.ASCII.GetString(res))
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12370660
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
         Dim url As String
        Try
            url = "http://www.yahoo.com"
            Dim webReq As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
            Dim webResp As HttpWebResponse = CType(webReq.GetResponse(), HttpWebResponse)
            Dim responseStream As Stream = webResp.GetResponseStream
            Dim readStream As New StreamReader(responseStream)
            Dim strContent As New StringBuilder
            Dim sLine As String = ""
            Do While Not sLine Is Nothing
                sLine = readStream.ReadLine
                If Not sLine Is Nothing Then
                    strContent.Append(sLine)
                End If
            Loop
            readStream.Close()
            responseStream.Close()
            RichTextBox1.AppendText("Done")
            RichTextBox1.Refresh()
        Catch ex As Exception
            MsgBox("ex=" & ex.Message & Chr(13) & ex.StackTrace)
        End Try
End Sub
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12370671
Dim myRequest As HttpWebRequest = CType(HttpWebRequest.Create("http://www.creditcardgateway.com/"), HttpWebRequest)
            myRequest.AllowAutoRedirect = False
            myRequest.Method = "POST"
            myRequest.ContentType = "application/x-www-form-urlencoded"

'Create post stream
            Dim RequestStream As Stream = myRequest.GetRequestStream()
            Dim SomeBytes() As Byte = Encoding.UTF8.GetBytes(strToSend)

            RequestStream.Write(SomeBytes, 0, SomeBytes.Length)
            RequestStream.Close()

            'Send request and get response
            Dim myResponse As HttpWebResponse = CType(myRequest.GetResponse(), HttpWebResponse)


You get the point
0
 
LVL 2

Author Comment

by:Psychotext
ID: 12370708
Woah you guys are fast!  I shall have a look at these and post back.  Thanks!
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 12371257
Gr8 code Aeros ;)

Best, Nauman.
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12371294
hehe thanks naumen, I really appreciate that;)

Aeros
0
 
LVL 2

Author Comment

by:Psychotext
ID: 12372308
Ok... I've never done anything like this before so you'll have to bear with me.  As far as I can see from your code there are two ways (That you've shown) to do the submission.  The problem is I can't get either to work! ;)  I think my problem is that I actually want the page redirected to the remote page when the form is submitted, but I don't think your code does that (It would appear to send, then wait for return values).  I've tried to make sense of it all as best I can and come up with the following two versions.  Sorry if I've mangled your code too horrifically!

    Private Sub Option1()
        Dim myRequest As HttpWebRequest = CType(HttpWebRequest.Create("https://www.domain.com/dataprocess.cfm"), HttpWebRequest)
        myRequest.AllowAutoRedirect = True
        myRequest.Method = "POST"
        myRequest.ContentType = "application/x-www-form-urlencoded"
            
            'Am I right in thinking comma is the correct delimiter?
        Dim strNVP As String = "LOGIN=loginvalue,INTERNAL=internalvalue,AMOUNT=" & txtAmount.Text
        Dim encoding As New ASCIIEncoding
        Dim byte1 As Byte() = encoding.GetBytes(strNVP)

        Dim newStream As Stream = myRequest.GetRequestStream()
        newStream.Write(byte1, 0, byte1.Length)
        newStream.Close()
    End Sub

    Private Sub Option2()
        Dim nvcPostInfo As New Collections.Specialized.NameValueCollection(3)
        Dim AuthorizeRequest As New Net.WebClient

        With nvcPostInfo
            .Add("LOGIN", "loginvalue")
            .Add("INTERNAL", "internalvalue")
            .Add("AMOUNT", txtAmount.Text)
        End With

        AuthorizeRequest.BaseAddress = "https://www.domain.com/dataprocess"
        AuthorizeRequest.UploadValues(AuthorizeRequest.BaseAddress, "POST", nvcPostInfo)
    End Sub

The first option doesn't actually do anything at the moment.  This is because I'm not sure how to send the values to the remote server and change the page at the same time.  The second option gives me a fairly nasty error message "The underlying connection was closed: The server committed an HTTP protocol violation.".  Which appears in the stack like this:

[WebException: The underlying connection was closed: The server committed an HTTP protocol violation.]
   System.Net.HttpWebRequest.CheckFinalStatus() +678
   System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) +139
   System.Net.HttpWebRequest.GetResponse() +250

I'm sure I'm going to look a little stupid here but if you don't ask you don't get! :)
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12372384
My code is from an external class so that is correct, it redirected from a routine in the page some time after this transaction was finished.

ok 1st, your gonna have to do something with the return stream before you redirect, your users will not notice this.  So basically take the response save it somewhere, then redirect.  Does that make sense?  

Now as for the error message, you will need to step through your routine, see if its sending the request.  If it is great, see if you are getting a response.  If you are check the http code its sending they have meanings!  If you are not then your request is malformed and thus no response is being givin because most likely its not getting there in the state the server expects it in.  There are ways to overide these checks such as using something like this in your web.config:

<system.net>
    <settings>
     <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
</system.net>

But that only cheats, so I advise you step through and see where your code is going wrong.  Parts of the Request/Response process will depend on whome you are trying to communicate with and their protocols as well

Aeros
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12372423
also if your using response.redirect try doing it this way:

         Response.Redirect("OrderProcessed.aspx", False)
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12372481
it could also be from installing sp1 on the .NET framework:

http://blogs.msdn.com/gzunino/archive/2004/09/05/225881.aspx
0
 
LVL 17

Accepted Solution

by:
AerosSaga earned 2000 total points
ID: 12372529
Heres how I use the above class

    Private Sub ImageButton1_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
        'Try
        Page.Validate()
        If Me.IsValid = True Then
            CheckForDiffShipping()
            WriteCustomerInfo()
            WriteOrdererdItems()
            'PerformAuthorization()
            WriteOrder()
            Session("CCType") = Me.ddlCCType.SelectedValue.ToString
            Session("CustomerID") = Me.lblCustomerID.Text.ToString
            Session("OrderID") = Me.lblOrderID.Text.ToString
            Session("SessionID") = Me.lblSessionID.Text.ToString
            Session("OrderTotal") = Me.lblTotalOrder.Text.ToString
            Session("ShippingCost") = Me.lblShipping.Text.ToString
            Session("FinalTotal") = Me.lblFinalTotal.Text.ToString
            Response.Redirect("ProcessOrder.aspx")
        Else
            Response.Write("An unhandled application exception has occoured")
        End If
        'Catch ex As Exception
        '    Me.lblError.Text = ex.Message.ToString
        ' End Try
    End Sub
    Private Sub CheckForDiffShipping()
        If Session("UseDiffInfo") Is "True" Then
            Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
            Dim cmd As New OleDb.OleDbCommand
            cmd.CommandType = CommandType.Text
            cmd.CommandText = "INSERT INTO Shipping (FirstName, LastName, Address1, Address2, City, State, ZipCode) " & _
            "VALUES ('" & CStr(Session("ShipFirstName")).ToString & "', '" & Session("ShipLastName") & "', '" & Session("ShipAddress1") & "','" & Session("ShipAddress2") & "', '" & _
            Session("ShipCity") & "', '" & Session("ShipState") & "', '" & Session("ShipZipCode") & "')"
            cmd.Connection = cnn
            cnn.Open()
            cmd.ExecuteNonQuery()
            cmd.CommandText = "SELECT @@IDENTITY AS 'ShippingID';"
            lblShippingID.Text = CStr(cmd.ExecuteScalar())
            cnn.Close()
            cmd.Dispose()
            cnn.Dispose()
        End If
    End Sub
    Private Sub WriteCustomerInfo()
        Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim cmd As New OleDb.OleDbCommand
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "INSERT INTO Customers (SessionID, FirstName, LastName, Address, Location, City, State, ZipCode, PhoneNumber, " & _
"EmailAddress, CCNumber, CCExpDate, CCType) VALUES (" & CStr(Session("SessionID")).ToString & ", '" & Session("BillFirstName") & "', '" & Session("BillLastName") & "','" & Session("BillAddress1") & "','" & _
Session("BillAddress2") & "', '" & Session("BillCity") & "', '" & Session("BillState") & "', '" & Session("BillZipCode") & "', '" & (CStr(Session("PhoneNumber"))) & _
"', '" & Session("EmailAddress") & "', '" & Me.txtCCNumber.Text & "', '" & Me.ddlExpDate.SelectedValue & "', '" & Me.ddlCCType.SelectedValue & "')"
        cmd.Connection = cnn
        cnn.Open()
        cmd.ExecuteNonQuery()
        cmd.CommandText = "SELECT @@IDENTITY AS 'CustomerID';"
        Me.lblCustomerID.Text = CStr(cmd.ExecuteScalar())
        cnn.Close()
        cmd.Dispose()
        cnn.Dispose()
    End Sub
    Private Sub WriteOrdererdItems()
        Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim cmd As New OleDb.OleDbCommand
        Dim ThisDay As Date
        ThisDay = Today
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "INSERT INTO OrderedITems (CustomerID, OrderDate, ProductID, ProductName, ProductPrice, Quantity, OrderSessionString) " & _
                "SELECT " & Me.lblCustomerID.Text & ",'" & ThisDay & "', TempSession.ProductID, TempSession.ProductName, " & _
                "TempSession.ProductPrice, TempSession.Quantity, '" & Me.Session.SessionID.ToString & "' FROM TempSession WHERE TempSession.SessionString = '" & Me.Session.SessionID & "'"
        cmd.Connection = cnn
        cnn.Open()
        cmd.ExecuteNonQuery()
        cmd.CommandText = "SELECT @@IDENTITY AS 'OrderID';"
        cmd.ExecuteScalar()
        Me.lblOrderID.Text = CStr(cmd.ExecuteScalar())
        cnn.Close()
        cmd.Dispose()
        cnn.Dispose()
    End Sub
    Private Sub PerformAuthorization()
        Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim cmd As New OleDb.OleDbCommand
        Dim strResponse, strAuthNetCode, strAuthNetTransID As String
        Dim AuthNetAddress As New PaymentProcessing.Address(Session("BillFirstName"), Session("BillLastName"), Session("BillAddress1") & " " & Session("BillAddress2"), Session("BillCity"), Session("BillState"), Session("BillZipCode"))
        Dim AuthNetCard As New PaymentProcessing.CreditCard(Me.txtCCNumber.Text, Me.ddlExpDate.SelectedValue)
        Dim AuthNetAmount As String = Me.lblOrderTotal.Text
        Dim AuthNetAdditionalInfo As New PaymentProcessing.PaymentCustomerInformation
        If Session("EmailAddress") <> "" Then
            AuthNetAdditionalInfo.EmailAddress = Session("EmailAddress")
        End If
        Dim AuthNetTrans As New PaymentProcessing.AuthorizeNet(Me.lblOrderID.Text, AuthNetCard, AuthNetAddress, CSng(AuthNetAmount), PaymentProcessing.AuthorizeNet.TransactionFlow.Capture, AuthNetAdditionalInfo)
        AuthNetTrans.PostTransaction()
        Try
            Me.lblAuthCode.Text = CStr(AuthNetTrans.AuthCode.ToString)
            Me.lblTransID.Text = CStr(AuthNetTrans.TransID.ToString)
        Catch ex As Exception
            Me.lblError.Text = ex.Message.ToString
        End Try
    End Sub
    Private Sub WriteOrder()
        Dim cnnCompute As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim cnnWrite As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim cmdCompute As New OleDb.OleDbCommand
        Dim cmdWrite As New OleDb.OleDbCommand
        Dim drCompute As OleDb.OleDbDataReader
        Dim intQuantity As Integer
        Dim decPrice, decTotal, decTotalTemp, decFinalTotal, decTax As Decimal
        Dim dblTax, dblFinalTotal, dblSubTotal, dblTotal As Double
        Dim ThisDay As Date
        ThisDay = Today
        decTotal = 0
        cmdCompute.CommandType = CommandType.Text
        cmdCompute.CommandText = "SELECT * FROM OrderedItems WHERE CustomerID = " & Me.lblCustomerID.Text.ToString & " AND OrderDate = '" & ThisDay & "' AND OrderSessionString = '" & Me.Session.SessionID.ToString & "'"
        cmdCompute.Connection = cnnCompute
        cnnCompute.Open()
        drCompute = cmdCompute.ExecuteReader(CommandBehavior.CloseConnection)
        While drCompute.Read()
            decPrice = CDec(drCompute.Item("ProductPrice"))
            intQuantity = CInt(drCompute.Item("Quantity"))
            decTotalTemp = decPrice * intQuantity
            decTotal = decTotalTemp + decTotal
            dblTotal = decTotal.Round(decTotal, 2)
        End While
        If Session("BillState") = "PA" Or Session("BillState") = "pa" Then
            decTax = decTotal * 0.06
            dblTax = decTax.Round(decTax, 2)
        Else
            decTax = 0
            dblTax = 0
        End If
        decFinalTotal = decTotal + decTax
        dblFinalTotal = decFinalTotal.Round(decFinalTotal, 2)
        Me.lblTotalOrder.Text = CStr(decTotal).ToString
        Session("FinalTotal") = dblFinalTotal
        Session("SubTotal") = dblTotal
        Session("Tax") = dblTax
        cmdWrite.CommandType = CommandType.Text
        If Session("GiftWrap") <> "True" Then
            Session("GiftWrap") = "False"
        End If
        If Session("Newsletter") <> "True" Then
            Session("Newsletter") = "False"
        End If
        If Session("UseDiffInfo") Is "True" Then
            cmdWrite.CommandText = "INSERT INTO Orders (SessionID, CustomerID, OrderTotal, OrderComplete, OrderTax, OrderShipping, AuthCode, TransID, ShippingMethod, GiftWrap, Newsletter, ShippingID) " & _
                  "VALUES (" & Session("SessionID") & ", " & Me.lblCustomerID.Text & ", " & dblFinalTotal & ", True, " & dblTax & ", " & Me.lblShipping.Text & ", '" & Me.lblAuthCode.Text & "', '" & Me.lblTransID.Text & _
                  "', '" & Me.lblShippingMethod.Text & "', " & Session("GiftWrap") & ", " & Session("Newsletter") & ", " & Me.lblShippingID.Text & ");"
        Else
            cmdWrite.CommandText = "INSERT INTO Orders (SessionID, CustomerID, OrderTotal, OrderComplete, OrderTax, OrderShipping, AuthCode, TransID, ShippingMethod, GiftWrap, Newsletter, ShippingID) " & _
        "VALUES (" & Session("SessionID") & ", " & Me.lblCustomerID.Text & ", " & dblFinalTotal & ", True, " & dblTax & ", " & Me.lblShipping.Text & ", '" & Me.lblAuthCode.Text & "', '" & Me.lblTransID.Text & _
        "', '" & Me.lblShippingMethod.Text & "', " & Session("GiftWrap") & ", " & Session("Newsletter") & ", NULL);"
        End If
        cmdWrite.Connection = cnnWrite
        cnnWrite.Open()
        cmdWrite.ExecuteNonQuery()
        cmdCompute.Dispose()
        cmdWrite.Dispose()
        cnnCompute.Dispose()
        cnnWrite.Dispose()
    End Sub
0
 
LVL 2

Author Comment

by:Psychotext
ID: 12372553
I'm very confused now.  I think I had better explain the process a little better than I did the first time round.

User goes to checkout page (checkout.aspx).
User clicks submit button (In the original form (Above) this just posts to the payment server)
User is taken to the payment server to enter their credit card details / address.
User's details are checked and if valid the payment server sends data to my server (getdata.aspx) and awaits a "200 Success" message.
User is taken to a reciept page which has a return to store button (thankyou.aspx).

I think we might be confusing the payment processor I'm having to use (Useless) with a good one that just lets you submit the data to the server and returns the transaction data at the same time.  With this one the user actually has to go off to their page to enter the relevant payment data.  The HTML in my first post worked fine, I just wanted to get the same effect from the backend code.

Sorry if I haven't been clear.
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12372640
well not sure about the specifics for that kinda system, but your gonna have to get the response save it then redirect, thats just the way it is.
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12372646
and the above methodology is correct I assure you.
0
 
LVL 2

Author Comment

by:Psychotext
ID: 12373014
Ok, I shall keep trying and post back.  Kinda wishing I'd just left it now! :D
0
 
LVL 2

Author Comment

by:Psychotext
ID: 12375832
Have been doing some testing.  The following two functions work correctly for getting the data to the external page, but I still cannot work out how to piggy back the data to the page and display the output.  Have tried response.redirect, but this just gives an error on the remote page as no POST variables are included when the page is loaded.  I'll keep trying but I'd really appreciate it if anyone had any ideas.

      Private Sub PostV1()
            'Uses name value collection and Net.WebClient

            Dim nvcPostInfo As New Collections.Specialized.NameValueCollection(6)
            Dim AuthorizeRequest As New Net.WebClient

            With nvcPostInfo
                  .Add("SOMEINFO", "VALUE1")
                  .Add("MOREINFO", "VALUE2")
            End With

            AuthorizeRequest.BaseAddress = "http://www.domain.com/pageprocess.aspx"
            AuthorizeRequest.UploadValues(AuthorizeRequest.BaseAddress, "POST", nvcPostInfo)
      End Sub

      Private Sub PostV2()
            'Uses ASCII encoded string and HTTPWebRequest

            Dim myRequest As HttpWebRequest = CType(HttpWebRequest.Create("http://www.domain.com/pageprocess.aspx"), HttpWebRequest)
            myRequest.AllowAutoRedirect = True
            myRequest.Method = "POST"
            myRequest.ContentType = "application/x-www-form-urlencoded"

            'I made a mistake here before by using comma as the delimiter
            Dim strNVP As String = "SOMEINFO=VALUE1&MOREINFO=VALUE2"

            Dim encoding As New ASCIIEncoding
            Dim byte1 As Byte() = encoding.GetBytes(strNVP)

            Dim newStream As Stream = myRequest.GetRequestStream()
            newStream.Write(byte1, 0, byte1.Length)
            newStream.Close()

            Dim myHttpWebResponse As HttpWebResponse = CType(myRequest.GetResponse(), HttpWebResponse)
      End Sub
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12376545
I have no idea what your trying to do if you got the response, save it either in a db session, whatever, then response.redirect.  What is the issue here?
0
 
LVL 2

Author Comment

by:Psychotext
ID: 12376735
I dont actually get any response worth saving.  In the case of the HTML form post (Which I am trying to replicate through code-behind), certain data is sent (Such as an account number, and the amount) and then the user is taken to the page (The same one handling the POST values) to put in their name, address and credit card details.  Once they have done all this (It takes a couple of screens), some data is passed back to me.  I dont really care about this last step though as the payment processor just sends these values to another page (As I mentioned earlier) in a behind the scenes post.

I just dont know how to explain it any better. lol  I need to do what this does on submission: <form id="frmDataEnter" method="post" action="https://www.domain.com/dataprocess.cfm"> and that is to take the user (and some POST data) off to the payment processing page to put their credit card details etc in.

Really sorry, I've had this problem before - I just don't think I'm that good at explaining things clearly.
0
 
LVL 2

Author Comment

by:Psychotext
ID: 12376748
By the way, thanks for all the help so far.  You've been very patient with me.  The code that submits the data to the offsite page works perfectly (Both versions).
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12377204
why not just save the first postback values in session and avoid all of this?

so
1)save accountinfo/orderinfo to session
2)popup you info form
3)submit it all as needed

0
 
LVL 2

Author Comment

by:Psychotext
ID: 12377458
This may have been the source of the confusion - It's not my information form.  All I can do is send the basic data (Only my login and the price to charge customer) to the payment site.  From that point on the user enters information into a form on the payment site that only the payment processor gets (Their address / credit card info).  

All I get back in the end is a payment reference and a code telling me if the payment was succesful.
0
 
LVL 2

Author Comment

by:Psychotext
ID: 12393544
I'm going to award the points here as the code you have given me is along the right lines - just not appropriate for this particular problem.  I'm going to post another question that makes the problem clearer and gives a link to the actual form in action so that experts can understand what's going on.

I found your code very useful though and will no doubt be making use of it for other payment systems in the future.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Often people are aiming at development of perfect Magento websites. Though, it is easier said than done. You know what’s much easier? To ruin everything. It can be done in seconds. Many of us experimented with design, tried to change some values dir…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…
Suggested Courses

649 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