Problems With Paypal Express Checkout Integration (WEBREQUEST) - asp.net

So I was struggling with making head or tail out of the PayPal documentation and always felt that something was not right with my Webrequest.
So I stripped all the code back to basic and simply submitted the request via HTTP and the PLUS side is that I now get a response back from the PayPal sandbox server where ACK=Success and TOKEN=Valid-token-value-here there are some other variables returned too, such as CORRELATIONID and TIMESTAMP.
And hence so I tried some of the webrequest samples and I simply get a blank screen instead of being redirected to Paypal for the (sandbox) customer to complete payment.
So if anyone can post their WebRequest method that would be great.
Here is the code I used for my webrequest, I'm sure its wrong but cannot pinpoint where it is going wrong.
Also, when I run the code on my localhost during debugging, everything works fine and the call is completed with SUCCESS and a TOKEN is received.
When I run it live, I recieve Error Number 5 in the Error exception and also the text `Remote host failed to connect' in the STATUS DESCRIPTION.
THIS IS THE UPDATED CODE
Function MakeWebRequest(ByVal pUseSandbox As Boolean, ByVal pRequestMethod As String, ByVal pReturnUrl As String, ByVal pCancelUrl As String, ByRef pRtnStatus As String, ByRef pRtnStatusId As HttpStatusCode, ByRef pRtnResponseString As String) As Boolean
'
Dim _sxHost As String = Nothing
Dim _sxEndpoint As String = Nothing
Dim _sxNameValCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxResponseCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxCounta As Integer = Nothing
Dim _sxParamsString As String = Nothing
'
'-> Init
_sxParamsString = ""
MakeWebRequest = False
_sxNameValCol = New System.Collections.Specialized.NameValueCollection()
_sxResponseCol = New System.Collections.Specialized.NameValueCollection()
If pUseSandbox Then
_sxHost = "http://www.sandbox.paypal.com"
_sxEndpoint = "https://api-3t.sandbox.paypal.com/nvp"
Else
_sxHost = "http://www.paypal.com"
_sxEndpoint = "https://api-3t.paypal.com/nvp"
End If
'-> Create Request
Try
'-> Key/Value Collection Params
_sxNameValCol.Add("METHOD", "SetExpressCheckout")
_sxNameValCol.Add("USER", _UserName)
_sxNameValCol.Add("PWD", _Password)
_sxNameValCol.Add("SIGNATURE", _Signature)
_sxNameValCol.Add("PAYMENTREQUEST_0_AMT", Format(_Basket.BasketTotalIncDelivery / 100, "0.00"))
_sxNameValCol.Add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale")
_sxNameValCol.Add("PAYMENTREQUEST_0_CURRENCYCODE", "GBP")
_sxNameValCol.Add("RETURNURL", pReturnUrl)
_sxNameValCol.Add("CANCELURL", pCancelUrl)
_sxNameValCol.Add("REQCONFIRMSHIPPING", "0")
_sxNameValCol.Add("NOSHIPPING", "2")
_sxNameValCol.Add("LOCALECODE", "EN")
_sxNameValCol.Add("BUTTONSOURCE", "PP-ECWizard")
_sxNameValCol.Add("VERSION", "93.0")
'-> UrlEncode
For _sxCounta = 0 To _sxNameValCol.Count - 1
If _sxCounta = 0 Then
_sxParamsString = _sxParamsString & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
Else
_sxParamsString = _sxParamsString & "&" & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
End If
Next
'-> Credentials (not used)
'_sxRequest.Credentials = CredentialCache.DefaultCredentials
Try
Dim _sxRequest As WebRequest = DirectCast(System.Net.WebRequest.Create(_sxEndpoint), System.Net.HttpWebRequest)
'-> Convert request to byte-array
Dim _sxByteArray As Byte() = Encoding.UTF8.GetBytes(_sxParamsString)
_sxRequest.Method = "POST" 'Our method is post, otherwise the buffer (_sxParamsString) would be useless
_sxRequest.ContentType = "application/x-www-form-urlencoded" 'We use form contentType, for the postvars
_sxRequest.ContentLength = _sxByteArray.Length 'The length of the buffer (postvars) is used as contentlength
Dim _sxPostDataStream As System.IO.Stream = _sxRequest.GetRequestStream() 'We open a stream for writing the postvars
_sxPostDataStream.Write(_sxByteArray, 0, _sxByteArray.Length) 'Now we write, and afterwards, we close
_sxPostDataStream.Close() 'Closing is always important!
'-> Create Response
Dim _sxResponse As HttpWebResponse = DirectCast(_sxRequest.GetResponse(), HttpWebResponse)
'-> Get Response Status
pRtnStatus = _sxResponse.StatusDescription
pRtnStatusId = _sxResponse.StatusCode
'-> Reponse Stream
Dim _sxResponseStream As Stream = _sxResponse.GetResponseStream() 'Open a stream to the response
'-> Response Stream Reader
Dim _sxStreamReader As New StreamReader(_sxResponseStream) 'Open as reader for the stream
pRtnResponseString = _sxStreamReader.ReadToEnd() 'Read the response string
MakeWebRequest = True
'-> Tidy up
_sxStreamReader.Close()
_sxResponseStream.Close()
_sxResponse.Close()
_sxByteArray = Nothing
_sxPostDataStream = Nothing
_sxRequest = Nothing
_sxResponse = Nothing
_sxResponseStream = Nothing
_sxStreamReader = Nothing
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "response(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "request(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
'-> Tidy Up
_sxHost = Nothing
_sxEndpoint = Nothing
_sxNameValCol = Nothing
_sxResponseCol = Nothing
_sxCounta = Nothing
_sxParamsString = Nothing
'
End Function

OK, so it's now clear that you're not getting any response from the server because your server isn't able to connect to PayPal's servers at all. Hence, you got no server-response and the message Unable to connect to the remote server. When I tested, I got a HTTP 200 response with the following body:
TIMESTAMP=2015-07-07T09:07:39Z&CORRELATIONID=7f4d2313c9696&ACK=Failure&VERSION=93.0&BUILD=17276661&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Authentication/Authorization Failed&L_LONGMESSAGE0=You do not have permissions to make this API call&L_SEVERITYCODE0=Error
Obviously that's because I tested with a blank username and password.
So, something is wrong with your server setup that's preventing you from making outside connections, either at the IIS level or due to your firewall configuration.
Without physically being present at your machine, there's not a lot we can do to track down what's blocking it, but you can try opening HTTP requests to other public websites like Google.com and see if those succeed.

Related

Authenticating using OATH2 on Azure app registration works fine on IIS express, but fails in IIS

I have an application that I am trying to add a layer of SSO, authenticating against Azure AD app registration. The code works fine running in IIS Express, but fails with a 400 Bad Request whenever I attempt to run it from any IIS environment, including localhost.
I have a working function that requests an authorisation code, which works with no issues and the code is returned in the querystring. The issue happens in the next stage, where I use that code to retrieve the user's Sub ID from Microsoft. This is the code I have:
'Get the base azure values
Dim AzureClient As String = ClientInfo
Dim AzureSecret As String = AzureSecret
Dim AuthRedirectUri As String = "The address of the page"
Dim TenantID As String = AzureTenantID
Dim codeVerifier = Verifier string passed in earlier function
Dim httpWReq As HttpWebRequest = DirectCast(WebRequest.Create("https://login.microsoftonline.com/" & TenantID & "/oauth2/v2.0/token"), HttpWebRequest)
httpWReq.Method = "POST"
httpWReq.Host = "login.microsoftonline.com"
httpWReq.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = "client_id=" & AzureClient
postData += "&scope=openid&20email&20profile"
postData += "&code=" & Code
postData += "&redirect_uri=" & AuthRedirectUri
postData += "&grant_type=authorization_code"
postData += "&code_verifier=" & codeVerifier
postData += "&client_secret=" & AzureSecret
Dim encoding As New ASCIIEncoding()
Dim byteArray As Byte() = encoding.GetBytes(postData)
' Set the ContentLength property of the WebRequest.
httpWReq.ContentLength = byteArray.Length
Using streamWriter = New StreamWriter(httpWReq.GetRequestStream())
streamWriter.Write(postData)
End Using
' Get the response.
Dim response As WebResponse = httpWReq.GetResponse() <--- This is where the 400 Bad Request is thrown in IIS, but not IIS Express
Dim responseString As String = New StreamReader(response.GetResponseStream()).ReadToEnd()
Dim o As OAuth2AccessTokenReponse = DirectCast(JsonConvert.DeserializeObject(responseString, GetType(OAuth2AccessTokenReponse)), OAuth2AccessTokenReponse)
Dim IDToken As String = o.id_token
Dim stream = IDToken
Dim handler = New JwtSecurityTokenHandler()
Dim jsonToken = handler.ReadToken(stream)
Dim tokenS = TryCast(jsonToken, JwtSecurityToken)
Dim subID = tokenS.Claims.First(Function(claim) claim.Type = "sub").Value
Return subID
I've compared the calls coming from both environments and they are identical. I have both localhost addresses (localhost IIS address and IIS Express port) so the only differences are the port numbers used in the redirect URI field.
Does anyone have any idea what could be throwing this?
Problem sorted. After much, much digging about I found that IIS was still supporting TLS1.0 - removed that and everything works fine now.

SagePay RedirectURL failure

Using server integration and .net, I post the original request to SagePay and get the NextURL fine, and so go to the payment pages... step through them OK, but then I get the error:
Server error 5006: Unable to redirect to Vendor's web site. The Vendor failed to provide a RedirectionURL.
HTTP error 500: The request was unsuccessful due to an unexpected condition encountered by the server.
But I am sending a RedirectionURL (though the docs call is RedirectURL, which is somewhat confusing - anyway, I've tried using both. This si what I'm sending back from my NotificatioURL - what's wrong?
Dim sb As New StringBuilder
sb.Append("Status=OK")
sb.Append("&StatusDetail=Fine")
sb.Append("&RedirectURL=https://mydomain.co.uk/sagepay.aspx")
Dim urlTEST As String = "https://test.sagepay.com/gateway/service/vspserver-register.vsp"
Dim urlLIVE As String = "https://live.sagepay.com/gateway/service/vspserver-register.vsp"
Try
Dim data As Byte() = Encoding.UTF8.GetBytes(sb.ToString)
Dim request As WebRequest = WebRequest.Create(urlTEST)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = data.Length
ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateRemoteSSLCertificate
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim stream = request.GetRequestStream()
stream.Write(data, 0, data.Length)
stream.Close()
Dim response As WebResponse = request.GetResponse()
response.Close()
Catch ex As Exception
'log error
End Try
Update: I gather this POST (unlike the initial one with the basket info) requires that the data be sent plain text key-value pairs separated by CrLf's, so I amended this to
Dim sb As New StringBuilder
sb.AppendLine("Status=OK")
sb.AppendLine("StatusDetail=Fine")
sb.Append("RedirectURL=https://mydomain.co.uk/sagepay.aspx")
but it still fails with the same errors. I also tried using, instead of the WebRequst class, the simpler:
Dim client As WebClient = New WebClient()
Dim reply As String = client.UploadString(urlTEST, sb.ToString)
But still no joy. Also tried changing the request.ContentType to "text/plain", but nope.
Come on, someone, please - this si basic to the their operations, someone must have done it....
Blimey - it never pays to be clever. This script doesn't require WebRequest or anything, just write to the simple Response object. Sigh.. as Linus said ....

vb.net multiple webproxy in httpwebrequest

I am currently working on a VB.net project where I need to get http responses from a certain URI but the requests needs to go through http proxy which I am perfectly fine with. The problem occurred when I realised sometimes our proxy servers are not working and then the application throws an error. I want my app to check whether the proxy is working or not, if not then I want it to take another proxy from the proxy list/array. And also, please feel free to share if you have any alternative ideas.
Currently I am using this (which is static and when it throws an error I need to manually change the proxy):
Dim proxyObject As WebProxy = New WebProxy("192.168.0.10:80")
request.Proxy = proxyObject
What I want is something like this:
If WebProxy("192.168.0.10:80") is working fine Then
Execute the response
Else
Take the next proxy address from the list/array and go back to the starting
of "If"
End If
FYI: my proxies doesn't require authentication.
I apologise if I couldn't explain it properly and to be honest I'm fairly new in VB.net.
Thanks a lot for your time and patience. Appreciate your help.
Borrowing from this question
Dim urlList As New List(Of String) 'Urls stored here
For each urlString as string in urlList
If CheckProxy(urlString) Then
'Execute the response
else
Continue For 'or something else here, mark it as bad?
End If
next
Public Shared Function CheckProxy(ByVal Proxy As String) As Boolean
Dim prx As Uri = Nothing
If Uri.TryCreate(Proxy, UriKind.Absolute, prx) Then
Return CheckProxy(prx)
ElseIf Uri.TryCreate("http://" & Proxy, UriKind.Absolute, prx) Then
Return CheckProxy(prx)
Else
Return False
End If
End Function
Public Shared Function CheckProxy(ByVal Proxy As Uri) As Boolean
Dim iProxy As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
iProxy.ReceiveTimeout = 500 : iProxy.SendTimeout = 500
Try
'' Connect using a timeout (1/2 second)
Dim result As IAsyncResult = iProxy.BeginConnect(Proxy.Host, Proxy.Port, Nothing, Nothing)
Dim success As Boolean = result.AsyncWaitHandle.WaitOne(500, True)
If (Not success) Then
iProxy.Close() : Return False
End If
Catch ex As Exception
Return False
End Try
Dim bytData() As Byte, strData As String
Dim iDataLen As Integer = 1024
strData = String.Format("CONNECT {0}:{1} HTTP/1.0{2}{2}", "www.google.com", 80, vbNewLine)
bytData = System.Text.ASCIIEncoding.ASCII.GetBytes(strData)
If iProxy.Connected Then
iProxy.Send(bytData, bytData.Length, SocketFlags.None)
ReDim bytData(1024)
Do
Try
iDataLen = iProxy.Receive(bytData, bytData.Length, SocketFlags.None)
Catch ex As Exception
iProxy.Close() : Return False
End Try
If iDataLen > 0 Then
strData = System.Text.ASCIIEncoding.ASCII.GetString(bytData)
Exit Do
End If
Loop
Else
Return False
End If
iProxy.Close()
Dim strAttribs() As String
strAttribs = strData.Split(" "c)
If strAttribs(1).Equals("200") Then
Return True
Else
Return False
End If
End Function

HttpWebRequest.GetResponse does not return AutoID for server side controls

In .NET by default the client side ID's, for server side controls, get concatenated with generated text.
For example:
<asp:TextBox ID="txtUser" runat="server">
would become...
<input type="text" id="ctl00_body_txbUser">
However when I use HttpWebRequest.GetResponse(objReq.Getresponse, HttpWebResponse) to request the same page the item comes back without the auto generated text.
<input type="text" id="txbUser">
Is it possible to use an HttpWebRequest object and GetResponse in such a way that it returns a response with the Auto generated ID's .NET uses for server side controls?
I am working with a 3rd party that has previously set up translation rules specific to ID, now we are attempting have the same rules work against an API call passed a string generated from the page. However, the string generated from the page does not have the same IDs.
Below is code being used to return the Web Page as a string.
Public Shared Function GetWebPageAsString(ByVal strURI As String, ByVal strPostData As String) As String
' Declare our variables. '
Dim objHttpRequest As HttpWebRequest
Dim PostBuffer() As Byte
Dim PostDataStream As Stream = Nothing
Dim objHttpResponse As HttpWebResponse = Nothing
Dim objStreamReader As StreamReader = Nothing
Dim strResponseText As String = ""
Try
' Create a new request. '
objHttpRequest = CType(WebRequest.Create(strURI), HttpWebRequest)
objHttpRequest.Timeout = 3000000
objHttpRequest.Method = "POST"
PostBuffer = Encoding.ASCII.GetBytes(strPostData)
objHttpRequest.ContentType = "application/x-www-form-urlencoded"
objHttpRequest.ContentLength = PostBuffer.Length
PostDataStream = objHttpRequest.GetRequestStream
PostDataStream.Write(PostBuffer, 0, PostBuffer.Length)
PostDataStream.Close()
' Get the response to our request as a stream object. '
objHttpResponse = CType(objHttpRequest.GetResponse, HttpWebResponse)
' Create a stream reader to read the data from the stream. '
objStreamReader = New StreamReader(objHttpResponse.GetResponseStream, Encoding.UTF8)
' Copy the text retrieved from the stream to a variable. '
strResponseText = objStreamReader.ReadToEnd()
' Close our objects. '
objStreamReader.Close()
objHttpResponse.Close()
Catch ex As Exception
strResponseText = strURI & " | " & strPostData
Throw (ex)
Finally
If Not objStreamReader Is Nothing Then
objStreamReader.Close()
End If
If Not PostDataStream Is Nothing Then
PostDataStream.Close()
End If
If Not objHttpResponse Is Nothing Then
objHttpResponse.Close()
End If
objHttpRequest = Nothing
PostBuffer = Nothing
PostDataStream = Nothing
objHttpResponse = Nothing
objStreamReader = Nothing
End Try
' Set return value. '
Return strResponseText
End Function
EDIT: Just to Clarify, I need the IDs to continue to be Auto generated by .NET. I understand that I could make them equal by setting the mode to Static. Unfortunately the 3rd Party we are working with has already created the rules for our current pages based on the IDs that were generated by .NET. Requesting the same page using the HTTPRequest object and pushing data into a stream. I am not seeing the Auto Generated IDs anymore, even though its the same page.
Create a clean master page and put your page in it. That should fix the IDs issue.

FTPWebRequest: Transfer from one FTP to another FTP, Destination file corrupt

Here's my agonizing problem. I'm transferring from one FTP (a Dev site) to another FTP (a Test site). Spare me the thoughts of changing this process. It's out of my hands. In any case, here's my method:
Public Function TransferFile(originalFile As String, destinationFile As String) As String
Try
'FileStream for holding the file
Dim uploadRequest As FtpWebRequest = WebRequest.Create(destinationFile)
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile
uploadRequest.Credentials = New NetworkCredential(ftp_user, ftp_pw)
uploadRequest.UseBinary = True
uploadRequest.UsePassive = False
'connect to the server
Dim fileRequest As FtpWebRequest = WebRequest.Create(originalFile)
fileRequest.Method = WebRequestMethods.Ftp.DownloadFile
fileRequest.Credentials = New NetworkCredential(ftp_user, ftp_pw)
fileRequest.UseBinary = True
fileRequest.UsePassive = False
'get the servers response
Dim response As WebResponse = fileRequest.GetResponse()
'retrieve the response stream
Dim stream As Stream = response.GetResponseStream()
CopyStream(stream, uploadRequest.GetRequestStream)
stream.Close()
response.Close()
Return "File transfered"
Catch ex As System.Security.SecurityException
Return ex.Message
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Shared Sub CopyStream(input As Stream, output As Stream)
Dim buffer As Byte() = New Byte(32767) {}
While True
Dim read As Integer = input.Read(buffer, 0, buffer.Length)
If read <= 0 Then
Return
End If
output.Write(buffer, 0, read)
End While
End Sub
This works perfectly for ASPX files and their .vb code behinds. When we try to transfer .DLL files, they show up on the server as 0 bytes, and sometimes actually transfer. The problem is that, despite being the same size as the original, they act as if they are corrupt. Does anyone have a solution?
Just a guess - use BYREF in your sub definition
Public Shared Sub CopyStream(BYREF input As Stream, BYREF output As Stream)
Closing out the output stream and getting a response from the uploadRequest worked.

Resources