1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning PHP and MySQL E-Commerce From Novice to Professional phần 10 pps

71 246 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 71
Dung lượng 2,6 MB

Nội dung

// 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 <frame src="test_datacash.php?step=2"> <frame src="test_datacash.php?step=3"> </frameset> CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 637 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 637 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 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); CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS638 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 638 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com $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); } } ?> CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 639 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 639 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 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); } } ?> CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS640 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 640 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 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. CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 641 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 641 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 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 CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS642 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 642 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com For PRIOR_AUTH_CAPTURE transactions, we don’t need to specify all this information again; we only need to pass the transaction ID that was returned in response to the AUTH_ONLY request. // Capture $transaction = array ('x_ref_trans_id' => $ref_trans_id, // Transaction id 'x_method' => 'CC', // Payment method 'x_type' => 'PRIOR_AUTH_CAPTURE'); // Transaction type We’ll transform these arrays into a string of name-value pairs and submit them to the Authorize.net server. The response comes in the form of a string whose values are separated by a configurable character. Later, in Figure 20-3, you can see a sample response for an AUTH_ONLY request (in the left part of the window) and a sample response for a PRIOR_AUTH_CAPTURE request (in the right part of the window). We’ll write a simple test with this transaction type before implementing any modifications to TShirtShop. Follow the steps in the exercise to test Authorize.net. Exercise: Testing Authorize.net 1. Create a new file named authorize_net_request.php in the business folder, and add the following code to it: <?php class AuthorizeNetRequest { // Authorize Server URL private $_mUrl; // Will hold the current request to be sent to Authorize.net private $_mRequest; // Constructor initializes the class with URL of Authorize.net public function __construct($url) { // Authorize.net URL $this->_mUrl = $url; } public function SetRequest($request) { $this->_mRequest = ''; $request_init = array ('x_login' => AUTHORIZE_NET_LOGIN_ID, 'x_tran_key' => AUTHORIZE_NET_TRANSACTION_KEY, 'x_version' => '3.1', 'x_test_request' => AUTHORIZE_NET_TEST_REQUEST, 'x_delim_data' => 'TRUE', CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 643 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 643 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 'x_delim_char' => '|', 'x_relay_response' => 'FALSE'); $request = array_merge($request_init, $request); foreach($request as $key => $value ) $this->_mRequest .= $key . '=' . urlencode($value) . '&'; } // Send an HTTP POST request to Authorize.net 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 request to be POSTed curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($this->_mRequest, '& ')); // Set the URL where we want to POST our data 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; } } ?> CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS644 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 644 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 2. Add the following at the end of include/config.php file, modifying the constant data with the details of your Authorize.net account: // Constant definitions for authorize.net define('AUTHORIZE_NET_URL', 'https://test.authorize.net/gateway/transact.dll'); define('AUTHORIZE_NET_LOGIN_ID', '[Your Login ID]'); define('AUTHORIZE_NET_TRANSACTION_KEY', '[Your Transaction Key]'); define('AUTHORIZE_NET_TEST_REQUEST', 'FALSE'); 3. Add the following test_authorize_net.php test file in your site root folder: <?php session_start(); if (empty ($_GET['step'])) { require_once 'include/config.php'; require_once BUSINESS_DIR . 'authorize_net_request.php'; $request = new AuthorizeNetRequest(AUTHORIZE_NET_URL); // 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 $request->SetRequest($transaction); $auth_only_response = $request->GetResponse(); $_SESSION['auth_only_response'] = $auth_only_response; $auth_only_response = explode('|', $auth_only_response); // Read the transaction ID, which will be necessary for taking the payment $ref_trans_id = $auth_only_response[6]; // Capture $transaction = array ('x_ref_trans_id' => $ref_trans_id, // Transaction id 'x_method' => 'CC', // Payment method 'x_type' => 'PRIOR_AUTH_CAPTURE'); // Transaction type $request->SetRequest($transaction); $prior_auth_capture_response = $request->GetResponse(); CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS 645 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 645 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com $_SESSION['prior_auth_capture_response'] = $prior_auth_capture_response; } else { switch ($_GET['step']) { case 1: print $_SESSION['auth_only_response']; break; case 2: print $_SESSION['prior_auth_capture_response']; break; } exit(); } ?> <frameset cols="50%, 50%"> <frame src="test_authorize_net.php?step=1"> <frame src="test_authorize_net.php?step=2"> </frameset> 4. Load the test_authorize_net.php page in your favorite browser to see the results (see Figure 20-3). Figure 20-3. Authorize.net transaction results 5. Go to Authorize.net, and log in to the Merchant Interface (https://test.authorize.net/). You can see the transaction you’ve just performed in the Unsettled Transactions section under the Search tab. This report is shown in Figure 20-4. CHAPTER 20 ■ PROCESSING CREDIT CARD TRANSACTIONS646 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 646 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... doesn’t stop us from adding even more features to make it more useful and pleasant for visitors By adding a product reviews system to your web site, you can increase the chances that visitors will return to your site, either to write a review for a product they bought or to see what other people think about that product A review system can also help you learn your customers’ tastes, which enables you to. .. 'ps_check_stock .php' ; require_once BUSINESS_DIR 'authorize_net_request .php' ; 4 Add a reference to the business/authorize_net_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 'authorize_net_request .php' ; 8644ch20FINAL.qxd 1/30/08 12:54 PM Page 653 Simpo PDF Merge and Split Unregistered... product recommendations and even make changes in the web site or the structure of the product catalog based on customer feedback To make things easy for both the customer and us, we’ll add the list of product reviews and the form to add a new product review to the product details pages The form to add a new product will show up for only registered users, because we decided not to allow anonymous reviews... standard Internet protocols such as HTTP The messages exchanged by the client and the server are encoded using an XML-based protocol named Simple Object Access Protocol (SOAP) or by using Representational State Transfer (REST) and are sent to the server over the HTTP protocol REST uses carefully crafted URLs with specific name-value pairs to call specific methods on the servers REST is considered to. .. for purchases made from your web site Sounds like easy money, doesn’t it? In this chapter, you’ll learn how to use AWS to add a special department called Amazon T-Shirts to your web store, which you can see in Figure 22-1 This will be a “special” department in that it will be handled differently from others—for example, payment is handled directly by Amazon.com when the visitor wants to buy a product... review. {/if} The code from the presentation object is pretty straightforward and should not be a problem for you Summary Yep, it was that simple Although you might want to add improvements for your own solution (for example, allow the visitors to edit their reviews, or forbid them from adding more reviews), the base is there, and it works as expected You’re now all set to proceed to the final chapter... what web services are • Learn how to connect to the Amazon E-Commerce Service • Use the Amazon E-Commerce Service to sell Amazon t-shirts through TShirtShop For more information about accessing web services using PHP we recommend you check , out Pro PHP XML and Web Services (Robert Richards Apress, 2006.), which includes examples of accessing the Amazon.com, Google, eBay, and Yahoo web services Introducing... want to make a fortune from this service, dig deeper into additional resources to find more substance Figure 22-1 Integrating the Amazon T-Shirts department into TShirtShop The rest of the chapter is divided into two parts In the first part, you’ll learn how to access AWS; in the second part, you’ll integrate AWS into the TShirtShop web site 8644ch22.qxd 1/30/08 12:56 PM Page 667 Simpo PDF Merge and. .. keywords One trivial way is to use the PHP file_get_contents() function, as you can see in the following script To test accessing web services using REST, create a new file named test_rest .php in your tshirtshop directory, and write the following code in it: < ?php // Tell the browser it is going to receive an XML document header('Content-type: text/xml'); /* DON'T FORGET to replace the string '[Your... tshirtshop database (don’t forget to set the delimiter to $$) When a registered visitor adds a product review, the catalog_create_product_review stored procedure is called Create catalog_create_product_review stored procedure CREATE PROCEDURE catalog_create_product_review(IN inCustomerId INT, IN inProductId INT, IN inReview TEXT, IN inRating SMALLINT) BEGIN INSERT INTO review (customer_id, product_id, review, . complete and functional e-commerce web site. However, this doesn’t stop us from adding even more features to make it more useful and pleasant for visitors. By adding a product reviews system to your. 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. has two important methods: SetRequest(), used to set up transaction details, and GetResponse(), used to send the request to and retrieve the response from Authorize.net. The following code snippet

Ngày đăng: 12/08/2014, 10:21

TỪ KHÓA LIÊN QUAN