SagePay RedirectURL failure - asp.net

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 ....

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.

WP Rest API - Upload image to WP using Restsharp

I have a problem uploading an image to Wordpress from a VB .NET project (using Restsharp). I create the client and the request for this, I added a header with the authorization, parameters...) but, when I execute the request, this response Status OK (200) but the image has not create in Wordpress.
I tried all this sentences, and no works:
Test 1:
Dim client As RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request As RestRequest = New RestRequest(Method.POST)
request.AddHeader("Authorization", "Basic {base64code}")
request.AddHeader("Cookie", "PHPSESSID=b83jbtsfjbb2bkkso7s75m75il")
request.AddHeader("Content-Disposition", "attachment; filename=Google-logo.jpg")
request.AddHeader("Content-Type", "image/jpeg")
request.AddFile("file", "C:\temp\Google-logo.jpg")
request.AddParameter("title", "titleExample")
request.AddParameter("caption", "captionExample")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.StatusCode)
Test 2:
Dim client As RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request As RestRequest = New RestRequest(Method.POST)
request.AddHeader("Authorization", "Basic {base64code}")
request.AddHeader("Cookie", "PHPSESSID=b83jbtsfjbb2bkkso7s75m75il")
request.AddParameter("title", "titleExample")
request.AddParameter("caption", "captionExample")
request.AlwaysMultipartFormData = True
request.AddParameter("file", "C:\temp\Google-logo.png")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.StatusCode)
Test 3:
Dim client as RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request = New RestRequest(Method.POST)
request.RequestFormat = DataFormat.Json
request.AddHeader("Authorization", "Basic {base64code}")
request.AddFileBytes("file", BytesImage, "C:\temp\Google-logo.jpg", "image/jpeg")
request.AddParameter("title", "tempFile")
request.AddParameter("caption", "tempFileCaption")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.Content)
Test 4: In this example I not use RestSharp, I used the HttpWebRequest, and the same result
Dim myReq As HttpWebRequest
Dim myResp As HttpWebResponse
myReq = HttpWebRequest.Create("http://domain-example.com/wp-json/wp/v2/media")
myReq.Method = "POST"
myReq.ContentType = "application/json"
myReq.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("user:password")))
Dim myData As String = "c:\temp\Google-logo.jpg"
myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)
myResp = myReq.GetResponse
Dim myreader As New System.IO.StreamReader(myResp.GetResponseStream)
Dim myText As String
myText = myreader.ReadToEnd
I tried to simulate the upload using Postman, but I can't.
I don't know why it's so hard to upload an image to Wordpress using REST...
Disclaimer:
Also, this post doesn't work for me
The following is from the docs.
To add a file to the request you can use the RestRequest function called AddFile. The main function accepts the FileParameter argument:
request.AddFile(fileParameter);
You can instantiate the file parameter using FileParameter.Create that accepts a bytes array or FileParameter.FromFile, which will load the file from disk.
There are also extension functions that wrap the creation of FileParameter inside:
// Adds a file from disk
AddFile(parameterName, filePath, contentType);
// Adds an array of bytes
AddFile(parameterName, bytes, fileName, contentType);
// Adds a stream returned by the getFile function
AddFile(parameterName, getFile, fileName, contentType);
Remember that AddFile will set all the necessary headers, so please don't try to set content headers manually. Your code sets a lot of content headers, and it's unnecessary, and might be breaking your requests.
You can always use https://requestbin.com and send your requests there to inspect the content of those requests, so you can see if they match the expected request format.
In test 1, remove or comment out this line of code:
request.AddHeader("Content-Type", "image/jpeg")
The solution for this is activate the JWT authentication plugin for Wordpress. By default, Wordpress avoid any POST call, the basic authentication doesn't work.
So, once activated the JWT (following the process), you must create a Token (using POST to the JWT endpoint) and put the Token in the POST process to create anything (posts, media, etc.)

Problems With Paypal Express Checkout Integration (WEBREQUEST)

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.

ASP.Net delay, how can I tell if it is the client or the server?

I've got a generic handler on a site. When I go directly to it it responds immediately. When I try to get to it from a .Net program, there is a long (10 second give or take) pause before the server is registering the request.
Here is the code I'm using to hit the server:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://MYURL/fs.ashx");
request.Method = "POST";
request.ContentType = "text/xml";
// This is the line that takes 10 seconds to return
StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(sXMLToSend);
streamOut.Close();
XmlDocument doc = new XmlDocument();
HttpWebResponse resp = null;
resp = (HttpWebResponse)request.GetResponse();
StreamReader responseReader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
sResponse = responseReader.ReadToEnd();
Console.WriteLine(sResponse);
resp.Close();
I don't think that this line was taking that long about a week ago, but I don't have any data to back that up. Any ideas what the issue could be? If I hit the url in a browser it responds immediately. Are there any tools that I can use to figure out if it is my machine, or the server, or...I don't even know where to begin.
Might it just be due to the fact that GetRequestStream is a synchronous method and its buffering it all up before returning? Maybe you should try calling the async version and process data as it comes in.

Send HTTP Command using VB.NET

I'm trying to send an HTTP command using VB.NET and I'm not quite sure how to do it. I don't want to actually navigate to the page, just execute the command.
http://xbmc.local/xbmcCmds/xbmcHttp?command=ExecBuiltIn&parameter=XBMC.updatelibrary%28video%29
What I'm doing is building an integrated interface for my XBMC home theater, and my home automation.
You can use the WebRequest object to send an HTTP Request.
' Create a WebRequest object with the specified url. '
Dim myWebRequest As WebRequest = WebRequest.Create(url)
' Send the WebRequest and wait for response. '
Dim myWebResponse As WebResponse = myWebRequest.GetResponse()
The WebResponse class has a number of properties you can check to see if the request succeeded or not. And just something to be aware of, GetResponse() will throw an exception if it times out.
Try the following
Dim client = WebRequest.Create("http://xbmc.local/xbmcCmds/xbmcHttp?command=ExecBuiltIn&parameter=XBMC.updatelibrary%28video%29")
Dim response = client.GetResponse()

Resources