Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 74 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
74
Dung lượng
3,22 MB
Nội dung
CHAPTER 16 ■ CREDIT CARD TRANSACTIONS 609 // Get pre response response = request.GetResponse(dataCashUrl); // Display pre response Console.WriteLine("Pre Response:"); xmlBuilder = new StringBuilder(); xmlWriter = new StringWriter(xmlBuilder); responseSerializer.Serialize(xmlWriter, response); Console.WriteLine(xmlBuilder.ToString()); Console.WriteLine(); // Construct fulfil request request = new DataCashRequest(); request.Authentication.Client = dataCashClient; request.Authentication.Password = dataCashPassword; request.Transaction.HistoricTxn.Method = "fulfill"; request.Transaction.HistoricTxn.AuthCode = response.MerchantReference; request.Transaction.HistoricTxn.Reference = response.DatacashReference; // Display fulfil request Console.WriteLine("Fulfil Request:"); xmlBuilder = new StringBuilder(); xmlWriter = new StringWriter(xmlBuilder); requestSerializer.Serialize(xmlWriter, request); Console.WriteLine(xmlBuilder.ToString()); Console.WriteLine(); // Get fulfil response response = request.GetResponse(dataCashUrl); // Display fulfil response Console.WriteLine("Fulfil Response:"); xmlBuilder = new StringBuilder(); xmlWriter = new StringWriter(xmlBuilder); responseSerializer.Serialize(xmlWriter, response); Console.WriteLine(xmlBuilder.ToString()); // Await user input to finish Console.ReadKey(); } Darie-Watson_4681C16.fm Page 609 Friday, September 16, 2005 10:39 AM 610 CHAPTER 16 ■ CREDIT CARD TRANSACTIONS 16. Now build and run the solution. The text displayed in the OutputBox text box is as follows: Pre Request: <?xml version="1.0" encoding="utf-16"?> <Request xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Authentication> <password>bbdNsX7p</password> <client>99341800</client> </Authentication> <Transaction> <CardTxn> <method>pre</method> <Card> <pan>4444333322221111</pan> <expirydate>10/07</expirydate> </Card> </CardTxn> <TxnDetails> <merchantreference>9999999</merchantreference> <amount currency="GBP">49.99</amount> </TxnDetails> </Transaction> </Request> Pre Response: <?xml version="1.0" encoding="utf-16"?> <Response xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <status>1</status> <reason>ACCEPTED</reason> <merchantreference>9999999</merchantreference> <datacash_reference>4000200041287947</datacash_reference> <time>1122838608</time> <mode>TEST</mode> <CardTxn> <card_scheme>VISA</card_scheme> <country>United Kingdom</country> <authcode>953441</authcode> </CardTxn> </Response> Darie-Watson_4681C16.fm Page 610 Friday, September 16, 2005 10:39 AM CHAPTER 16 ■ CREDIT CARD TRANSACTIONS 611 Fulfil Request: <?xml version="1.0" encoding="utf-16"?> <Request xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Authentication> <password>bbdNsX7p</password> <client>99341800</client> </Authentication> <Transaction> <HistoricTxn> <reference>4000200041287947</reference> <authcode>9999999</authcode> <method>fulfill</method> </HistoricTxn> <TxnDetails> <amount /> </TxnDetails> </Transaction> </Request> Fulfil Response: <?xml version="1.0" encoding="utf-16"?> <Response xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <status>1</status> <reason>FULFILLED OK</reason> <merchantreference>4000200041287947</merchantreference> <datacash_reference>4000200041287947</datacash_reference> <time>1122838608</time> <mode>TEST</mode> </Response> 17. Log on to https://testserver.datacash.com/reporting2 to see the transaction log for your DataCash account (note that this view takes awhile to update, so you might not see the transaction right away). This report is shown in Figure 16-1, with a more detailed view in Figure 16-2. Darie-Watson_4681C16.fm Page 611 Friday, September 16, 2005 10:39 AM 612 CHAPTER 16 ■ CREDIT CARD TRANSACTIONS Figure 16-1. DataCash transaction report Darie-Watson_4681C16.fm Page 612 Friday, September 16, 2005 10:39 AM CHAPTER 16 ■ CREDIT CARD TRANSACTIONS 613 Figure 16-2. DataCash transaction report details How It Works: Communicating with DataCash You’ve created code to represent the XML documents that you’re exchanging. Two root classes—DataCashRequest and DataCashResponse—encapsulate XML requests and responses. These classes contain instances of the other classes defined, which contain instances of other classes, and so on, relating to the structure of the XML documents described earlier. Each of the members of these classes has an associated XML serialization attribute, matching the data with the way it will be formatted when the request or response classes are serialized. For example, many of the string members appear as follows: [XmlElement("status")] public string Status; Darie-Watson_4681C16.fm Page 613 Friday, September 16, 2005 10:39 AM 614 CHAPTER 16 ■ CREDIT CARD TRANSACTIONS The Status field will be formatted as follows: <status>Status data</status> The correct capitalization is included while at the same time allowing you to set the status data using standard PascalCasing format. ■Note PascalCasing is where variable names start with a capital letter, and each subsequent word in the name also has a capital letter, such as ThisIsAVariable. One alternative scheme is camelCasing, where the first word isn’t capitalized, for example thisIsAVariable. The capitalization in the names of these casing schemes serves as a reminder of their usage. One of the classes used, TransactionClass, is slightly more complicated than the others, because the <Transaction> element contains one of either <CardTxn> or <HistoricTxn>, depending on whether the request is a pre request or a fulfil request. Instead of using fields, this class uses properties that ensure that only one of these two elements is used. The DataCashRequest class also has a method called GetResponse that sends the request and packages the returned response as a DataCashResponse class. In the code to do this, you start by creating an HttpWebRequest instance for the URL supplied as a parameter: public DataCashResponse GetResponse(string url) { HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest; This request is then defined as a POST request with the appropriate encoding: httpRequest.Method = "POST"; UTF8Encoding encoding = new UTF8Encoding(); ■Note HTTP requests can be sent in a number of formats, the most common being GET and POST. The difference here is that GET requests have just a URL and header information; POST requests have all this plus a message body. Think of an HTTP POST request as if it were an email, with the HTTP response being the email reply. In both cases, header information is like the address and subject of the email, and body informa- tion is like the message body of an email. Next you need to supply the body of the POST request, which is the XML document you want to send. To do this, you get the serialized version of the data contained in the object via the Xml property (which simply serializes the DataCashRequest instance into XML, by using the XML serialization attributes): byte[] bodyBytes = encoding.GetBytes(Xml); Darie-Watson_4681C16.fm Page 614 Friday, September 16, 2005 10:39 AM CHAPTER 16 ■ CREDIT CARD TRANSACTIONS 615 You also need to specify the length of the data contained in the HTTP header for the request: httpRequest.ContentLength = bodyBytes.Length; Next you take the XML data and place it into the request via standard stream manipulation code: Stream httpRequestBodyStream = httpRequest.GetRequestStream(); httpRequestBodyStream.Write(bodyBytes, 0, bodyBytes.Length); httpRequestBodyStream.Close(); After you have the request class, you can obtain the response, also via stream manipulation: HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse; StreamReader httpResponseStream = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.ASCII); string httpResponseBody = httpResponseStream.ReadToEnd(); httpResponseStream.Close(); You only need the XML data contained in this stream, so clip off the headers at the beginning of the data returned before deserializing it. You do this using the String.Substring method to obtain the section of the string that starts with "<?xml", the location of which is found using the String.IndexOf method. httpResponseBody = httpResponseBody.Substring( httpResponseBody.IndexOf("<?xml")); XmlSerializer serializer = new XmlSerializer(typeof(DataCashResponse)); StringReader responseReader = new StringReader(httpResponseBody); Finally, you cast the deserialized object into a DataCashResponse object for further manipulation: return serializer.Deserialize(responseReader) as DataCashResponse; } After the transaction has completed, you can check that everything has worked properly via the DataCash reporting web interface. Integrating DataCash with BalloonShop Now you have a new set of classes that you can use to perform credit card transactions. However, you need to modify a few things to integrate it with your existing e-commerce application and pipeline. Darie-Watson_4681C16.fm Page 615 Friday, September 16, 2005 10:39 AM 8213592a117456a340854d18cee57603 616 CHAPTER 16 ■ CREDIT CARD TRANSACTIONS Business Tier Modifications In fact, all the modifications you’ll make to BalloonShop occur at the business tier because we’ve slipped in the data and presentation tier modifications already. We also have AuthCode and Reference fields ready to use for the database. In the presentation tier, we have the user interface elements in place to check on these values. All you have to do is make the PSCheckFunds and PSTakePayment pipeline sections work. Modifying the BalloonShopConfiguration Class Before modifying the pipeline itself, you have to modify the order-processor configuration, because you now have three new pieces of information that CommerceLib requires to operate: • DataCash Client • DataCash password • DataCash URL You can give access to this information via the BalloonShopConfiguration class as with the other similar information required for order processing. Add the following three properties to BalloonShopConfiguration: // DataCash client code public static string DataCashClient { get { return ConfigurationManager.AppSettings["DataCashClient"]; } } // DataCase password public static string DataCashPassword { get { return ConfigurationManager.AppSettings["DataCashPassword"]; } } // DataCash server URL public static string DataCashUrl { get { return ConfigurationManager.AppSettings["DataCashUrl"]; } } Darie-Watson_4681C16.fm Page 616 Friday, September 16, 2005 10:39 AM CHAPTER 16 ■ CREDIT CARD TRANSACTIONS 617 This uses information in the web.config file of BalloonShop. Modify web.config as follows, supplying your own client and password data as before: <appSettings> <add key="DataCashClient" value="99110400" /> <add key="DataCashPassword" value="rUD27uD" /> <add key="DataCashUrl" value="https://testserver.datacash.com/Transaction" /> </appSettings> Modifying the PSCheckFunds Pipeline Section Class The final changes involve modifying the pipeline section classes that deal with credit card transactions. The infrastructure for storing and retrieving authentication code and reference information has already been included, via the OrderProcessor.SetOrderAuthCodeAndReference method and the AuthCode and Reference properties. The modifications to PSCheckFunds are as follows: using DataCashLib; namespace CommerceLib { /// <summary> /// 2nd pipeline stage - used to check that the customer /// has the required funds available for purchase /// </summary> public class PSCheckFunds : IPipelineSection { private OrderProcessor orderProcessor; public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSCheckFunds started.", 20100); try { // check customer funds via DataCash gateway // configure DataCash XML request DataCashRequest request = new DataCashRequest(); request.Authentication.Client = BalloonShopConfiguration.DataCashClient; request.Authentication.Password = BalloonShopConfiguration.DataCashPassword; Darie-Watson_4681C16.fm Page 617 Friday, September 16, 2005 10:39 AM 618 CHAPTER 16 ■ CREDIT CARD TRANSACTIONS request.Transaction.TxnDetails.MerchantReference = orderProcessor.Order.OrderID.ToString() .PadLeft(6, '0').PadLeft(7, '5'); request.Transaction.TxnDetails.Amount.Amount = orderProcessor.Order.TotalCost.ToString(); request.Transaction.TxnDetails.Amount.Currency = "GBP"; request.Transaction.CardTxn.Method = "pre"; request.Transaction.CardTxn.Card.CardNumber = orderProcessor.Order.CreditCard.CardNumber; request.Transaction.CardTxn.Card.ExpiryDate = orderProcessor.Order.CreditCard.ExpiryDate; if (orderProcessor.Order.CreditCard.IssueDate != "") { request.Transaction.CardTxn.Card.StartDate = orderProcessor.Order.CreditCard.IssueDate; } if (orderProcessor.Order.CreditCard.IssueNumber != "") { request.Transaction.CardTxn.Card.IssueNumber = orderProcessor.Order.CreditCard.IssueNumber; } // get DataCash response DataCashResponse response = request.GetResponse( BalloonShopConfiguration.DataCashUrl); if (response.Status == "1") { // update order authorization code and reference orderProcessor.Order.SetAuthCodeAndReference( response.MerchantReference, response.DatacashReference); // audit orderProcessor.CreateAudit( "Funds available for purchase.", 20102); // update order status orderProcessor.Order.UpdateStatus(2); // continue processing orderProcessor.ContinueNow = true; } else { // audit orderProcessor.CreateAudit( "Funds not available for purchase.", 20103); // mail admin Darie-Watson_4681C16.fm Page 618 Friday, September 16, 2005 10:39 AM [...]... when accessing any kind of external functionality exposed through these protocols Congratulations, you have just finished your journey into learning about building e-commerce web sites with Beginning ASP.NET 2.0 E-Commerce in C# 2005: From Novice to Professional! You have the knowledge to build your own customized solutions that are even more interesting and powerful than what we showed you in this book... and integrate into your web site Perhaps the most interesting and powerful is the possibility to create and manage Amazon shopping carts from your C# code, by using the Amazon API If you’re really into integrating Amazon.com into your web site, you should study the ECS documentation carefully and make the most of it Summary In this chapter, you learned how to access Amazon Web Services using REST and... them having a Buy from Amazon link attached to it instead of the usual Add to Cart link 631 Darie-Watson_4681C17.fm Page 632 Tuesday, September 20, 2005 5:01 AM 632 CHAPTER 17 ■ INTEGRATING AMAZON WEB SERVICES ■Caution If you want to add this kind of functionality for your real e-commerce web site, you’ll probably want to customize this functionality Don’t forget to read (and comply to) the Amazon E-Commerce. .. testing) Optionally, you could configure other context information here, matching the values shown in the test code in the last section (port, timeout, and proxy information) • Modify OrderProcessorConfiguration to give access to these configured values • Modify PSCheckFunds and PSTakePayment to use this new information to communicate with PayFlow Pro This involves building a request string, interpreting... receive strings consisting of name-value pairs, separated by ampersands Effectively, you use a similar syntax to query strings appended to URLs The NET API comes with instructions for installing the various DLLs necessary to communicate with the PayFlow Pro gateway and includes sample code to test things out The C# test application starts with the following declarations: using System; using PayFlowPro;... This is the toy you’ll use all the way in this book to build your BalloonShop web site The installation process automatically installs the NET Framework 2.0, in case you don’t already have it on your system In the process of installing Visual Web Developer 2005, you’ll be given the option to install SQL Server 2005 Express Edition along with it, and we suggest you do so You need SQL Server 2005 Express... September 20, 2005 5:01 AM CHAPTER 17 ■■■ Integrating Amazon Web Services I n the dynamic world of the Internet, sometimes it isn’t enough to just have an important web presence; you also need to interact with functionality provided by third parties to achieve your goals So far in this book, you already saw how to integrate external functionality to process payments from your customers In this chapter,... really want to make a fortune out of this service, you should dig deeper to find more substance 625 Darie-Watson_4681C17.fm Page 626 Tuesday, September 20, 2005 5:01 AM 626 CHAPTER 17 ■ INTEGRATING AMAZON WEB SERVICES Figure 17-1 Integrating the “Amazon Balloons” department into BalloonShop The rest of this chapter is divided into two parts In the first part, you’ll learn how to access the Amazon E-Commerce. .. interpreting response strings, and storing authorization codes in the database as with DataCash In addition, to use the PayFlow Pro library, you need to add a reference to BalloonShop to use PFProdotNET.dll (the NET API for PayFlow Pro) and copy the certs directory to the C:\WINDOWS\system32 directory (as described in the sample application documentation) The downloadable code for this chapter includes a version... The important points you need to understand from this exercise follow: • The search parameter commands were saved to web.config, so you can do various changes to the behavior of the “Amazon Balloons” pages without modifying any C# code • To enable accessing ECS, you added a Web Reference to its WDSL file Visual Studio was kind enough to do the rest for you, giving you direct access to the classes exposed . ?????? 493 600 000 000 000 001 9 7 Decline the transaction. DECLINED 633 300 000 000 000 5 1 Authorized with random auth code. AUTH CODE ?????? 633 300 000 000 001 3 7 Decline the transaction. DECLINED 633 300 000 0 123 4 50 1. 16 -2. DataCash Credit Card Test Numbers Card Type Card Number Return Code Description Sample Message Switch 493 600 000 000 000 000 1 1 Authorized with random auth code. AUTH CODE ?????? 493 600 000 000 000 001 9. code. AUTH CODE ?????? Visa 424 2 424 2 424 2 424 2 7 Decline the transaction. DECLINED 4444333 322 221 111 1 Authorized with random auth code. AUTH CODE ?????? 454638 901 000 0131 1 Authorized with random