Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 76 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
76
Dung lượng
1,55 MB
Nội dung
Figure 13-31 7. Type 2 and click Update. The totals are updated, as shown in Figure 13-32. Figure 13-32 8. Click Delete. The item is removed from your cart. How It Works By adding two bits to the application in this Try It Out, you enabled the whole functionality of the shop- ping cart. You started by adding a button to the Product Item page and creating some code that ran when the button was clicked. The code handles the business of adding an item to your shopping cart. You start by getting the Price, ProductName, PictureUrl and ProductID: double Price = double.Parse(((Label)DataList1.Controls[0].FindControl(“PriceLabel”)).Text); string ProductName = ((Label)DataList1.Controls[0].FindControl(“NameLabel”)).Text; string PictureURL = ((Label)DataList1.Controls[0].FindControl(“PictureUrlLabel”)).Text; int ProductID = int.Parse(Request.QueryString[“ProductID”]); 501 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 501 This information has already been stored in the page. You use the FindControl method of a control to locate a control. The DataList control contains an item template, so you have to move into the controls collection of the DataList control to get at the Label controls. You can cast the contents of the control to text by prefixing them with the control type in brackets. So each of the three lines works like this. You declare a variable in which to store your item. You search the DataList control for your Label control using FindControl, and supply it with the name of the control you want to find. You convert the con- trol from a “generic” control into a specific Label control. (Note that this only works if the control you are casting to actually is a Label control.) So for the Price, you search for the PriceLabel control’s contents and you retrieve the text property of the label. There is actually another level of conversion required here. You want the price as a double data type, so you convert the text item you receive into a double and store it in the double data type. The PictureUrlLabel is the one you didn’t delete in the second Try It Out of this chapter because we said you’d need it later. This is where you need it. Having stored the Price, ProductName, and PictureURL, you still need the ProductID. This can be located in the query string passed to the page: int ProductID = int.Parse(Request.QueryString[“ProductID”]); You check to see if a cart exists for this profile: if (Profile.Cart == null) { Profile.Cart = new Wrox.Commerce.ShoppingCart(); } Profile.Cart.Insert(ProductID, Price, 1, ProductName, PictureURL); Server.Transfer(“WroxShop.aspx”); } If a cart doesn’t exist, you create a new one. Then you need to insert a new item into your shopping cart along with the ProductID, Price, ProductName, PictureURL, and the quantity of 1: Profile.Cart.Insert(ProductID, Price, 1, ProductName, PictureURL); Last, you simply transfer the user back to the initial Product Catalog page: Server.Transfer(“WroxShop.aspx”); This stage can continue cyclically until the user either leaves the application or needs to check out. Checkout Checking out is perhaps the lengthiest stage of the whole process. The checkout process involves a num- ber of considerations, not just the totalling up of the items and how much they cost, but also things like stock availability, getting the user’s address and delivery details, obtaining and verifying payment for the items, and some sort of rounding up of the whole process. Checkout is, in itself, a mini set of stages. If you’re serious about implementing your own e-commerce process, it’s worth checking some of the major e-commerce vendors (such as Amazon), seeing what they do in their checkout process, and asking is it quick and intuitive to use? A lot of time and effort has gone into producing checkout processes that can be completed in the minimum number of steps, with the minimum number of clicks. 502 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 502 In your design, consider checkout as comprising the following: ❑ Order processing ❑ Login ❑ Enter or get the address and delivery details ❑ Get the credit card details ❑ Finish This is one part of the process that is impossible to model completely, without actually building a real, live, working e-commerce site. However, some considerations about each step are worth talking about. Order Processing The first step of the checkout process is to check whether or not the item is in stock. With a large retailer such as Amazon, not all of the items they carry will be sourced by them. They have a range of suppliers, and they often need to check with them first to see if a particular item is in stock. Hence you will find that some products will ship from Amazon within 24 hours, whereas others may take between four and six weeks. In reality there is often another pipeline (similar to Figure 13-33) going on here that has to be negotiated. Figure 13-33 With Wrox United, you’re not going to delve into this level of detail. You are going to assume that all goods are stored in the Wrox United warehouse, and after you’ve checked the stock level and they are in stock, they are good to be released for shipping. Login We’ve already mentioned that the Wrox United application uses one of ASP.NET 2.0’s best features to keep track of the shopping cart, in that you don’t have to physically log in to keep track of your shop- ping cart. However, when you come to checkout, you must log in, because you need to supply your address details and credit card information. You need to supply a login box and password to be able to authenticate your user’s details. You will use the standard ASP.NET 2.0 login control to do this. Address/Delivery Details The address details are fairly easy to sort as well. One of two scenarios could occur. Either you have already captured the user’s details and you can access the details that are stored with the profile, or if you don’t have them on record, you must request that the user enter them into a series of text boxes. You can either use the Profile that was created in Chapter 11 and that stores these details, or you can store the details supplied in the text boxes by the user. Inform Supplier Check Stock Order Ready/Charge CardSupplier Ships Goods Notification Of Shipping 503 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 503 Credit Card Handling Here you’re going to cop out and not handle credit cards at all — you’ll just add a small dummy section. This gives the impression that it isn’t a major part of the e-commerce pipeline, but don’t be fooled for a moment — it is of course critical to the success of the pipeline. For obvious reasons, you can’t set up an actual credit card–handling facility. For starters, you don’t have a physical product to sell. Fetching as the Wrox United kits undoubtedly would be, they only exist in cyberspace. So here we can’t provide any code, but instead can quickly consider what you need to take into account when setting up a credit card–handling facility on your web site. Credit card retailers first starting out need a merchant ID, usually supplied via their bank, which gives some sort of guarantee that the business is genuine. Most Internet businesses require the same thing. In the U.S., there are two ways to do this. The first is to provide all the processing and handling of credit cards yourself, and the second is to get someone else to do it on your behalf. In-House Credit Card Transactions Setting up credit card processing in-house is the ideal way to keep an eye on all your transactions, but it can be quite a slow and unwieldy process. You require an e-commerce ID (also known as a merchant number or as an Internet Merchant Account [IMA] in the UK) from a third party who can actually pro- cess the credit card details for you, meaning the third party can decide whether or not a particular credit card number is genuine. You will have to apply for an account with the third party and provide a lot of details that help establish your authenticity. Obtaining an E-Commerce ID, Merchant Number, or IMA In the U.S., you can go to one of the following web sites: ❑ Verisign/CyberCash: www.icverify.com ❑ First Data/Card Service: www.cardservice.com In the UK, you can go to one of these web sites: ❑ WorldPay: www.worldpay.co.uk ❑ DataCash: www.datacash.com For worldwide transaction processing, you can try PayPal (www.paypal.com), which accepts credit cards once you have set up a business account with them. Payment Gateways After you have your e-commerce ID, merchant number, or IMA, you still need another link in the chain, a way of communicating from a payment gateway to a bank. You should be able to use the same com- pany you obtained an e-commerce ID from to do this. You supply the e-commerce ID to the bank, and they use it to track the money’s movements to the gateway service and back again. These services usu- ally come at a hefty price. If all this sounds too complex, you might want to consider the alternative. Bureau Services Because this is a beginner’s book, it’s probably safe to assume that the first site you start developing won’t be a major store. More likely you’ll be working on a small store (maybe your own) that perhaps 504 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 504 won’t really want to cover the risks and costs associated with having a system handling credit cards itself. In the early days of e-commerce on the web, there were a series of high-profile hacks. One notori- ous one was where all customers of a high-profile music store had their credit card details stolen when the database containing them was compromised. Rather than having to worry about all the risks from encrypting card details to storing them in a way to ensure their complete safety, it’s easier to get some- one else to do this for you. These are termed bureau services. When you get to the part of a site where you check out, instead of handling the details, you link to the bureau service’s site, and they handle the whole process for you from then on. Until relatively recently, bureau services were expensive propositions that required quite a large finan- cial commitment on the part of the seller. Several years ago, I costed a small record label’s ability to do this, and the cheapest I could find to provide an online store would have meant they would have to have sold several hundred CDs a month to cover the gateway fees alone. The rise of eBay has led to a massive rise in demand of people who want to handle their own sales instantly, so rather than having to wait for checks (which carry risk of both fraud and bouncing if the funds aren’t present), or doing money trans- fers via banks or a third party such as Western Union, they want to be able to handle credit card transac- tions. In addition to that, they might only ever want to handle as little as 10 or 20 sales. Two popular solutions supply this service, and can actually supply common components such as a shopping cart for you: ❑ PayPal: www.paypal.com ❑ BTClick&Buy: www.btclickandbuy.com Other sites exist too. There are digital credit card services that specialize in micropayments when paying for small items such as single mp3s. It all depends on what you want to sell and how much you want to sell it for. If these two sites don’t provide a solution that suits you, then look around for something more suited to your needs. If you want further details about how to handle credit card transactions, we sug- gest you read the details given on the sites mentioned in these sections. Summarizing the Transaction Typically, after you’ve completed your transaction, it would be good to receive a notification or receipt of what you’ve ordered. This is actually a relatively simple step of the process, but to e-mail somebody requires a working SMTP server, so for that reason alone, you aren’t going to implement this step. How You Intend to Checkout Once again, you are governed by keeping things simple. What is the minimum you can boil down your checkout process to? The five-stage process will be as follows: ❑ Login ❑ Delivery address ❑ Payment ❑ Confirmation of the order ❑ Finish 505 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 505 You will also need a breadcrumb to you to help you keep an eye on where you are in the whole checkout process. As mentioned at the beginning of the chapter, one priority is being able to abort the transaction at any point prior to confirming the purchase. What you’re not going to do is the stock handling (reducing items and keep track of stock levels) or sending a confirmation-of-order e-mail. The chapter is already big enough as it is and these things are arguably stretched over different disciplines to e-commerce. What you are going to do in the next Try It Out is create the final stages of the e-commerce pipeline. Try It Out Checking Out 1. In Solution Explorer in Visual Web Developer, right-click the C:\ \Chapter13 heading at the top and select Add New Item. Add a Web Form called Checkout.aspx and check the Place Code in Separate File box to ensure a separate code-behind file is created. 2. In Design View, from the Toolbox grab a Wizard control and drop it onto the page, as shown in Figure 13-34. Figure 13-34 3. From the smart tag dialog box, select the Add/Remove wizard steps option. 506 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 506 4. In the dialog box that appears, you are going to add three extra steps. This is so you have five steps: one for login, one for address, one for credit card details, one to confirm the order, and one to finish the transaction. Start by clicking Add (see Figure 13-35) and entering Step 3 next to Title. Then clicking Add again and enter Step 4. Click Add one more time and enter Step 5. Figure 13-35 5. Go back and change the Title property in each so that it reads as shown in Figure 13-36. Figure 13-36 6. Click OK. 7. From the Login section of the Toolbox, drag a Login box into the <asp:Wizard> control, as shown in Figure 13-37. 507 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 507 Figure 13-37 8. Click Source View. Add the following code to the Wizard step for Step 2 (Delivery Address): <asp:checkbox id=”chkUseProfileAddress” runat=”server” autopostback=”True” text=”Use membership address” OnCheckedChanged=”chkUseProfileAddress_CheckedChanged”></asp:checkbox><br /> <table border=”0”> <tr><td>Name</td><td><asp:textbox id=”txtName” runat=”server” /></td></tr> <tr><td>Address</td><td><asp:textbox id=”txtAddress” runat=”server” /></td></tr> <tr><td>City</td><td><asp:textbox id=”txtCity” runat=”server” /></td></tr> <tr><td>County</td><td><asp:textbox id=”txtCounty” runat=”server” /></td></tr> <tr><td>Postcode</td><td><asp:textbox id=”txtPostCode” runat=”server” /> </td></tr> <tr><td>Country</td><td><asp:textbox id=”txtCountry” runat=”server” /></td></tr> </table> 9. Add the following code to the Wizard step for Step 3 (Payment): <asp:DropDownList id=”lstCardType” runat=”server”> <asp:ListItem>MasterCard</asp:ListItem> <asp:ListItem>Visa</asp:ListItem> </asp:DropDownList> <br /> Card Number: <asp:Textbox id=”txtNumber” runat=”server” Text=”0123456789” ReadOnly=”True”/> <br /> Expires: <asp:textbox id=”txtExpiresMonth” runat=”server” columns=”2” /> / <asp:textbox id=”txtExpiresYear” runat=”server” columns=”4” /> 508 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 508 10. Go back to Design View for Step 4 (Confirmation). Type the following: Please confirm the amount you wish to have deducted from your credit card. 11. Select ShoppingCart.ascx and drag it into the Wizard control above the text you have cre- ated, as shown in Figure 13-38. Figure 13-38 12. Click Complete and in Design View for Step 5 (Complete), type Thank you for your order. 13. Go to Source View and above the <asp:Wizard> control, add the following: <asp:Label id=”NoCartlabel” runat=”server” visible=”false”> There are no items in your cart. Visit the shop to buy items. </asp:Label> <div style=”float:right”> <asp:LoginView ID=”LoginView1” Runat=”server”> <AnonymousTemplate> <asp:passwordrecovery id=”PasswordRecovery1” runat=”server” /> </AnonymousTemplate> </asp:LoginView> </div> 14. Above this code, add the following: <%@ Import Namespace =”System.Data.SqlClient”%> <%@ Import Namespace =”Wrox.Commerce”%> 509 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 509 15. Save the design. 16. Go to Solution Explorer, and select checkout.aspx.cs. 17. Add the following code-behind in place of whatever is already there: using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using Wrox.Commerce; using System.Web.UI.WebControls; using System.Web.Security; public partial class Checkout : System.Web.UI.Page { void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Profile.Cart == null) { NoCartlabel.Visible = true; Wizard1.Visible = false; } if (User.Identity.IsAuthenticated) { Wizard1.ActiveStepIndex = 1; } else { Wizard1.ActiveStepIndex = 0; } } } protected void chkUseProfileAddress_CheckedChanged(object sender , System.EventArgs e ) { // fill the delivery address from the profile, but only if it’s empty // we don’t want to overwrite the values if (chkUseProfileAddress.Checked && txtName.Text.Trim() == “”) { txtName.Text = Profile.Name; txtAddress.Text = Profile.Address; txtCity.Text = Profile.City; txtCounty.Text = Profile.County; txtPostCode.Text = Profile.PostCode; txtCountry.Text = Profile.Country; } } protected void Wizard1_FinishButtonClick( object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e) 510 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 510 [...]... created, with the addition of an ORDER BY clause to order the results by the product name This is a good way to combine the ease of data source controls with stored procedures — let the designer create the control, and then copy the SQL statement into a stored procedure and use the procedure name in the data source control The column Name is wrapped within square brackets because Name is a keyword within... scared you away E-commerce is a lengthy and complex process — however, the new features of ASP.NET 2.0 make it approachable and possible to program for the first time without weeks of heartache and stress Although e-commerce isn’t something to be taken lightly, it is something that can be added to an application with a little bit of thought and careful work This chapter started by describing the e-commerce... procedure, you open it (double-click or right-click and select Open from the menu) from within the Database Explorer, where you will be presented with the following: ALTER PROCEDURE dbo.usp_Products AS SELECT ProductID, Name, Description, Price, PictureURL FROM Products ORDER BY Name Notice that CREATE PROCEDURE has been replaced with ALTER PROCEDURE The CREATE statement is only used when creating stored procedures,... with the following code: CREATE PROCEDURE dbo.usp_NewsInsert @DateToShow datetime, @Description text, @PictureUrl varchar(50), @Category varchar(50), @Title varchar(50) AS INSERT INTO News(DateToShow, Description, PictureUrl, Category, Title) VALUES (@DateToShow, @Description, @PictureUrl, @Category, @Title) 8 9 Save and close the procedure Create another new procedure, replacing the default text with. .. control The column Name is wrapped within square brackets because Name is a keyword within SQL The stored procedure works without the brackets, but using them tells SQL Server that this use of Name is a column, and saves SQL Server having to work that out on its own The procedure name starts with usp_ for usability and historic reasons You don’t want your stored procedure to have the same name as the table,... name is useful, because it helps to identify which stored procedures are related to which tables In SQL Server, the system-stored procedures start with sp_ (an acronym for stored procedure), so using that as a prefix would confuse your stored procedures with the system ones So usp_ (an acronym for user stored procedure) is generally used instead This isn’t a requirement, but you’ll find that it is... is generated from sourceImage using GetThumbnailImage with the new width and height This creates a new image based on the new size After it is generated, targetImage is then saved to a file as a GIF image The finally blocks of each try/catch check that the Image object exists before disposing of the object, by calling the Dispose method Disposal with Using The using statement makes the preceding code... because it presents you with an easy-to-understand graphical way of designing queries, and shows the actual SQL statement When the Query Builder is closed, the SQL is inserted into the stored procedure It doesn’t update the existing SQL but inserts the new SQL instead If you want to use the Query Builder to edit the existing SQL in a stored procedure, you need to place the cursor within the SQL block... of these items specifically required the use of the shopping cart, so you held off creating one They just queried the database and displayed the relevant details However, without these pages, you would not be able to shop effectively With a catalog working, you could add the cart The cart consisted of two objects: the CartItem object (one for each item selected by the user from the catalog and the ShoppingCart... Next you created a checkout process that handled the login, the confirmation of the delivery address, and the credit card details, and finished the procedure Although you couldn’t handle the card details with the application, you learned about the various options offered Finally you learned how to make the transactions secure and some ways to extend and improve the e-commerce procedure in Wrox United Exercises . details. 513 E-Commerce 16 _0 425 83 ch13.qxd 4/4 /06 2: 50 PM Page 513 Figure 13-39 Figure 13- 40 Figure 13-41 514 Chapter 13 16 _0 425 83 ch13.qxd 4/4 /06 2: 50 PM Page 514 22 . Click Next. On the last page (see Figure 13- 42) ,. customer bought a replica kit in 20 04, when the 20 05 version comes out, it might be good to e-mail them). 5 20 Chapter 13 16 _0 425 83 ch13.qxd 4/4 /06 2: 50 PM Page 5 20 . that can be completed in the minimum number of steps, with the minimum number of clicks. 5 02 Chapter 13 16 _0 425 83 ch13.qxd 4/4 /06 2: 50 PM Page 5 02 In your design, consider checkout as comprising