INVALID paypal ipn response however [duplicate] - asp.net

This question already exists:
PayPal IPN Sandbox response always INVALID
Closed 9 years ago.
I am using sandbox mode. I have a buy now button in sandbox mode linked to my sandbox business account which has ipn enabled with the url to my site. The ipn implementation is exactly the same as the sample code here: https://cms.paypal.com/cms_content/GB/en_GB/files/developer/IPN_ASP_NET_C.txt
I click the button and make a purchase using a sandbox personal account which is successful. it shows up as sent with code 200 in the business accounts ipn history but on the ipn page on my site the response is invalid.
Been at this for days now.. cant figure it out :(

Here's what I'm using for https://ASPSecurityKit.net
private void ProcessPayment(bool test)
{
try
{
string callbackResponse = null;
string content = null;
string callbackUrl = test ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
var req = (HttpWebRequest) WebRequest.Create(callbackUrl);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
content = Encoding.ASCII.GetString(
Request.BinaryRead(HttpContext.Request.ContentLength)
);
content += "&cmd=_notify-validate";
req.ContentLength = content.Length;
using (var streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(content);
}
using (var streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
callbackResponse = streamIn.ReadToEnd();
}
if (callbackResponse.Equals("VERIFIED", StringComparison.OrdinalIgnoreCase))
{
// Now validate whether gross_amount is ok, receiver_email is your business acount mail id and so on.
}
}
catch (Exception ex)
{
// Logger.Log(ex); // Uncomment this line if you have a logger
}
}
Note: I store all transactions in the database whether varified or invalid. That logic is ASPSecurityKit.net specific hence I have omitted that here.

Related

Service Worker file offline events

Google Chrome latest(v55.0.2883.87)
There are various event in that (sw.js)file. Everytime a file got requested fetch event occur. How and when other events occur(sync, push)(web notification api). I want to debug it. Is there any doc available?
Update:
server-key-from-firebase-console
subscription-key-after-subscribing-web-notification
Found how push notification fired--
String url = "https://fcm.googleapis.com/fcm/send";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "key=<server-key-from-firebase-console>");
con.setRequestProperty("Content-Type", "application/json");
String urlParameters = "{\"to\":\"<subscription-key-after-subscribing-web-notification>\"}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
Update 2:
Ok now i found how to fire a sync event in service worker file either from google chrome debugger tool or from javascript. Below is the code, what i have found on google's blog post.
// Register your service worker:
navigator.serviceWorker.register('/sw.js');
// Then later, request a one-off sync:
navigator.serviceWorker.ready.then(function(swRegistration) {
return swRegistration.sync.register('myFirstSync');
});
Then listen for the event in /sw.js:
self.addEventListener('sync', function(event) {
if (event.tag == 'myFirstSync') {
event.waitUntil(doSomeStuff());
}
});
A good resource for knowing more about ServiceWorker is MDN (Mozilla Developer Network).
Here is the entry point to the documentation related to ServiceWorker:
https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
There you have links and explanations for the install, fetch, sync and push events. And the new ones that will appear like background sync will be documented there too.
Happy reading.

Getting Facebook Page Feed ( using graph api ) in asp.net, receiving error "Unsupported Browser"

I am trying to get facebook page feed ( public posts) which does not require any access token.
here's the url
https://www.facebook.com/feeds/page.php?format=json&id=1393547494231876
when i run this in browser where id= any facebook page id. it returns first 25 public posts in json format.
but when i run this in my code to get json result facebook return a page saying "unsupported browser"
this is my method . i pass it facebook page id to get posts..
public static String GetPosts(string PageId)
{
string id = PageId;
string apilink = "https://www.facebook.com/feeds/page.php?format=json&id=";
HttpWebRequest request = WebRequest.Create(apilink + id) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
String result = reader.ReadToEnd();
return result;
}
}
Here's the result that i get in return string
Result Image String
and so on remaining page returned.
Can somebody help me how to get it working??
Update
Found Answer...
I Have To Set User agent to make Facebook think i am a browser..
so just added
request.UserAgent = ".NET Framework";
and i worked.
Thanks to All.
Found Answer... I Have To Set User agent to make Facebook think i am a browser.. so just added request.UserAgent = ".NET Framework"; and i worked. Thanks to All.

ASP.NET Why is this shortening url code redirecting to page

Hey I have the following method
public static string GetShortenedURL(String inURL)
{
String shortURL = "";
String queryURL = "http://api.bit.ly/shorten?version=2.0.1&longUrl=" + inURL + "&login=&apiKey=";
HttpWebRequest request = WebRequest.Create(queryURL) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string jsonResults = reader.ReadToEnd();
int indexOfBefore = jsonResults.IndexOf("shortUrl\": \"") + 12;
int indexOfAfter = jsonResults.IndexOf("\"", indexOfBefore);
shortURL = jsonResults.Substring(indexOfBefore, indexOfAfter - indexOfBefore);
}
return shortURL;
}
Which worked fine on my development machine, but on live server for some reason whenever I call this method I actually seems to visit the URL aswell. The reason why this is a problem is because that URL updates a status of a record. But I only want to do this when the user clicks on the link in the mail but for some very weird reason when Im creating the email on my confirmation page of registration and call this shortened URL method so I can add the short URL in my mail to send out,
it seems to visit it by itself. Hence updating my status when it shouldnt yet.
Any Ideas ?
EDIT : This is how i call it
emailBody.Append(M1Utils.GetShortenedURL(ConfigurationSettings.AppSettings["strSite_FEURL"].ToString() + "login/verify.aspx?" + strEncrypted)).Append("\r\n\r\n");

