Error while paypal integration - c#

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

Related

HttpWebRequest works with windows form but not with Web API

I need to call HTTPS POST service from WEB API method.
I am using HttpWebRequest to call this API, however i am getting 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 x.x.x.x:443"
When I tried to call this API in Windows Form then it works well.
HttpWebRequest r = null;
HttpWebResponse rsp = null;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
r = (HttpWebRequest)System.Net.WebRequest.Create("url");
String d = "Serialize JSON"
r.Method = "POST";
r.ContentType = "application/json";
StreamWriter wr = new StreamWriter(r.GetRequestStream());
wr.WriteLine(d);
wr.Close();
rsp = (HttpWebResponse)r.GetResponse();
StreamReader reader = new StreamReader(rsp.GetResponseStream());
String dd = reader.ReadToEnd();
Might be because you are trying to use SSL, from the last part - x.x.x.x:443. My understanding is that 443 is used for SSL. Happy for someone to correct me if I incorrect.
Have a look at the following, this may help you out:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/working-with-ssl-in-web-api

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed

I am having an issue :
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 URL.
Also I get issue like:
System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host
and
System.Net.WebException: The operation has timed out at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
I know that this question has asked before but believe me I tried almost every single resolution at my end.
Weird thing is this issue does not appear at my end at all and only when client try to use which is not constant. Some time my application works fine at their end too.
What I am trying to accomplish is I have created an desktop application (Win Forms & C#) and trying to login client while sending request to my php api server which is hosted on GODaddy.
var request = (HttpWebRequest)WebRequest.Create("url");
if (request != null)
{
#region System.Net.WebException
request.Method = "POST";
if (!string.IsNullOrEmpty(body))
{
var requestBody = Encoding.UTF8.GetBytes(body);
request.ContentLength = requestBody.Length;
request.ContentType = "application/json";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestBody, 0, requestBody.Length);
}
}
else
{
request.ContentLength = 0;
}
request.Timeout = 15000;
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
string output = string.Empty;
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1252)))
{
if (response.StatusCode == HttpStatusCode.OK)
{
while (!stream.EndOfStream)
{
output += stream.ReadLine();
}
output = stream.ReadToEnd();
}
}
}
}
catch
{
// Excaption Caught here
}
}
Please help me out.
Thanks in advance.
Try adding this...
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ServicePoint.ConnectionLimit = 12;
MSDN article recommends 12 connections per CPU hence the limit of 12 because it's hosted by GoDaddy so I'm sure the server resources are limited.
I think I got the answer. Thought to post it so that it could help anyone else.
It most probably the particular machine issue or server issue but in my case, I tried to set Request.proxy = null and it worked like a charm.
I faced this problem at today. I set Timeout property of HttpWebRequest to 1 200 000 milliseconds (20 minute), but I got this error after 5 minute. I researched many sites at google and I found ReadWriteTimeout property of HttpWebRequest. Default value of ReadWriteTimeout is 5 minute. I increased value of ReadWriteTimeout and problem solved for me.
...
httpWebRequest.Timeout = 1200000;
httpWebRequest.ReadWriteTimeout = 1200000;
...

PayPal Instant Payment Notification (IPN) not working ASP.NET C#

I'm trying to get IPN working for my site but until now without any success.
I've red all PayPals documentation and i've setted up all the requires configurations to get IPN working.
Here's what i have done so far:
1. Created a dev account;
2. Updated my Website Payment Preferences to Auto Return: On;
3. Turned on Instant payment notifications in my profile properties;
4. Created a test payment option event:
protected void btCheckout_Click(object sender, EventArgs e)
{
var queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["cmd"] = "_cart";
queryString["business"] = "xpto-facilitator#xpto.com";
queryString["upload"] = "1";
queryString["item_name_1"] = "My Cart Item 1";
queryString["quantity_1"] = "1";
queryString["amount_1"] = "100.00";
queryString["shopping_url"] = "http://xpto.com/Client/Checkout";
queryString["return"] = "http://xpto.com/Client/Checkout";
queryString["notify_url"] = "http://xpto.com/CheckoutResult.aspx";
Response.Redirect("https://www.sandbox.paypal.com/cgi-bin/webscr?" + queryString.ToString());
}
5. Created a IPN page:
protected void Page_Load(object sender, EventArgs e)
{
//Post back to either sandbox or live
string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
strRequest += "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED")
{
//log for debugging purposes
LogManager.Error("CheckoutResult VERIFIED:" + strResponse);
}
else if (strResponse == "INVALID")
{
//log for debugging purposes
LogManager.Error("CheckoutResult INVALID: " + strResponse);
}
else
{
//log for debugging purposes
LogManager.Error("CheckoutResult something else: " + strResponse);
}
}
I manage to proceed with the checkout and successfully paid the items;
My IPN page wasn't executed because i don't have anything logged;
Tested my handler with the Instant Payment Notification (IPN) simulator and i always get the following error:
We could not send an IPN due to an HTTP error: 401: Unauthorized
What am i doing wrong? Am i missing anything?
The notify_url you're specifying for IPN is set to an endpoint that requires a login.
queryString["notify_url"] = "http://xpto.com/CheckoutResult.aspx";
This URL must be set to an endpoint that can accept and process POST requests from the IPN service without any login being required (I can't seem to find any documentation that specifically mentions this requirement). This is the primary reason why the IPN received by your listener must then be verified (which you look to be doing correctly) because prior to verification there's no way to fully trust the received request was sent by PayPal.

DoExpressCheckoutPayment processes payment and then times out

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.

How to fix this error call google location to address Service "target machine actively refused it"

When trying to call Google location to address Service, it gives me this message:
No connection could be made because the target machine actively
refused it 173.194.66.95:80
I use ASP.net 4 with C#.
This is my code:
protected void btn_FindAddress_Click(object sender, EventArgs e)
{
url = "http://maps.googleapis.com/maps/api/geocode/xml?latlng=";
query = LatY.Text + "," + LongX.Text + "&sensor=true";
Address.Text = url;
Uri uri = new Uri (url + query);
// Create a request for the URL.
WebRequest request = WebRequest.Create(uri);
//// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Status.Text = (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Address.Text = responseFromServer;
// Clean up the streams and the response.
reader.Close();
response.Close();
}
Most commonly, the outbound connection can be established (the remote server could be reached and a response was sent in a timely fashion) but the port you're trying to use is being blocked (a firewall or a proxy are the two most likely options I can think of).
It also might derive from the fact that there is no server on the other side of the connection: this may happen for example if you NAT port 80 to a system which doesn't have a web server. Being that you're invoking Google's url, I doubt it's the case, but I thought it worth of pointing out.

Categories