Google Checkout implementation on ASP.NET

In this tutorial, I will be using Google Checkout API which is provided by Google to make online payment. Google has not yet released final version for recurring payment. It is still have some problems. So, the main focus will be on the normal(one time) payment method and verification of the payment to detect any fraud payment.

Section 1 (Make a request for payment processing)

 Step 1 (Configuration)

Get the Merchant Id and Merchant key from the Google checkout. You can also create sandbox account from https://sandbox.google.com/checkout/sell/ to get those information.

The information can be found under Settings tab and then clicking on Integration link.

From the same section(Settings -> Integration link) set the API version similar to the version that you have downloaded and click on Save button.

Step 2 (Add reference of dll)

Add a reference of Gcheckout.dll in your project.

Step 3 (Make a request for payment)

To make the request we need to create object of CheckoutShoppingCartRequest class.

GCheckout.Checkout.CheckoutShoppingCartRequest gCartRequest = new GCheckout.Checkout.CheckoutShoppingCartRequest

("","", GCheckout.EnvironmentType.Production, "", 30, false);

 Set  and  from Step 1.

In third parameter you can select the Sandbox or Production by using EnvironmentType enumeration.

Set  as currency code.
Please refer  http://www.iso.org/iso/.....

5th parameter is for cart expiration time. This is the duration between the user’s payment requested time and the maximum time user is allowed to make the successful payment.

The last parameter is whether this payment is for donation or not.

Step 4 (Add cart items in request)

gCartRequest.AddItem("", "", 12, 2);

By using AddItem function of CheckoutShoppingCartRequest we can add the item for payment processing. If there will be more then one item then you can loop and add those items for payment request.

is the name of product.

is the description of product

The third parameter is for specifying the product price which accept decimal value.

The last parameter is for specifying quantity.

Step 5 (sending your own data to Google checkout)

Sometime there are requirement to send your own to data to verify something or to identify the user while making successful payment.

//Create extra data to pass

XmlDocument tempDoc = new System.Xml.XmlDocument();

XmlNode orderIdNode = tempDoc.CreateElement("OrderId");

orderIdNode.InnerText = "ORD-001";

XmlNode userId = tempDoc.CreateElement("userId");

userId.InnerText = "vikash";

//Add private data

gCartRequest.AddMerchantPrivateDataNode(orderIdNode);

gCartRequest.AddMerchantPrivateDataNode(userId);

You need to create data in form of XML element and after that elements need to be inserted in payment process through AddMerchantPrivateDataNode method.

Step 5 (Send data for processing the payment)

Through send method the message is send to Google checkout and stored in response object which will hold the information. Finally, if request is successful then it will be stored in RedirectUrl property of GcheckoutResponse class and now we can redirect to Google Checkout page.

//Get response

GCheckoutResponse response = gCartRequest.Send();

 // Post the request for Google checkout

Response.Redirect(response.RedirectUrl, true);

Section 2 (Verify the payment )

From above process we have redirected user to Google checkout page for doing the payment. Now we have to check the user whether the user has paid the amount or not.

Step 1 (Configuration)

Again log-in into your Google Checkout Merchant account and and click on Settings tab and then Integration and follow these steps:

a. In API callback URL specify the page URL through which you will be verifying.

Ex: http://www.somewebsite.com/CheckoutPages/GooglePaymentNotification.aspx

b. Specify desired Callback contents from radio button then click on Save.

Step 2(Create page for handling the request)

Create the page or handler on same URL which you have specified above. This will read the request from Google and do the processing for payment verification.

For reading the request use this code in the page_load event, if you are using aspx page:

string serialNumber = null;

 // Receive Request

Stream requestInputStream = Request.InputStream;

 

string requestStreamAsString = null;

using (System.IO.StreamReader streamReader = newStreamReader(requestInputStream))

{

requestStreamAsString = streamReader.ReadToEnd();

}

 

// Parse Request to retrieve serial number

string[] requestStreamAsParts = requestStreamAsString.Split(newchar[] { '=' });

if (requestStreamAsParts.Length >= 2)

{

serialNumber = requestStreamAsParts[1];

}

 

// Call NotificationHistory Google Checkout API to retrieve the notification for the given serial number and process the notification(This class will be created in next step)

GoogleCheckoutHelper.ProcessNotification(serialNumber);

 

//serialize the message to the output stream only if you could process the message.

//Otherwise throw an http 500.

 

//Send Google Notification Acknowledgement

var response = new GCheckout.AutoGen.NotificationAcknowledgment();

response.serialnumber = serialNumber;

 HttpContext.Current.Response.Clear();

HttpContext.Current.Response.BinaryWrite(GCheckout.Util.EncodeHelper.Serialize(response));

HttpContext.Current.Response.StatusCode = 200;

 
Step 3 ( Create helper class to recognize the Google request)

This class will help us to identify the request and so the processing.

///

/// Google Checkout helper for doing the process

///

publicclassGoogleCheckoutHelper

{

 privatestaticvoid HandleAuthorizationAmountNotification(GCheckout.AutoGen.AuthorizationAmountNotification inputAuthorizationAmountNotification)

{

// TODO: Add custom processing for this notification type

}

 

privatestaticvoid HandleChargeAmountNotification(GCheckout.AutoGen.ChargeAmountNotification inputChargeAmountNotification)

{

// TODO: Add custom processing for this notification type

}

 

///

/// Handle new order Information

///

///Google checkout order

privatestaticvoid HandleNewOrderNotification(GCheckout.AutoGen.NewOrderNotification newOrder)

{

// TODO: processing for cart(This step is explained in next step)

}

}

 

privatestaticvoid HandleOrderStateChangeNotification(GCheckout.AutoGen.OrderStateChangeNotification notification)

