¿Hay algún tutorial sobre cómo recuperar las respuestas de una transacción de Google Checkout cuando se usa C# y la API GCheckout? Todos los ejemplos que pude encontrar fueron para versiones anteriores de la API y no la actual (2.5). Más específicamente, me gustaría ver un ejemplo de respuesta de lo que Google me devolverá sin y conexión HTTPS. Sé que son datos mínimos, pero aún me gustaría ver un ejemplo y ver cómo otros lo analizan.C# y Google Checkout. ¿Recibió la respuesta del servidor?
Respuesta
Google envía una notificación interna
Crear una página de notificación de la siguiente manera:
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="GCheckout" %>
<%@ Import Namespace="GCheckout.AutoGen" %>
<%@ Import Namespace="GCheckout.Util" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Text" %>
<script runat="server" language="c#">
string serialnum = string.Empty;
void Page_Load(Object sender, EventArgs e)
{
// Extract the XML from the request.
Stream RequestStream = Request.InputStream;
StreamReader RequestStreamReader = new StreamReader(RequestStream);
string RequestXml = RequestStreamReader.ReadToEnd();
RequestStream.Close();
// Act on the XML.
switch (EncodeHelper.GetTopElement(RequestXml))
{
case "new-order-notification":
NewOrderNotification N1 = (NewOrderNotification)EncodeHelper.Deserialize(RequestXml, typeof(NewOrderNotification));
string OrderNumber1 = N1.googleordernumber;
string ShipToName = N1.buyershippingaddress.contactname;
string ShipToAddress1 = N1.buyershippingaddress.address1;
string ShipToAddress2 = N1.buyershippingaddress.address2;
string ShipToCity = N1.buyershippingaddress.city;
string ShipToState = N1.buyershippingaddress.region;
string ShipToZip = N1.buyershippingaddress.postalcode;
System.Xml.XmlNode[] arr = N1.shoppingcart.merchantprivatedata.Any;
String PData = String.Empty;
try
{
PData = arr[0].InnerText;
}
catch { PData = "Error"; }
decimal TotalPrice = 0.0M;
foreach (Item ThisItem in N1.shoppingcart.items)
{
string Name = ThisItem.itemname;
int Quantity = ThisItem.quantity;
decimal Price = ThisItem.unitprice.Value;
TotalPrice += Price * Quantity;
}
serialnum = N1.serialnumber;
string Message = "Order No : " + OrderNumber1 + " Total Price = $" + TotalPrice + "\r\nP. Data:" + PData;
LogTransaction(OrderNumber1, serialnum, Message, PData);
SendGoogleAcknowledgement();
break;
case "risk-information-notification":
RiskInformationNotification N2 = (RiskInformationNotification)EncodeHelper.Deserialize(RequestXml, typeof(RiskInformationNotification));
// This notification tells us that Google has authorized the order and it has passed the fraud check.
// Use the data below to determine if you want to accept the order, then start processing it.
string OrderNumber2 = N2.googleordernumber;
string AVS = N2.riskinformation.avsresponse;
string CVN = N2.riskinformation.cvnresponse;
bool SellerProtection = N2.riskinformation.eligibleforprotection;
serialnum = N2.serialnumber;
break;
case "order-state-change-notification":
OrderStateChangeNotification N3 = (OrderStateChangeNotification)EncodeHelper.Deserialize(RequestXml, typeof(OrderStateChangeNotification));
// The order has changed either financial or fulfillment state in Google's system.
string OrderNumber3 = N3.googleordernumber;
string NewFinanceState = N3.newfinancialorderstate.ToString();
string NewFulfillmentState = N3.newfulfillmentorderstate.ToString();
string PrevFinanceState = N3.previousfinancialorderstate.ToString();
string PrevFulfillmentState = N3.previousfulfillmentorderstate.ToString();
serialnum = N3.serialnumber;
break;
case "charge-amount-notification":
ChargeAmountNotification N4 = (ChargeAmountNotification)EncodeHelper.Deserialize(RequestXml, typeof(ChargeAmountNotification));
// Google has successfully charged the customer's credit card.
string OrderNumber4 = N4.googleordernumber;
decimal ChargedAmount = N4.latestchargeamount.Value;
serialnum = N4.serialnumber;
break;
case "refund-amount-notification":
RefundAmountNotification N5 = (RefundAmountNotification)EncodeHelper.Deserialize(RequestXml, typeof(RefundAmountNotification));
// Google has successfully refunded the customer's credit card.
string OrderNumber5 = N5.googleordernumber;
decimal RefundedAmount = N5.latestrefundamount.Value;
serialnum = N5.serialnumber;
break;
case "chargeback-amount-notification":
ChargebackAmountNotification N6 = (ChargebackAmountNotification)EncodeHelper.Deserialize(RequestXml, typeof(ChargebackAmountNotification));
// A customer initiated a chargeback with his credit card company to get her money back.
string OrderNumber6 = N6.googleordernumber;
decimal ChargebackAmount = N6.latestchargebackamount.Value;
serialnum = N6.serialnumber;
break;
default:
break;
}
}
private void SendGoogleAcknowledgement()
{
StringBuilder responseXml = new StringBuilder();
responseXml.Append("<?xml version='1.0' encoding='UTF-8'?>");
responseXml.Append("<notifiation-acknowledgment xmlns='http://checkout.google.com/schema/2' />");
HttpResponse response =
System.Web.HttpContext.Current.Response;
response.StatusCode = 200;
response.ContentType = "text/xml";
response.Write(responseXml.ToString());
response.End();
}
protected virtual void LogTransaction(string OrderNo, string SerialNo, string Message, String PData)
{
try
{
//Insert record in database
string sql = "Update GoogleOrder Set GoogleOrderNumber = @GoogleOrderNumber WHERE PrivateData = @PData";
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["inCommandConnectionString"].ConnectionString))
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(sql, Conn);
Cmd.Parameters.AddWithValue("@GoogleOrderNumber", OrderNo);
Cmd.Parameters.AddWithValue("@PData", PData);
Cmd.ExecuteNonQuery();
Conn.Close();
}
}
catch (Exception ex)
{
LogError("Error to Save The order No" + OrderNo);
}
//Insert record in text file
LogError(Message);
}
private void LogError(String Message)
{
String LogFile = ConfigurationManager.AppSettings.Get("LinkPointLogFile");
if (LogFile != "")
{
byte[] binLogString = Encoding.Default.GetBytes(Message);
try
{
FileStream loFile = new FileStream(LogFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
loFile.Seek(0, SeekOrigin.End);
loFile.Write(binLogString, 0, binLogString.Length);
loFile.Close();
}
catch { ; }
}
}
`
en google checkout setting page establece el nombre y la ruta de la página de notificación y obtendrá la respuesta en esa página. Para comprobar si la página de notificación está funcionando o no, intente registrar la transacción en un archivo txt y una vez que todo esté funcionando correctamente, puede eliminar ese código.
En este ejemplo, PData es un número que envío a Google Checkout para obtener el mismo número en notificación, lo usé para hacer coincidir la transacción con un pedido en particular.
Espero que este código te ayude;
Nota: He copiado mi respuesta de:
C# example for Google Checkout replies?
que estaba cerrado por alguna razón como un duplicado por un moderador (creo que se fusionan se hubiera sido mejor teniendo en cuenta que esta pregunta no tenía una respuesta y la otra lo hizo).
-
quería que esta versión de la API Google 2.5 .NET código de ejemplo para un largo tiempo y finalmente se construyeron a mí mismo:
Si necesita WebForms clásicos en lugar de MVC, deja yo sé.
No incluí ejemplos de cómo se ven los paquetes, porque sinceramente, no importa (se supone que la API debe envolver los paquetes). No es mucho trabajo modificar la muestra en un par de lugares y que le envíe un correo electrónico con esa información.
Sin una conexión HTTPS solo obtendrá un número de serie POSTed para usted. Para mayor seguridad, debe asegurarse de que la autorización sea correcta (debe haber un encabezado Authorization
que contenga <your mercahnt id>:<your merchant key>
codificado con codificación base64)
Luego debe realizar una llamada a través de Notification-History-API para solicitar los detalles de la actualización, vagamente:
IList<string> ordersToGetUpdate = new List<string> { serialNumber };
NotificationHistoryRequest request = new NotificationHistoryRequest(ordersToGetUpdate);
NotificationHistoryResponse resp = (NotificationHistoryResponse)request.Send();
foreach (object notification in resp.NotificationResponses)
{
// You'd now need to handle the response, which could be one of NewOrderNotification, OrderStateChangeNotification, RiskInformationNotification, AuthorizationAmountNotification or a ChargeAmountNotification
NewOrderNotification newOrder = notification as NewOrderNotification;
if(newOrder != null)
{
// Yay! New order, so do "something" with it
}
OrderStateChangeNotification orderUpdate = notification as OrderStateChangeNotification;
if (orderUpdate != null)
{
// Order updated (paid, shipped, etc), so do "something" with it
}
// you probably get the idea as to how to handle the other response types
}
- 1. El servidor proxy recibió una respuesta no válida de un servidor en sentido ascendente
- 2. Cómo obtener y analizar la respuesta JSON del traductor Google
- 3. jQuery Ajax y respuesta de redirección del servidor
- 4. ¿Alguna vez recibió una respuesta inesperada durante la entrevista?
- 5. AutoCompleteTextView con la respuesta del servidor
- 6. ¿es posible eliminar "Google Frontend" del encabezado de respuesta del motor de la aplicación de Google?
- 7. C# ASP.NET Reconocimiento de notificación de Google Checkout
- 8. C# stream ¿recibió todos los datos?
- 9. fusionar colección principal con respuesta del servidor
- 10. Controladores de respuesta del servidor para google.script.run
- 11. Error PHP cURL: "Respuesta vacía del servidor"
- 12. Amazon FPS vs PayPal vs Google Checkout
- 13. google analytics seguimiento del servidor
- 14. Uso de Google Checkout en ASP.Net
- 15. "Conexión: Keep-Alive" en la respuesta del servidor
- 16. No se puede leer la respuesta del servidor
- 17. jQuery y Google Maps respuesta JSON
- 18. ¿Cómo puedo correlacionar la respuesta de Google Checkout con el orden correcto en la base de datos?
- 19. C# Obtener cookies de la respuesta del servidor proporcionada en los datos POST
- 20. ¿Cuál es la diferencia entre solicitud, respuesta y servidor?
- 21. Google Maps v3 geocodificación del lado del servidor
- 22. TFS/File Checkout desde C#
- 23. Error de curvatura - Respuesta vacía del servidor (ssl)
- 24. Cómo caché del lado del servidor ASP.NET personalizado Respuesta de HttpHandler
- 25. caracteres especiales en respuesta XML recibidos del servidor
- 26. Obtener respuesta del servidor con el método WebClient.UploadFileAsync
- 27. Restkit json mensaje de respuesta de error del servidor
- 28. ¿Cómo se lee JSON (respuesta del servidor) en Javascript?
- 29. ¿Cómo enviar una respuesta de error del servidor usando php?
- 30. C# webclient y servidor proxy