Google Checkout HTTP Post with ASP.net - 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

Related

INVALID paypal ipn response however [duplicate]

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.

check URL exists or throws page not found message in asp.net

I want to validate an url, whether it exists or throwing page not found error. can anyone help me how to do it in asp.net.
for e.g., my url may be like http://www.stackoverflow.com or www.google.com i.e., it may contain http:// or may not. when i check, it should return the webpage valid if exists or page not found if doesnot exists
i tried HttpWebRequest method but it needs "http://" in the url.
thanks in advance.
protected bool CheckUrlExists(string url)
{
// If the url does not contain Http. Add it.
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}
Try this
using System.Net;
////// Checks the file exists or not.
bool FileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if it Exist
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false. So the URL is Not Exist
return false;
}
}
Hope I Helped

How to do httpPost to a webservice which accepts a byte array of a file using c#

I am working on an API kind of project,
I have wrote a WebMethod (not exactly. I am using MVC to create REST like API)
public UploadFileImage(string employeeId, byte[] imageBytes, string imageName)
{
// saves the imagebyte as an image to a folder
}
the web service would be consumed by a web app, or windows or even iphone or such portable stuffs. I am testing my web service using a web app, by simple httpPost.
string Post(Uri RequestUri, string Data)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(RequestUri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = IsXml.Checked ? "text/xml" : "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes(Data);
Stream os = null; // send the Post
request.ContentLength = bytes.Length; //Count bytes to send
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
return streamReader.ReadToEnd();
}
catch (Exception ex)
{
return ex.Message;
}
}
This code works fine for evey method like, AddEmployee, DeleteEmployee etc. THe parameter Data is of form "Id=123&name=abcdefgh&desig=Developer",
How I call any other function is
Post(new Uri("http://localhost/addemployee"),"name=abcd&password=efgh")
where post is the function i wrote.
All good for all functions. Except that I dont know how to consume the above mentioned function UploadFileImage to upload an image?
Thanks
Try encoding the imageBytes as Base64.
From your code snippet is not too clear how you call UploadFileImage, that is how you convert its parameters tripplet into Data.
That is why my answer is quite generic:
In general, you'd better transfer your image file by
request.ContentType = "multipart/form-data; boundary=----------------------------" + DateTime.Now.Ticks.ToString("x");
Please allow me to refer you to a sample at StackOverflow on how to format a multipart request. I am sure that if you google, you shall find a lots of detailed examples and explanations as well.
I hope this helps :-)

User authentication through REST web service on a different domain - asp.net

I am looking to connect to a web service on a different domain in order to authenticate users. The Web Service itself is a RESTful service, written in Java. Data is passed to and from it in JSON.
I initially tried to connect using jQuery (see below)
function Login()
{
$.ajax({
url: "http://www.externaldomain.com/login/authenticate",
type: "POST",
dataType: "json",
contentType: "application/json",
data: "{'emailAddress':'bob#bob.com', 'password':'Password1'}",
success: LoadUsersSuccess,
error: LoadUsersError
});
}
function LoadUsersSuccess(){
alert(1);
}
function LoadUsersError(){
alert(2);
}
However, when checking on Firebug, this brought up a 405 Method Not Allowed error.
At this stage, as this is the first time I've really worked with web services, I really just wondered whether this was the best way to do things? Is it worth persevering with this method in order to find a solution, or am I best to maybe try and find a server-side answer to this issue? If so, does anyone have any examples they could post up?
Many thanks
Doing cross-domain web service calls in a browser is very tricky. Because it's a potential security vulnerability, browsers block these types of requests. However, there is a workaround called JSONP. If you use JSONP instead of plain JSON, you should be able to make the cross-domain request.
Right ok, to update where I am, I checked in firebug and on the external server and the reason why I'm getting a 405 error is because I'm doing a Get rather than a Post.
What I need to do is send the username and password, then receive a GUID back which will then be used for any future requests. I thought by having 'type:post' in the code would be enough but apparently not. Anyone know where I might be going wrong here? As I said, a novice to web services and nothing I have tried from looking online has had any effect. Many thanks
Ok, I got the problem solved, and I did it by going back to C# and doing it there instead of using jQuery or JSONP and I used Json.Net for handling the data received. Here is the code:
protected void uxLogin_Click(object sender, EventArgs e)
{
StringBuilder data = new StringBuilder();
data.Append("{");
data.Append("'emailAddress': '" + uxEmail.Text + "', ");
data.Append("'password': '" + uxPassword.Text + "'");
data.Append("}");
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
string url = System.Configuration.ConfigurationManager.AppSettings["AuthenticationURL"].ToString();
string JSONCallback = string.Empty;
Uri address = new Uri(url);
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";
// Create a byte array of the data we want to send
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
JSONCallback = reader.ReadToEnd().ToString();
}
if (!String.IsNullOrEmpty(JSONCallback))
{
JObject jObject = JObject.Parse(JSONCallback);
if ((bool)jObject["loginResult"] == false)
{
string errorMessage = jObject["errorMessage"].ToString();
int errorCode = (int)jObject["errorCode"];
}
else
{
string idToken = jObject["idToken"].ToString();
Session["Userid"] = idToken;
Response.Redirect("~/MyDetails.aspx");
}
}
else
{
uxReturnData.Text = "The web service request was not successful - no data was returned";
}
}
Thanks anyway :)