{

// Charge Order If Chargeable

if ((notification.previousfinancialorderstate == GCheckout.AutoGen.FinancialOrderState.REVIEWING)

&& (notification.newfinancialorderstate == GCheckout.AutoGen.FinancialOrderState.CHARGEABLE))

{

 

ChargeOrderRequest oneChargeOrderRequest = newChargeOrderRequest(notification.googleordernumber);

GCheckout.Util.GCheckoutResponse oneGCheckoutResponse = oneChargeOrderRequest.Send();

}

 

// Update License If Charged

if ((notification.previousfinancialorderstate == GCheckout.AutoGen.FinancialOrderState.CHARGING)

&& (notification.newfinancialorderstate == GCheckout.AutoGen.FinancialOrderState.CHARGED))

{

// TODO: For each shopping cart item received in the NewOrderNotification, authorize the license

}

 

// TODO: Add custom processing for this notification type

}

 

privatestaticvoid HandleRiskInformationNotification(GCheckout.AutoGen.RiskInformationNotification notification)

{

// TODO: Add custom processing for this notification type

}

 

///

/// Process the request according to xml data that has been passed

///

///Serial number of the transaction

publicstaticvoid ProcessNotification(string serialNumber)

{

 

//Request

NotificationHistoryRequest oneNotificationHistoryRequest = newNotificationHistoryRequest("",

"",

Enum.GetName(typeof(GCheckout.EnvironmentType), GCheckout.EnvironmentType.Production),

newNotificationHistorySerialNumber(serialNumber));

 

//Response

NotificationHistoryResponse oneNotificationHistoryResponse = (NotificationHistoryResponse)oneNotificationHistoryRequest.Send();

 

//Get type of notification

object notification = GCheckout.Util.EncodeHelper.Deserialize(oneNotificationHistoryResponse.ResponseXml);

 

//Check for the notification and call functions according to that

if (notification.GetType().Equals(typeof(GCheckout.AutoGen.NewOrderNotification)))

{

GCheckout.AutoGen.NewOrderNotification oneNewOrderNotification = (GCheckout.AutoGen.NewOrderNotification)notification;

if (oneNewOrderNotification.serialnumber.Equals(serialNumber))

{

HandleNewOrderNotification(oneNewOrderNotification);

}

}

elseif (notification.GetType().Equals(typeof(GCheckout.AutoGen.OrderStateChangeNotification)))

{

GCheckout.AutoGen.OrderStateChangeNotification oneOrderStateChangeNotification = (GCheckout.AutoGen.OrderStateChangeNotification)notification;

if (oneOrderStateChangeNotification.serialnumber.Equals(serialNumber))

{

HandleOrderStateChangeNotification(oneOrderStateChangeNotification);

}

}

elseif (notification.GetType().Equals(typeof(GCheckout.AutoGen.RiskInformationNotification)))

{

GCheckout.AutoGen.RiskInformationNotification oneRiskInformationNotification = (GCheckout.AutoGen.RiskInformationNotification)notification;

if (oneRiskInformationNotification.serialnumber.Equals(serialNumber))

{

HandleRiskInformationNotification(oneRiskInformationNotification);

}

}

elseif (notification.GetType().Equals(typeof(GCheckout.AutoGen.AuthorizationAmountNotification)))

{

GCheckout.AutoGen.AuthorizationAmountNotification oneAuthorizationAmountNotification = (GCheckout.AutoGen.AuthorizationAmountNotification)notification;

if (oneAuthorizationAmountNotification.serialnumber.Equals(serialNumber))

{

HandleAuthorizationAmountNotification(oneAuthorizationAmountNotification);

}

}

elseif (notification.GetType().Equals(typeof(GCheckout.AutoGen.ChargeAmountNotification)))

{

GCheckout.AutoGen.ChargeAmountNotification oneChargeAmountNotification = (GCheckout.AutoGen.ChargeAmountNotification)notification;

if (oneChargeAmountNotification.serialnumber.Equals(serialNumber))

{

HandleChargeAmountNotification(oneChargeAmountNotification);

}

}

else

{

string exceptionText = "Unhandled Type [" + notification.GetType().ToString() + "]!; serialNumber=[" + serialNumber + "];";

Log.Error(exceptionText);

thrownewArgumentOutOfRangeException(exceptionText);

}

}

}

 

This is modified version of GoogleCheckoutHelper class got from

http://www.capprime.com/software_development_weblog

[OR]

http://google-checkout-dotnet-sample-code.googlecode.com/hg/examples/api25notification/App_Code/

 Step 4 (Mark your payment transaction as successful)

For achieving this now we just need to modify HandleNewOrderNotification function from GoogleCheckoutHelper class. We had previously sent our custom data to know the user and the transaction id. So for retrieving those details write this code under HandleNewOrderNotification:

//Check for private data

if (newOrder.shoppingcart.merchantprivatedata != null &&

newOrder.shoppingcart.merchantprivatedata.Any != null &&

newOrder.shoppingcart.merchantprivatedata.Any.Length > 0)

{

 

// Retrieve data from MerchantPrivateData

GCheckout.AutoGen.anyMultiple oneAnyMultiple = newOrder.shoppingcart.merchantprivatedata;

System.Xml.XmlNode[] oneXmlNodeArray = oneAnyMultiple.Any;

 

//Sales id

string strSalesId = oneXmlNodeArray[0].InnerText;

//User id

string strUserId = oneXmlNodeArray[1].InnerText;

int salesId = Convert.ToInt32(strSalesId);

//Mark transaction as successful through strUserId and salesId

}
150 150 Burnignorance | Where Minds Meet And Sparks Fly!