e-commerce credit card processing

e-commerce site is to enable credit card processing
Dr.NaveenBansal Profile Pic
Dr.NaveenBansal,India,Teacher
Published Date:25-10-2017
Your Website URL(Optional)
Comment
8644ch20FINAL.qxd 1/30/08 12:54 PM Page 623 CHAPTER 20 Processing Credit Card Transactions T he last thing we need to do before launching the e-commerce site is to enable credit card processing. In this chapter, we examine how we can build this into the pipeline we created in the previous chapter. We’ll start by looking at the theory behind credit card transactions, the sort of organiza- tions that help achieve credit card processing, and the sort of transactions that are possible. Moving on, we’ll take two example organizations, DataCash and Authorize.net, and discuss the specifics of their transaction application program interfaces (APIs), the means by which we use their credit card transaction features. After that, we’ll build a new class library that helps use one of these transaction APIs via some simple test code. Finally, we’ll integrate the API with the TShirtShop e-commerce application and order- processing pipeline. Credit Card Transaction Fundamentals For transactions, banks and other financial institutions use secure networks based on the X.25 protocol rather than Transmission Control Protocol/Internet Protocol (TCP/IP), the primary means by which data is transmitted across the Internet. You don’t need to know much about X.25 apart from the fact that it’s a different networking protocol that isn’t compatible with TCP/IP. As such, X.25 networks are completely separate from the Internet, and although it’s possible to get direct access to them, this isn’t likely to be a reasonable option. To do so, we might have to enter into some serious negotiation with the owners of the network we want to use. The owners will want to be completely sure that we are reliable customers who are capable of enforcing the necessary safeguards to prevent an attack on their system. Accord- ingly, the network owner won’t be handing out these licenses to just anyone—most people can’t afford the security measures required (which include locking your servers in a cage, sending daily backup tapes down a secure chute, having three individuals with separate keys to access these tapes, and so on). The alternative is to access these networks via a gateway provider. This enables us to perform our side of the credit card transaction protocol over the Internet (using a secure protocol), while relying on a chosen gateway to communicate with X.25 networks. Although there is likely to be a cost involved with this, the provider should have a deal with financial institutions to help keep costs low and pass the savings on to us (after the gateway takes its share), so it’s likely to 623 www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 624 624 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS be much cheaper than having your own X.25 connection. This method is also likely to be cheaper than using a third-party payment processor, because we only need the minimum functionality since we are handling our own order pipeline. There is no need, for example, to use all the order-auditing functionality offered by a company such as PayPal, because we already have all this functionality in our implementation. Working with Credit Card Payment Gateways To work with a gateway organization, we first need to open a merchant bank account. This can be done at most banks; the bank will provide you a merchant ID that you can use when signing up with the gateway. The next step is to find a suitable gateway. This can be a lot of hard work Although it isn’t hard to find a gateway, the challenge lies in finding a competent one that offers services at an acceptable price and quality. Literally hundreds of companies are eager to take a cut of your sales. A quick search on the Internet for “credit card gateway” will produce a long list. The web sites of these companies are for the most part pure brochureware—you’ll find yourself reading through pages of text about how they are the best and most secure at what they do, only to end up with a form to fill in so that a customer service representative can call you to “discuss your needs.” In the long run, you can rest assured that at least you will probably only have to go through the procedure once. You’ll probably find that most of the organizations offering this service are offering similar packages. However, some key points to look for include the banks they do business with (your merchant bank account will have to be at one of these), the currencies they deal in, and, of course, the costs. Table 20-1 shows some of the gateway services available. In this chapter, we’ll look at two of the few organizations that are easy to deal with—DataCash and Authorize.net. Table 20-1. Gateway Services United States United Kingdom Gateways URL Gateways URL Authorize.net http://www.authorize.net/ Arcot http://www.arcot.com/ First Data http://www.firstdata.com/ WorldPay http://www.worldpay.com/ Cardservice http://cardservice.com/ DataCash http://www.datacash.com/ ICVerify http://www.icverify.com/ DataCash and Authorize.net In this chapter, we’ll demonstrate implementing credit card transactions with two online services: DataCash and Authorize.net. DataCash is a credit card gateway organization based in the United Kingdom. You’ll need a UK merchant bank account if you want to use it in the final application. However, you don’t have to worry about this for now: it’s very easy to get access to a rather useful test account— you don’t even need a merchant bank account. Authorize.net, as mentioned on its official web site at http://www.authorize.net, “provides Internet Protocol (IP) payment gateway services that enable merchants to authorize, settle, and manage credit card or electronic check transactions anytime, anywhere.” In other words, Authorize.net also offers the service that we need to process the credit cards ourselves when someone buys one of our t-shirts. www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 625 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 625 The important point to remember is that the techniques covered in this chapter apply to every credit card gateway. The specifics might change slightly if you switch to a different organi- zation, but you’ll have already done most of the hard work. As you’ll see later in this chapter, both Authorize.net and DataCash let us perform test trans- actions using so-called “magic” credit card numbers (supplied separately by Authorize.net and DataCash), which will accept or decline transactions without performing any actual financial transactions. This is fantastic for development purposes, because we certainly don’t want to use our own credit cards for testing Understanding Credit Card Transactions Whichever gateway you use, the basic principles of credit card transactions are the same. First, the sort of transactions we’ll be dealing with in an e-commerce web site are known as Card Not Present (CNP) transactions, which means we don’t have the credit card in front of us and we can’t verify the customer signature. This isn’t a problem; after all you’ve probably been perform- ing CNP transactions for some time now online, over the phone, by mail, and so on. It’s just something to be aware of should you see the CNP acronym. Several advanced services are offered by various gateways, including cardholder address verification, security code checking, fraud screening, and so on. Each of these adds an addi- tional layer of complexity to your credit card processing, and we’re not covering those details here. Rather, this chapter provides a starting point from which you can add these services if required. Whether or not you choose these optional extra services depends on how much money is passing through your system and the trade-off between the costs of implementing the services and the potential costs, which could be prevented by these extra services, if some- thing goes wrong. If you are interested in these services, that customer service representative mentioned previously will be happy to explain things. As it stands now, we can perform several types of transactions: Authorization: Check a card for adequate funds and perform a deduction. Preauthorization: Check a card for funds and allocate them if available; this doesn’t deduct funds immediately. Fulfillment: Complete a preauthorized transaction, deducting the funds already allocated. Refund: Refund a completed transaction or simply put money on a credit card. Again, the specifics vary, but these are the basic types. In this chapter, we’ll use the preauthorization/fulfillment model, which means we don’t take payment until just before we instruct our supplier to ship goods. This structure was hinted at by the structure of the pipeline we created in the previous chapter. Working with DataCash Now that we’ve covered the basics, let’s consider how we’ll get things working in the TShirtShop application using the DataCash system. The first thing to do is to get a test account with DataCash by following these steps: www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 626 626 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 1. Go to http://www.datacash.com/. 2. Head to the Developers Area ➤ Get a Test Account section of the web site. 3. Enter your details, and submit the form. 4. From the e-mail you receive, make a note of your account username and password, as well as the additional information required for accessing the DataCash reporting system. ■Note After you obtain your test account, be sure to download the DataCash Developer’s Guide at https://testserver.datacash.com/software/DevelopersGuide.pdf. This is the official document you can rely on to have accurate and recent information about any DataCash services. DataCash offers a PHP API composed of a number of PHP classes that you can use to con- nect to its services. These classes compose the XML messages that interact with the DataCash web service for you. In this chapter, for understanding how the system works even better, we choose to create the XML structures and interact with the DataCash web service directly. We’ll be doing a lot of XML manipulation when communicating with DataCash, because we’ll need to create XML documents to send to DataCash and to extract data from XML responses. In the following few pages, we’ll take a quick look at the XML required for the operations we’ll be performing and the responses we can expect. We’ll discuss the communication protocol, which implies discussing the XML files that reflect the following stages of a transaction: • Preauthentication request • Response to the preauthentication request • Fulfillment request • Fulfillment response We’ll implement these stages into the TShirtShop order pipeline. While reading this chap- ter, always remember to use the official documentation, which contains the most current and relevant updates, at https://testserver.datacash.com/software/DevelopersGuide.pdf. Preauthentication Request When we send a preauthentication request to DataCash, we need to include the following information: • DataCash username (known as the DataCash client) • DataCash password • A unique transaction reference number • The amount of money to be debited • The currency used for the transaction (U.S. dollars, British pounds, and so on) www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 627 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 627 • The type of transaction (the code pre for preauthentication and the code fulfill for fulfillment) • The credit card number • The credit card expiration date • The credit card issue date (if applicable to the type of credit card being used) • The credit card issue number (if applicable to the type of credit card being used) The unique transaction reference number must be a number between 6 and 12 digits long, which we choose to uniquely identify the transaction with an order. Because we can’t use a short number, we can’t just use the order ID values we’ve been using up until now for orders. We can, however, use this order ID as the starting point for creating a reference number by simply adding a high number to it, such as 1,000,000. We can’t duplicate the reference number in any future transactions; we must be sure that after a transaction is completed, it won’t exe- cute again, which could result in charging the customer twice. This process implies, however, that if a credit card is rejected, we might need to create a whole new order for the customer to generate a new and unique reference number to send to the gateway, but that shouldn’t be a problem. The XML request is formatted in the following way, with the values detailed previously shown in bold: ?xml version="1.0" encoding="UTF-8"? Request Authentication passwordDataCash password/password clientDataCash client/client /Authentication Transaction TxnDetails merchantreferenceUnique reference number/merchantreference amount currency='Currency Type'Cash amount/amount /TxnDetails CardTxn methodpre/method Card panCredit card number/pan expirydateCredit card expiry date/expirydate /Card /CardTxn /Transaction /Request Response to the Preauthentication Request The response to a preauthentication request includes the following information: www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 628 628 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS • The status code number indicates what happened; the code will be 1 if the transaction was successful or another of several other codes if something else happens. For a com- plete list of return codes for a DataCash server, see https://testserver.datacash.com/ software/returncodes.shtml. • The reason for the status is, basically, a string explaining the status in English. For a status of 1, this string is ACCEPTED. • An authentication code and a reference number are provided for use in completing the transaction in the fulfillment request stage (discussed next). • The time that the transaction was processed is provided. • The mode of the transaction, which is TEST when using the test account, is also given. • Confirmation of the type of credit card used is provided. • Confirmation of the country that the credit card was issued in is included as well. • And the authorization code used by the bank (for reference only) is also supplied. The XML for this is formatted as follows: ?xml version="1.0" encoding="utf-8"? Response statusStatus code/status reasonReason/reason merchantreferenceAuthentication code/merchantreference datacash_referenceReference number/datacash_reference timeTime/time modeTEST/mode CardTxn card_schemeCard Type/card_scheme countryCountry/country issuerCard issuing bank/issuer authcodeBank authorization code/authcode /CardTxn /Response Fulfillment Request For a fulfillment request, we need to send the following information: • DataCash username (the DataCash client) • DataCash password • The type of the transaction (for fulfillment, the code fulfill) • The authentication code received earlier • The reference number received earlier www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 629 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 629 We can, optionally, include additional information, such as a confirmation of the amount to be debited from the credit card, although this isn’t really necessary. The fulfillment request XML message is formatted as follows: ?xml version="1.0" encoding="UTF-8"? Request Authentication passwordDataCash password/password clientDataCash client/client /Authentication Transaction HistoricTxn referenceReference Number/reference authcodeAuthentication code/authcode methodfulfill/method /HistoricTxn /Transaction /Request Fulfillment Response The response to a fulfillment request includes the following information: • The status code number indicates what happened; the code will be 1 if the transaction was successful or another of several other codes if something else happens. Again, for a com- plete list of codes, see https://testserver.datacash.com/software/returncodes.shtml. • The reason for the status is, basically, a string explaining the status in English. For a status of 1, this string is FULFILLED OK. • Two copies of the reference code are provided for use by DataCash. • The time that the transaction was processed is supplied. • And the mode of the transaction, which is TEST when using the test account, is also provided. The XML message for the fulfillment response is formatted as follows: ?xml version="1.0" encoding="utf-8"? Response statusStatus code/status reasonReason/reason merchantreferenceReference Code/merchantreference datacash_referenceReference Code/datacash_reference timeTime/time modeTEST/mode /Response www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 630 630 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS Exchanging XML Data with DataCash Because the XML data we need to send to DataCash has a simple and standard structure, we’ll build it manually in a string, without using the XML support offered by PHP 5. However, we will take advantage of PHP 5’s SimpleXML extension, which makes reading simple XML data a piece of cake. Although less complex and powerful than DOMDocument, the SimpleXML extension makes parsing XML data easy by transforming it into a data structure we can simply iterate through. You first met the SimpleXML extension in Chapter 6. ■Note For the code that communicates with DataCash, we use the cURL library (http://curl.haxx.se/). Uncomment the following line in php.ini by removing the leading semicolon:extension=php_curl.dll. Then restart Apache. You’ll find the php.ini file in the C:\xampp\apache\bin\ folder on Windows or the /opt/lampp/etc folder on Linux. For more details about the cURL library, check out the excellent tutorial at http://www.zend.com/pecl/ tutorials/curl.php. The official documentation of PHP’s cURL support is located at http://www.php.net/ curl. Exercise: Communicating with DataCash 1. Create a new file named datacash_request.php in the business folder, and add the following code to it: ?php class DataCashRequest // DataCash Server URL private _mUrl; // Will hold the current XML document to be sent to DataCash private _mXml; // Constructor initializes the class with URL of DataCash public function __construct(url) // Datacash URL this-_mUrl = url; / Compose the XML structure for the pre-authentication request to DataCash / public function MakeXmlPre(dataCashClient, dataCashPassword, merchantReference, amount, currency, www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 631 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 631 cardNumber, expiryDate, startDate = '', issueNumber = '') this-_mXml = "?xml version=\"1.0\" encoding=\"UTF-8\"\x3F Request Authentication passworddataCashPassword/password clientdataCashClient/client /Authentication Transaction TxnDetails merchantreferencemerchantReference/merchantreference amount currency=\"currency\"amount/amount /TxnDetails CardTxn methodpre/method Card pancardNumber/pan expirydateexpiryDate/expirydate startdatestartDate/startdate issuenumberissueNumber/issuenumber /Card /CardTxn /Transaction /Request"; // Compose the XML structure for the fulfillment request to DataCash public function MakeXmlFulfill(dataCashClient, dataCashPassword, authCode, reference) this-_mXml = "?xml version=\"1.0\" encoding=\"UTF-8\"\x3F Request Authentication passworddataCashPassword/password clientdataCashClient/client /Authentication Transaction HistoricTxn referencereference/reference authcodeauthCode/authcode methodfulfill/method /HistoricTxn /Transaction /Request"; www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 632 632 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS // Get the current XML public function GetRequest() return this-_mXml; // Send an HTTP POST request to DataCash using cURL public function GetResponse() // Initialize a cURL session ch = curl_init(); // Prepare for an HTTP POST request curl_setopt(ch, CURLOPT_POST, 1); // Prepare the XML document to be POSTed curl_setopt(ch, CURLOPT_POSTFIELDS, this-_mXml); // Set the URL where we want to POST our XML structure curl_setopt(ch, CURLOPT_URL, this-_mUrl); / Do not verify the Common name of the peer certificate in the SSL handshake / curl_setopt(ch, CURLOPT_SSL_VERIFYHOST, 0); // Prevent cURL from verifying the peer's certificate curl_setopt(ch, CURLOPT_SSL_VERIFYPEER, 0); / We want cURL to directly return the transfer instead of printing it / curl_setopt(ch, CURLOPT_RETURNTRANSFER, 1); // Perform a cURL session result = curl_exec(ch); // Close a cURL session curl_close (ch); // Return the response return result; ? 2. Define the DataCash URL and login data at the end of your include/config.php file: // Constant definitions for datacash define('DATACASH_URL', 'https://testserver.datacash.com/Transaction'); www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 633 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 633 define('DATACASH_CLIENT', 'your account client number'); define('DATACASH_PASSWORD', 'your account password'); ■Note Don’t forget to use the data from your DataCash account 3. Create the test_datacash.php file in your project’s home (the tshirtshop folder), and add the follow- ing in it: ?php session_start(); if (empty (_GET'step')) require_once 'include/config.php'; require_once BUSINESS_DIR . 'datacash_request.php'; request = new DataCashRequest(DATACASH_URL); request-MakeXmlPre(DATACASH_CLIENT, DATACASH_PASSWORD, 8880000 + rand(0, 10000), 49.99, 'GBP', '3528000000000007', '11/09'); request_xml = request-GetRequest(); _SESSION'pre_request' = request_xml; response_xml = request-GetResponse(); _SESSION'pre_response' = response_xml; xml = simplexml_load_string(response_xml); request-MakeXmlFulfill(DATACASH_CLIENT, DATACASH_PASSWORD, xml-merchantreference, xml-datacash_reference); response_xml = request-GetResponse(); _SESSION'fulfill_response' = response_xml; else header('Content-type: text/xml'); switch (_GET'step') case 1: print _SESSION'pre_request'; www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 634 634 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS break; case 2: print _SESSION'pre_response'; break; case 3: print _SESSION'fulfill_response'; break; exit(); ? frameset cols="33%, 33%, 33%" frame src="test_datacash.php?step=1" frame src="test_datacash.php?step=2" frame src="test_datacash.php?step=3" /frameset 4. Load the test_datacash.php file in your browser to see the results. If you use Opera, the output should look like Figure 20-1, because Opera shows only the contents of the XML elements. If you use another web browser, you should see properly formatted XML documents. Figure 20-1. DataCash transaction results www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 635 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 635 5. Log on to https://testserver.datacash.com/reporting2 to see the transaction log for your DataCash account (note that this view takes a while to update, so you might not see the transaction right away). This report is shown in Figure 20-2. Figure 20-2. DataCash transaction report details How It Works: The Code That Communicates with DataCash The DataCashRequest class is quite simple. First the constructor sets the HTTPS address where we send your requests: // Constructor initializes the class with URL of DataCash public function __construct(url) // Datacash URL this-_mUrl = url; When we want to make a preauthentication request, we first need to call the MakeXmlPre() method to create the required XML for this kind of request. Some XML elements are optional (such as startdate or issuenumber, which get default values if we don’t provide our own—see the MakeXmlPre() method), but the other elements are mandatory. www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 636 636 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS ■Note If you want to see exactly which elements are mandatory and which are optional for each kind of request, check the XML API frequently asked questions document from DataCash. The next kind of request we must be able to make to the DataCash system is a fulfill request. The XML for this kind of request is prepared in the MakeXmlFulfill() method. We then have the GetRequest() method that returns the last XML document built by either MakeXmlPre() or MakeXmlFulfill(): // Get the current XML public function GetRequest() return this-_mXml; Finally, the GetResponse() method actually sends the latest XML request file, built by a call to either MakeXmlPre() or MakeXmlFulfill() and returns the response XML. Let’s take a closer look at this method. GetResponse() starts by initializing a cURL session and setting the POST method to send your data: // Send an HTTP POST request to DataCash using cURL public function GetResponse() // Initialize a cURL session ch = curl_init(); // Prepare for an HTTP POST request curl_setopt(ch, CURLOPT_POST, 1); // Prepare the XML document to be POSTed curl_setopt(ch, CURLOPT_POSTFIELDS, this-_mXml); // Set the URL where we want to POST our XML structure curl_setopt(ch, CURLOPT_URL, this-_mUrl); / Do not verify the Common name of the peer certificate in the SSL handshake / curl_setopt(ch, CURLOPT_SSL_VERIFYHOST, 0); // Prevent cURL from verifying the peer's certificate curl_setopt(ch, CURLOPT_SSL_VERIFYPEER, 0); To return the transfer into a PHP variable, we set the CURLOPT_RETURNTRANSFER parameter to 1, send the request, and close the cURL session: / We want cURL to directly return the transfer instead of printing it / curl_setopt(ch, CURLOPT_RETURNTRANSFER, 1); www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 637 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 637 // Perform a cURL session result = curl_exec(ch); // Close a cURL session curl_close (ch); // Return the response return result; The test_datacash.php file acts like this: When we load it in the browser, the script makes a preauthentication request and a fulfillment request and then saves the preauthentication request, response, and fulfillment XML data in the session: session_start(); if (empty (_GET'step')) require_once 'include/config.php'; require_once BUSINESS_DIR . 'datacash_request.php'; request = new DataCashRequest(DATACASH_URL); request-MakeXmlPre(DATACASH_CLIENT, DATACASH_PASSWORD, 8880000 + rand(0, 10000), 49.99, 'GBP', '3528000000000007', '11/09'); request_xml = request-GetRequest(); _SESSION'pre_request' = request_xml; response_xml = request-GetResponse(); _SESSION'pre_response' = response_xml; xml = simplexml_load_string(response_xml); request-MakeXmlFulfill(DATACASH_CLIENT, DATACASH_PASSWORD, xml-merchantreference, xml-datacash_reference); response_xml = request-GetResponse(); _SESSION'fulfill_response' = response_xml; The test_datacash.php page will be loaded three times more, because we have three frames that we want to fill with data: frameset cols="33%, 33%, 33%" frame src="test_datacash.php?step=1" frame src="test_datacash.php?step=2" frame src="test_datacash.php?step=3" /frameset www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 638 638 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS Depending on the step value, we decide which of the previously saved-in-session XML data is displayed in the current frame. If the step value is 1, the prerequest XML code is displayed. If the value is 2, the preresponse XML code is displayed. If the step value is 3, the fulfill response XML is displayed. else header('Content-type: text/xml'); switch (_GET'step') case 1: print _SESSION'pre_request'; break; case 2: print _SESSION'pre_response'; break; case 3: print _SESSION'fulfill_response'; break; exit(); Integrating DataCash with TShirtShop Now that we have a new class that performs credit card transactions, all we need to do is inte- grate its functionality into the order pipeline we built in the previous chapters. To fully integrate DataCash with TShirtShop, we’ll need to update the existing PsCheckFunds and PsTakePayments classes. We need to modify the pipeline section classes that deal with credit card transactions. We’ve already included the infrastructure for storing and retrieving authentication codes and reference information, via the OrderProcessor::SetOrderAuthCodeAndReference() method. Exercise: Implementing the Order Pipeline Classes 1. First, replace the code in business/ps_check_funds.php with the following code that works with DataCash: ?php class PsCheckFunds implements IPipelineSection public function Process(processor) // Audit processor-CreateAudit('PsCheckFunds started.', 20100); www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 639 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 639 order_total_cost = processor-mOrderInfo'total_amount'; order_total_cost += processor-mOrderInfo'shipping_cost'; order_total_cost += round((float)order_total_cost (float)processor-mOrderInfo'tax_percentage', 2) / 100.00; request = new DataCashRequest(DATACASH_URL); request-MakeXmlPre(DATACASH_CLIENT, DATACASH_PASSWORD, processor-mOrderInfo'order_id' + 1000006, order_total_cost, 'GBP', processor-mCustomerInfo'credit_card'-CardNumber, processor-mCustomerInfo'credit_card'-ExpiryDate, processor-mCustomerInfo'credit_card'-IssueDate, processor-mCustomerInfo'credit_card'-IssueNumber); responseXml = request-GetResponse(); xml = simplexml_load_string(responseXml); if (xml-status == 1) processor-SetAuthCodeAndReference( xml-merchantreference, xml-datacash_reference); // Audit processor-CreateAudit('Funds available for purchase.', 20102); // Update order status processor-UpdateOrderStatus(2); // Continue processing processor-mContinueNow = true; else // Audit processor-CreateAudit('Funds not available for purchase.', 20103); throw new Exception('Credit card check funds failed for order ' . processor-mOrderInfo'order_id' . "\n\n" . 'Data exchanged:' . "\n" . request-GetResponse() . "\n" . responseXml); // Audit processor-CreateAudit('PsCheckFunds finished.', 20101); ? www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 640 640 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 2. Replace the code in business/ps_take_payment.php with the following code: ?php class PsTakePayment implements IPipelineSection public function Process(processor) // Audit processor-CreateAudit('PsTakePayment started.', 20400); request = new DataCashRequest(DATACASH_URL); request-MakeXmlFulFill(DATACASH_CLIENT, DATACASH_PASSWORD, processor-mOrderInfo'auth_code', processor-mOrderInfo'reference'); responseXml = request-GetResponse(); xml = simplexml_load_string(responseXml); if (xml-status == 1) // Audit processor-CreateAudit( 'Funds deducted from customer credit card account.', 20402); // Update order status processor-UpdateOrderStatus(5); // Continue processing processor-mContinueNow = true; else // Audit processor-CreateAudit('Could not deduct funds from credit card.', 20403); throw new Exception('Credit card take payment failed for order ' . processor-mOrderInfo'order_id' . "\n\n" . 'Data exchanged:' . "\n" . request-GetResponse() . "\n" . responseXml); // Audit processor-CreateAudit('PsTakePayment finished.', 20401); ? www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 641 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 641 3. Add a reference to the business/datacash_request.php file in index.php as highlighted: require_once BUSINESS_DIR . 'ps_check_funds.php'; require_once BUSINESS_DIR . 'ps_check_stock.php'; require_once BUSINESS_DIR . 'datacash_request.php'; 4. Add a reference to the business/datacash_request.php file in admin.php as highlighted: require_once BUSINESS_DIR . 'ps_ship_ok.php'; require_once BUSINESS_DIR . 'ps_final_notification.php'; require_once BUSINESS_DIR . 'datacash_request.php'; Testing DataCash Integration Now that we have all this in place, it’s important to test it with a few orders. We can do this easily by creating a customer with those magic credit card details. As mentioned earlier in this chapter, DataCash supplies these numbers for testing purposes and to obtain specific responses from DataCash. A sample of these numbers is shown in Table 20-2. A full list is available in the Developer’s Area of the DataCash web site, under the Magic Card Numbers section. Table 20-2. DataCash Credit Card Test Numbers Card Type Card Number Return Code Description Sample Message Switch 4936000000000000001 1 Authorizes with a random AUTH CODE ?????? authorization code 4936000000000000019 7 Declines the transaction DECLINED 6333000000000005 1 Authorizes with a random AUTH CODE ?????? authorization code 6333000000000013 7 Declines the transaction DECLINED 6333000000123450 1 Authorizes with a random AUTH CODE ?????? authorization code Visa 4242424242424242 7 Declines the transaction DECLINED 4444333322221111 1 Authorizes with a random AUTH CODE ?????? authorization code 4546389010000131 1 Authorizes with a random AUTH CODE ?????? authorization code At this moment, we can experiment with the new fully featured e-commerce web site by placing orders with the test credit card numbers, checking the e-mails the web site sends, and finding out how the site reacts in certain situations, such as how it logs errors, how orders are administered using the orders administration page, and so on. www.it-ebooks.info8644ch20FINAL.qxd 1/30/08 12:54 PM Page 642 642 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS Going Live Moving from the test account to the live one is now simply a matter of replacing the DataCash login information in include/config.php with real-world values. After you set up a merchant bank account, you can use the new details to set up a new DataCash account, obtaining new client and password data along the way. You also need to change the URL for the DataCash server that you send data to, because it needs to be the production server instead of the test- ing server. Other than removing the test user accounts from the database and moving the web site to an Internet location, this is all you need to do before exposing the newly completed e-commerce application to customers. Working with Authorize.net To test Authorize.net, you need to apply for a test account at http://developer.authorize.net/ testaccount/. The main page where developers can get information on Authorize.net integra- tion is http://developer.authorize.net/. Communicating with Authorize.net is different from communicating with DataCash. Instead of sending and receiving XML files, we send strings consisting of name-value pairs, separated by ampersands (&). Effectively, we use a similar syntax to query strings appended to URLs. Authorize.net returns the transaction results in the form of a string that contains the return values (without their names) separated by a character that we will specify when making the initial request. In our examples, we’ll use the pipe () character. The return values come in a predetermined order, and their significance is given by their position in the returned string. ■Note The complete documentation for the Authorize.net API can be found in the Advanced Integration Method (AIM) Implementation Guide: Card-Not-Present Transactions at http://www.authorize.net/support/ AIM_guide.pdf. Even more documents are available in the document library at http://www.authorize.net/ resources/documentlibrary/. The default transaction type is AUTH_CAPTURE, where we request and deduct the funds from the credit card using a single request. For TShirtShop, we’ll use two other transaction types: AUTH_ONLY, which checks if the necessary funds are available (this happens in the PsCheckFunds pipeline stage), and PRIOR_AUTH_CAPTURE, which deducts the amount of money that was previ- ously checked using AUTH_ONLY (this happens in the PsTakePayment pipeline stage). To perform an AUTH_ONLY transaction, we’ll first create an array that contains the necessary transaction data: // Auth transaction = array ('x_invoice_num' = '99999', // Invoice number 'x_amount' = '45.99', // Amount 'x_card_num' = '4007000000027', // Credit card number 'x_exp_date' = '1209', // Expiration date 'x_method' = 'CC', // Payment method 'x_type' = 'AUTH_ONLY'); // Transaction type www.it-ebooks.info

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.