After getting the token and payerID from SetExpressCheckOut now I'm looking to actually get the money from the user.
Using the code generated by the paypal function wizard, I'm calling the ConfirmPayment function.
The problem is that the function is called successfully and processes the payment from the user, but then I received a timeout error. So I get their money, and the user gets a time out page. Not the best way to keep customers.
The operation has timed out
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The operation has timed out
Source Error:
Line 313:
Line 314: //Retrieve the Response returned from the NVP API call to PayPal
**Line 315: HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();**
Line 316: string result;
Line 317: using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
I get a timeout on line 315 which originates from the paypal function's HTTPCall function.
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode( BNCode );
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
//Retrieve the Response returned from the NVP API call to PayPal
**HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();** (Line 315)
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
I feel this maybe something with Paypal's server but either ways, it doesn't work and will piss off users if it goes to live. Do you guys have any idea why it would time out all of a sudden? The same HTTPCall is used in SetExpressCheckOut before and works fine.
It seems like there is a variable in the paypalfunctions.cs that dictates the timeout for the page. It was set to 5000 and I simply upped it to 50000 since page loads were taking longer than 5 seconds and were timing out.
Related
I am very new to programming.
I'm setting up a loop that continuously send a POST request to a site through the REST API. The POST request works properly and the way I intend.
I would like to add functionality that requires the response from this post. However, every way of retrieving the response gives me an error:
"An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (400) Bad Request."
As I debug line by line, it seems that the "GetResponse()" line causes this each time, and causes the program to break. If I remove this line, the program works properly and throws no errors.
Hoping someone can assist. Here is what I have written:
string URL= "https:.......";
HttpWebRequest apiCall = (HttpWebRequest)WebRequest.Create(airWatchURL);
apiCall.Method = "POST";
apiCall.Headers.Add(HttpRequestHeader.Authorization, auth);
apiCall.Headers.Add("aw-tenant-code", apiKey);
apiCall.ContentType = "application/json";
apiCall.ContentLength = noBody.Length; //noBody = empty string
Stream c = apiCall.GetRequestStream();
Encoding d = System.Text.Encoding.ASCII;
StreamWriter requestWriter = new StreamWriter(c, d);
requestWriter.Write(noBody);
requestWriter.Close();
WebResponse apiResponse = apiCall.GetResponse(); //This line will return an error.
This will also return the same error:
HttpWebResponse apiResponse = apiCall.GetResponse() as HttpWebResponse;
This will again return the same error:
string status;
using (HttpWebResponse response = apiCall.GetResponse() as HttpWebResponse)
{
status = response.StatusCode.ToString();
}
I just cant seem to correctly call the GetResponse Method.
I'm getting data from Github for my application.
The first 2 OAuth steps are ok, but in the third I got the following error:
"the server committed a protocol violation. Section=ResponseStatusLine ERROR"
This is my code:
protected String WebRequest(string url)
{
url += (String.IsNullOrEmpty(new Uri(url).Query) ? "?" : "&") + "access_token=" + _accessToken;
HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.ServicePoint.Expect100Continue = false;
try
{
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
return responseReader.ReadToEnd();
}
catch
{
return String.Empty;
}
}
The program goes in exception after using the StreamReader object, that returns me the error.
If I follow these instructions The server committed a protocol violation. Section=ResponseStatusLine ERROR , the error turns into "403 forbidden".
When Github used api V2, different from now, there was no problem with this code.
So, can't be a .NET limitation but something connected with Github server.
Any suggestions?
You need to set UserAgent like this:
webRequest.UserAgent = "YourAppName";
Otherwise it will give The server committed a protocol violation. Section=ResponseStatusLine error.
I am using a simple .NET service (asmx) that works fine when invoking via the test form (POST). When invoking via a HttpWebRequest object, I get a WebException "System.Net.WebException: The remote server returned an error: (500) Internal Server Error." Digging deeper, reading the WebException.Response.GetResponseStream() I get the message: "Missing parameter: serviceType." but I've clearly included this parameter.
I'm at a loss here, and its worse that I don't have access to debug the service itself.
Here is the code being used to make the request:
string postData = String.Format("serviceType={0}&SaleID={1}&Zip={2}", request.service, request.saleId, request.postalCode);
byte[] data = (new ASCIIEncoding()).GetBytes(postData);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Timeout = 60000;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = data.Length;
using (Stream newStream = httpWebRequest.GetRequestStream())
{
newStream.Write(data, 0, data.Length);
}
try
{
using (response = (HttpWebResponse)httpWebRequest.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception("There was an error with the shipping freight service.");
string responseData;
using (StreamReader responseStream = new StreamReader(httpWebRequest.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("iso-8859-1")))
{
responseData = responseStream.ReadToEnd();
responseStream.Close();
}
if (string.IsNullOrEmpty(responseData))
throw new Exception("There was an error with the shipping freight service. Request went through but response is empty.");
XmlDocument providerResponse = new XmlDocument();
providerResponse.LoadXml(responseData);
return providerResponse;
}
}
catch (WebException webExp)
{
string exMessage = webExp.Message;
if (webExp.Response != null)
{
using (StreamReader responseReader = new StreamReader(webExp.Response.GetResponseStream()))
{
exMessage = responseReader.ReadToEnd();
}
}
throw new Exception(exMessage);
}
Anyone have an idea what could be happening?
Thanks.
UPDATE
Stepping through the debugger, I see the parameters are correct. I also see the parameters are correct in fiddler.
Examining fiddler, I get 2 requests each time this code executes. The first request is a post that sends the parameters. It gets a 301 response code with a "Document Moved Object Moved This document may be found here" message. The second request is a GET to the same URL with no body. It gets a 500 server error with "Missing parameter: serviceType." message.
It seems like you found your problem when you looked at the requests in Fiddler. Taking an excerpt from http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html:
10.3.2 301 Moved Permanently
The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible.
.....
Note: When automatically redirecting a POST request after
receiving a 301 status code, some existing HTTP/1.0 user agents
will erroneously change it into a GET request.
Here's a couple options that you can take:
Hard-code your program to use the new Url that you see in the 301 response in Fiddler
Adjust your code to retrieve the 301 response, parse out the new Url from the response, and build a new response with the new Url.
The latter option would be ideal if you're dealing with user-based input on the Url (like a web browser), since you don't know where the user is going to want your program to go.
I'm using a function to check if an external url exists. Here's the code with the status messages removed for clarity.
public static bool VerifyUrl(string url)
{
url.ThrowNullOrEmpty("url");
if (!(url.StartsWith("http://") || url.StartsWith("https://")))
return false;
var uri = new Uri(url);
var webRequest = HttpWebRequest.Create(uri);
webRequest.Timeout = 5000;
webRequest.Method = "HEAD";
HttpWebResponse webResponse;
try
{
webResponse = (HttpWebResponse)webRequest.GetResponse();
webResponse.Close();
}
catch (WebException)
{
return false;
}
if (string.Compare(uri.Host, webResponse.ResponseUri.Host, true) != 0)
{
string responseUri = webResponse.ResponseUri.ToString().ToLower();
if (responseUri.IndexOf("error") > -1 || responseUri.IndexOf("404.") > -1 || responseUri.IndexOf("500.") > -1)
return false;
}
return true;
}
I've run a test over some external urls and found that about 20 out of 100 are coming back as errors. If i add a user agent the errors are around 14%.
The errors coming back are "forbidden", although this can be resolved for 6% using a user agent, "service unavialable", "method not allowed", "not implemented" or "connection closed".
Is there anything I can do to my code to ensure more, preferrably all give a valid response to their existance?
Altermatively, code that can be purchased to do this more effectively.
UPDATE - 14th Nov 12 ----------------------------------------------------------------------
After following advice from previous respondants, I'm now in a situation where I have a single domain that returns Service Unavailable (503). The example I have is www.marksandspencer.com.
When I use this httpsniffer web-sniffer.net as opposed to the one recommended in this thread, it works, returning the data using a webrequest.GET, however I can't work out what I need to do, to make it work in my code.
I finally got to the point of bieng able to validate all the urls without exception.
Firstly I took Davios advice. Some domains return an error on Request.HEAD so I have included a retry for specific scenarios. This created a new Request.GET for the second request.
Secondly, the Amazon scenario. Amazon was intermittently returning a 503 error for its own site and permanent 503 errors for sites hosted on the Amazon framework.
After some digging I found adding the following line to the Request resolved both. It is the Accept string used by Firefox.
var request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
I have tried to integrate paypal sandbox with my project in asp.net.
Redirection to paypal sandbox working extremely fine ! You can check out your cart ! You can make payment ! But the problem is when paypal set redirection to my Success.aspx page !
I got the error as
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.101:808
I am using stream writer Object !
Wait Let me post my code !
this is page_load even of Success.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Used parts from https://www.paypaltech.com/PDTGen/
// Visit above URL to auto-generate PDT script
authToken = WebConfigurationManager.AppSettings["PDTToken"];
//read in txn token from querystring
txToken = Request.QueryString.Get("tx");
query = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, authToken);
// Create the request back
string url = WebConfigurationManager.AppSettings["PayPalSubmitUrl"];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = query.Length;
// Write the request back IPN strings
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(query);
stOut.Close();
// Do the request to PayPal and get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
// sanity check
Label2.Text = strResponse;
// If response was SUCCESS, parse response string and output details
if (strResponse.StartsWith("SUCCESS"))
{
PDTHolder pdt = PDTHolder.Parse(strResponse);
Label1.Text = string.Format("Thank you {0} {1} [{2}] for your payment of {3} {4}!",
pdt.PayerFirstName, pdt.PayerLastName, pdt.PayerEmail, pdt.GrossTotal, pdt.Currency);
}
else
{
Label1.Text = "Oooops, something went wrong...";
}
}
}
This sentence creates error !!
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
These type of exception occurs
Exception Details: System.Net.Sockets.SocketException:
A connection attempt failed because the connected party did
not properly respond after a period of time,
or established connection failed because connected
host has failed to respond 192.168.0.101:808
First off, do not mix PDT and IPN - just use IPN. Go into PayPal admin and make sure that the return URL is NOT set there and that PDT is NOT enabled.
There is an IPN class available online just for this purpose - some more info (Caveat: my own blog post):
http://codersbarn.com/?tag=/paypal
http://paypalipnclass.codeplex.com/releases/view/31282