How do I make a simple post to Twitter via ASP.NET (VB, preferably)?

I don't want to do anything fancy on Twitter except post to it via my site once a day. I have searched around a bit and there are all sorts of super-complex ways to do every little thing that Twitter does, but there seems to be little documentation on how to do the simplest thing, which is make a post!
Does anyone know how to do this? Or can you at least point me in the right direction? I don't need full wrappers or anything (http://apiwiki.twitter.com/Libraries#C/NET), just one simple function that will post to Twitter.
Thanks!
This is the easiest implementation ever. Up and running in under 2 minutes: Twitterizer
Its fairly simple; you just need to post an xml file to a web page using webrequest.create. This example is close (assumes you have the xml for the message in another place and just pass it into twitterxml variable as a string. The url might not be the right one; found it on this [page][1] which defines the interface
WebRequest req = null;
WebResponse rsp = null;
try
{
string twitterXML = "xml as string";
string uri = "http://twitter.com/statuses/update.format";
req = WebRequest.Create(uri);
//req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
req.Method = "POST"; // Post method
req.ContentType = "text/xml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(twitterXML);
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
}
[1]: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses update
There are a couple different ways of doing this, they vary depending on the tools you want to use and have access to. Option 1 will work right out of the box, but the coding can be complicated. Option 3 you will have to download tools for, but once there installed and loaded you should be able to consume the twitter api very quickly.
Use WebRequest.Create to create/send messages to remote endpoints
Use WCF, create a mirror endpoint and access the twitter api using client only endpoint.
Use the WCF REST Starter Kit Preview 2, which has a new class called the HttpClient. I would have to recommend this technique if you can. Here is a great video Consuming a REST Twitter Feed in under 3 minutes.
Here is a sample of using the WCF REST Starter Kit's HttpClient:
public void CreateFriendship(string friend)
{
using (var client = new HttpClient())
{
var url = string.Format("http://www.twitter.com/friendships/create/{0}.xml?follow=true", friend);
client.Post(url)
.CheckForTwitterError()
.EnsureStatusIs(HttpStatusCode.OK);
}
}
Add a comment if you'd like more info about a particular method.
Update:
For Option #1 see this question: Remote HTTP Post with C#
There are a few ways of doing this, you can check out http://restfor.me/twitter and it will give you the code from RESTful documentation.
Essentially making any authenticated call you can follow this logic:
///
/// Executes an HTTP POST command and retrives the information.
/// This function will automatically include a "source" parameter if the "Source" property is set.
///
/// The URL to perform the POST operation
/// The username to use with the request
/// The password to use with the request
/// The data to post
/// The response of the request, or null if we got 404 or nothing.
protected string ExecutePostCommand(string url, string userName, string password, string data) {
WebRequest request = WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) {
request.Credentials = new NetworkCredential(userName, password);
byte[] bytes = Encoding.UTF8.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream()) {
requestStream.Write(bytes, 0, bytes.Length);
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
return reader.ReadToEnd();
}
}
}
}
return null;
}

Resources