POSTing xml for Google Checkout

I am experimenting using Google Checkout and I am having trouble sending validation to the server. Here is my code:

XNamespace ns = XNamespace.Get("http://checkout.google.com/schema/2");

XDocument cart = new XDocument();
XElement rootElement = new XElement(ns + "checkout-shopping-cart",
    new XElement("shopping-cart",
        new XElement("items",
            new XElement("item",
                new XElement("item-name", "doodad"),
                new XElement("item-description", "Description for the doodad"),
                new XElement("unit-price", 9.99, new XAttribute("currency", "GBP")),
                new XElement("quantity", 1)
            )
         )
    )
);

cart.Add(rootElement);

string authKey = "111222333444:NOTAREALKEY";
authKey = EncodeToBase64(authKey);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://checkout.google.com/cws/v2/Merchant/111222333444/merchantCheckout");

request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(cart.ToString());
request.ContentType = "application/xml; charset=UTF-8";
request.ContentLength = byteArray.Length;
request.Headers.Add("Authorization: Basic " + authKey);
request.Accept = "application/xml; charset=UTF-8";

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Exception here!
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseText = reader.ReadToEnd();

reader.Close();
dataStream.Close();
response.Close();

When I call GetResponse (), I get (400) Bad Request.

Any help would be greatly appreciated.

+3
source share
3 answers

Your XML looks broken, as John Skeet points out :-). To further support debugging - there may be more information about the error in the response. WebExceptionhas an object Responsethat can have a more detailed error message that can be read by calling its method GetResponseStream().

+4
source

API Google Checkout, , ?

XElement rootElement = new XElement(ns + "checkout-shopping-cart",
    new XElement(ns + "shopping-cart"),
        new XElement(ns + "items",
                     // etc

, , , API API Checkout - , "xmlns =..." , -, .

+2

You can still read the response message if the exception is a WebException. This will give you more information about what's wrong:

try {
   response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex1) {
   response = ex1.Response();
}
0
source

Source: https://habr.com/ru/post/1730222/


All Articles