Adding Google Calendar entry without using setUserCredentials

I am following the example provided by Google for Market place app at
http://code.google.com/googleapps/marketplace/tutorial_dotnet.html
I got the google authentication working as in the example ,
My next task is to add a entry to Google calendar. I found following code for that, and it is also working fine
CalendarService service = new CalendarService(APPLICATION_NAME);
service.setUserCredentials(vUserName, vPassword);
Google.GData.Calendar.EventEntry entry = new Google.GData.Calendar.EventEntry();
// Set the title and content of the entry.
entry.Title.Text = title;
entry.Content.Content = contents;
// Set a location for the event.
Where eventLocation = new Where();
eventLocation.ValueString = location;
entry.Locations.Add(eventLocation);
When eventTime = new When(startTime, endTime);
entry.Times.Add(eventTime);
Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
// Send the request and receive the response:
AtomEntry insertedEntry = service.Insert(postUri, entry);
The problem i have is the following line, If i give my username and password it will work
service.setUserCredentials(vUserName, vPassword);
i have authenticated the user as in google example. So I don’t know the username and password of other users login to my site using their gmail.
How do i add a calender entry with the information i have?
I have seen several examples with RequestFactory authenticating the user. but couldn't find complete example that I can use
you will need to create a .pfx cert file and upload it to google and place it on your server.
create your AuthSubRequest URL
<asp:HyperLink ID="GotoAuthSubLink" runat="server"/>
GotoAuthSubLink.Text = "Login to your Google Account";
GotoAuthSubLink.NavigateUrl = AuthSubUtil.getRequestUrl("(return url)http://www.example.com/RetrieveToken", "https://www.google.com/calendar/feeds/", false, true);
after the person clicks on your auth link they are returned to your return url. get your session token as follows
String sessionToken = ""; //Save this for making your calls.
String certFile = "D:\\websites\\yourwebsite.com\\google.pfx";
String result = GetAuthSubSessionToken(Request["token"]);
protected AsymmetricAlgorithm GetRsaKey()
{
X509Certificate2 cert = new X509Certificate2(certFile, "");
RSACryptoServiceProvider privateKey = cert.PrivateKey as RSACryptoServiceProvider;
return privateKey;
}
public string GetAuthSubSessionToken(string singleUseToken)
{
string gatStr = "";
try
{
AsymmetricAlgorithm rsaKey = GetRsaKey();
try
{
sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, rsaKey).ToString();
gatStr = "Session Token = " + SessionToken;
}
catch (Exception e)
{
gatStr = "Error: I appears that the Google authentication server is experiencing an error. Try the authorizaton link again in a few minutes. <a href=\""
+ rtnUrl + "\" title=\"" + e.Message + "\">continue</a>";
}
}
catch (Exception E)
{
gatStr = "Error: rsa " + E.Message + E.StackTrace;
}
return gatStr;
}
save the session token and use CreateCalendarService in subsequent calls to create your calendar service.
public CalendarService CreateCalendarService()
{
GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "YourName-calendarApp-1");
authFactory.Token = sessionToken;
authFactory.PrivateKey = GetRsaKey();
CalendarService cs = new CalendarService(authFactory.ApplicationName);
cs.RequestFactory = authFactory;
return cs;
}

Google Checkout HTTP Post with ASP.net

I have 2 pages I created in ASP.net(C#). The first one(called shoppingcart.asp) has a buy it now button. The second one(called processpay.asp) just waits for google checkout to send an HTTP request to it to process the payment. What I would like to do send a post statement to google checkout with a couple of variables that I want passed back to processpay.asp(ie clientid=3&itemid=10), but I don't know how to format the POST HTTP statement or what settings I have to change in google checkout to make it work.
Any ideas would be greatly appreciated.
Google Checkout has sample code and a tutorial on how to integrate it with any .NET application:
Google Checkout API - Google Checkout Sample Code for .NET
Make sure to check the section titled: "Integrating the Sample Code into your Web Application".
However, if you prefer to use a server-side POST, you may want to check the following method which submits an HTTP post and returns the response as a string:
using System.Net;
string HttpPost (string parameters)
{
WebRequest webRequest = WebRequest.Create("http://checkout.google.com/buttons/checkout.gif?merchant_id=1234567890");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{
webRequest.ContentLength = bytes.Length;
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch (WebException e)
{
// handle e.Message
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{
// get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{
return null;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException e)
{
// handle e.Message
}
return null;
}
Parameters need to be passed in the form: name1=value1&name2=value2
The code will likely end up looking something like this:
GCheckout.Checkout.CheckoutShoppingCartRequest oneCheckoutShoppingCartRequest =
GCheckoutButton1.CreateRequest();
oneCheckoutShoppingCartRequest.MerchantPrivateData = "clientid=3";
GCheckout.Checkout.ShoppingCartItem oneShoppingCartItem =
new GCheckout.Checkout.ShoppingCartItem();
oneShoppingCartItem.Name = "YourProductDisplayName";
oneShoppingCartItem.MerchantItemID = "10";
oneCheckoutShoppingCartRequest.AddItem(oneShoppingCartItem);
Yesterday I used http://www.codeproject.com/KB/aspnet/ASP_NETRedirectAndPost.aspx to send the post data and it works fine

Resources