12

有没有关于如何在使用 C# 和 GCheckout API 时从 Google Checkout 事务中获取响应的教程。我能找到的所有示例都是针对以前版本的 API 而不是当前版本 (2.5)。更具体地说,我希望看到 Google 将在没有HTTPS 连接的情况下发回给我的示例回复。我知道这是最少的数据,但我仍然想看看它的一个例子,看看其他人是如何解析它的。

4

3 回答 3

2

Google 在内部发送通知
创建一个通知页面,如下所示:

<%@ 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 { ; }
    }
}

`

在谷歌结帐设置页面上设置通知页面名称和路径,您将在该页面上获得响应。要测试通知页面是否正常工作,请尝试将事务记录到 txt 文件中,一旦一切正常,您就可以删除该代码。

在此示例中,PData 是我发送到谷歌结帐并在通知中返回相同号码的号码,我使用它来匹配交易与特定订单。

希望此代码对您有所帮助;

于 2011-02-26T10:47:50.690 回答
1

如果没有 HTTPS 连接,您只会收到一个 POST 给您的序列号。为了安全起见,您应该确保授权是正确的(应该有一个Authorization包含<your mercahnt id>:<your merchant key>使用base64编码编码的标头)

然后,您需要通过 Notification-History-API 调用来请求更新的详细信息,大致如下:

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
}
于 2011-02-12T17:29:26.440 回答
1

注意:我刚刚从以下位置复制了我的答案:

Google Checkout 回复的 C# 示例?

由于某种原因,版主将其作为副本关闭(我认为合并会更好,因为这个问题没有答案而另一个问题有)。

--

我想要这个 Google API 2.5 .NET 示例代码很久了,最后自己构建了它:

http://www.capprime.com/software_development_weblog/2010/11/29/UsingTheGoogleCheckout25APIWithASPNETMVCTheMissingSample.aspx

如果您需要经典的 WebForms 而不是 MVC,请告诉我。

我没有包含数据包外观的示例,因为老实说,这并不重要(API 应该包装数据包)。在几个地方修改样本并让它向您发送包含该数据的电子邮件并不是很多工作。

于 2011-02-11T13:24:07.907 回答