Chapter 9. Online Store

Many businesses, both large and small, would like to take better advantage of their web presence by selling their products or services directly online. Setting up ecommerce, however, can be a very daunting task. There are several options with varying complexity. Many hosting providers offer ecommerce or “shopping cart” packages that may be either included with your web hosting plan or available for purchase. With other services, such as PayPal, you can enable online purchases by using an HTML form that submits to their processing system. There are still more options for using dedicated ecommerce packages, both open source and proprietary, that you host and configure. The biggest issue with all of these methods tends to be the lack of integration with the rest of the website—all shopping cart and checkout functions take place within the other, external system.

This chapter will introduce the following modules:

Drupal Commerce (http://drupal.org/project/commerce)

Provides a full ecommerce package for running an online store

Feeds (http://drupal.org/project/feeds)

Provides data import capabilities for Drupal

Rules (http://drupal.org/project/rules)

Provides a means of clicking together custom programming logic

To follow along with the hands-on examples in this chapter, install Drupal using the Online Store installation profile, which installs Drupal with a few sample users and basic settings, as shown in Figure 9-1 and found at http://store.usingdrupal.com. For more information on using the book’s sample code, see the Preface.

Sweet Tees’ completed website

Figure 9-1. Sweet Tees’ completed website

Note

There are two highly useful resources to have nearby as you’re learning your way through Drupal Commerce. The first is the official Drupal Commerce website at http://www.drupalcommerce.org/, which contains documentation, a list of add-on modules, and other great stuff. The second is http://www.commerceguys.com/, which contains a series of screencast tutorials on how to do various tasks in Drupal Commerce that fall outside the scope of this chapter.

Case Study

Sweet Tees is a local T-shirt store that sells wildly popular, custom-printed T-shirts. It has a physical storefront, and the owners enjoy running a small store and love their current location. However, they get frequent mail-order requests for their shirts and stickers, and would like to grow that end of the business. Taking orders on the phone and tracking sales has proven to be inefficient and time-consuming for both them and their customers.

In order to increase sales, we will equip the Sweet Tees website with an online store that has integrated shopping cart functionality, where visitors to the site can add items to their cart without the hassle of having to create an account first. A shopping cart should be visible on all pages with a link to “check out” at any time. The store needs to flow seamlessly with the existing website so that customers have a consistent experience. Sweet Tees would like to make the checkout process as simple as possible, so we will also need to make sure we provide them with a single-page checkout, without requiring customers to create a user account. Finally, they wish to accept credit cards on their orders, so we will need to set up a payment gateway for this purpose.

Implementation Notes

Sweet Tees has several options to manage their online store; however, they really want to provide a seamless, user-friendly experience for their customers. They are looking for a solution that is simple and elegant, yet also comprehensive.

For Drupal, there are two primary ecommerce solutions, both of which consist of several modules, to implement the various features required.

Ubercart (http://drupal.org/project/ubercart), the premier ecommerce solution in Drupal 6, aims to provide a simplified installation, configuration, and management process. Ubercart also has some features that make it attractive for our implementation: a single-page checkout process, anonymous user purchases, and a nice administration interface.

Drupal Commerce (http://drupal.org/project/commerce) is a highly customizable ecommerce framework that was developed by Ubercart’s former lead developer, and is a ground-up rewrite of Ubercart that makes use of modern Drupal 7 constructs such as entities and fields, views, and rules. Drupal Commerce takes a “framework” approach to building out an ecommerce site, allowing the ultimate in customizability and flexibility to support everything from standard product-based stores to subscription websites.

For Sweet Tees, we will be using Drupal Commerce due to its native support of Drupal 7, and its inherent flexibility, which will help them handle any future requirements.

Note

Thanks to its five-year head start, Ubercart generally has more add-on modules available than Drupal Commerce, a fact that may make our choice a bit puzzling. However, the broader Drupal developer community effort is much more focused on Drupal Commerce, making it the more future-proof choice for Drupal 7 sites.

Spotlight: Drupal Commerce

Drupal Commerce is a complete package for running an online store. As such, it actually contains numerous submodules that each implement features of an online store, and can be turned on or off depending on the precise functionality required. In this section, we’ll look at each module in turn, and outline its purpose and where it fits.

Note

If you’d like to play with a quick demonstration of the Drupal Commerce module, try installing the Commerce Kickstart installation profile at http://drupal.org/project/commerce_kickstart.

Commerce and Commerce UI

Commerce is a required module that provides the underlying APIs and functionality for the Drupal Commerce suite as a whole, and doesn’t provide much in the way of configurability. The Commerce UI module provides the main Store (admin/commerce) configuration panel, pictured in Figure 9-2.

Note

Nearly all modules in the Drupal Commerce package are split into both a “functional” module and a “UI” module. This is to allow other contributed or custom modules to potentially replace the default user interface with one more streamlined to a particular use case.

Commerce UI provides the default Store management screens

Figure 9-2. Commerce UI provides the default Store management screens

Cart

Cart handles the shopping cart, pictured in Figure 9-3, and provides features such as a handy sidebar block showing cart contents on all pages, and the ability for customers to add or remove cart contents. Both the block and checkout page are views, so you can customize the precise fields and order they’re displayed in, just like any other listing built in the Views module.

The Cart module also exposes a number of events and actions that can trigger system behavior through the Rules module. For example, for a site selling multiple subscription levels, it might make sense to remove the old subscription level from the cart when adding a different subscription.

The shopping cart page and sidebar block provided by the Cart module

Figure 9-3. The shopping cart page and sidebar block provided by the Cart module

Checkout

The Checkout module, pictured in Figure 9-4, handles the display of the checkout screens, as well as the overall checkout process. There are four stages to the checkout process: “Checkout” (where billing information and payment details are typically gathered), “Review order” (which allows the customer to check over her order one last time before being charged), “Payment” (where the actual charging takes place), and “Checkout complete” (where final notifications and next steps are explained). The information displayed on each page (e.g., cart contents, billing information) is encapsulated in “checkout panes,” the visibility and order of which are configurable in the store settings, as pictured in Figure 9-5. One example of where this flexibility could come in handy is in a site selling memberships; since these aren’t “products” in the traditional sense, it may not make sense to show the cart contents on the checkout page.

One other very nice feature of the Checkout module, thanks to the Address Field module it lists as a dependency, is its ability to autopopulate proper address fields based on country selection—for example, “State” and “Zip code” for United States addresses, but “Province” and “Postal Code” for Canadian addresses.

Customer and Customer UI

The Customer module exposes an entity type called Customer Profile, which can be used to store information a customer must fill out during the checkout process. By default, Drupal Commerce ships with a profile type called “Billing information,” pictured in Figure 9-4. However, other modules—such as Commerce Shipping, which exposes a profile type called “Shipping information”—may offer additional types as well. Because customer profiles are entities, they may have other fields added to them, such as phone number or Tax ID.

Checkout panes are provided by the Checkout module

Figure 9-4. Checkout panes are provided by the Checkout module

The page elements (“checkout panes”) to show during the checkout process, as well as their order, are configurable in the Checkout module settings

Figure 9-5. The page elements (“checkout panes”) to show during the checkout process, as well as their order, are configurable in the Checkout module settings

Order, Order UI, Line Item, and Line Item UI

The Order and Line Item modules are responsible for recording, tracking, and managing individual orders to the store. Figures 9-6 and 9-7 show the default user interface for managing orders, provided by the Order UI and Line Item UI modules. You can view orders that are completed as well as those still in the shopping cart phase, and you can also create and edit orders manually—for example, to accept orders over the phone.

Orders overview listing page

Figure 9-6. Orders overview listing page

A sample order

Figure 9-7. A sample order

Payment and Payment UI

There are a number of add-on modules that expose different sorts of payment types to Drupal Commerce, including PayPal, Authorize.Net, and CyberSource. Check http://www.drupalcommerce.org/faq/payment-methods for a full listing.

Payments are configured with the Rules module, covered in Spotlight: Rules Module, which provides nearly limitless customizability over specific business logic requirements.

Product and Product UI

Something that’s pretty essential to any store is cataloguing all of the products it sells. In Drupal Commerce, this capability is provided by the Product module.

Products in Drupal Commerce are entities, which means you can create different product types (e.g., Book, Music, Event Registration), and add more fields to those product types. All products in Drupal Commerce have a set of basic, required fields: Product SKU, Title, Price, and Status. Figure 9-8 shows an example of a product type with an image field added to it.

A sample product form including both the standard, required fields as well as an extra image field

Figure 9-8. A sample product form including both the standard, required fields as well as an extra image field

Like elsewhere in Drupal Commerce, the default product view exposed by the optional Product UI module, pictured in Figure 9-9, can be customized with the Views module. This allows you to add extra fields, expose filters for product type or keyword search, or whatever else you can envision doing with Views.

The default view from the Product UI module

Figure 9-9. The default view from the Product UI module

Product Reference

The Product Reference module exposes a field that can be placed on content types. A content type with a product reference field is called a product display, and it handles output of the raw product data to customers, as well as the display of the “Add to Cart” button. We’ll go into more detail about products and product displays in the next Spotlight section, Spotlight: Managing Products with Drupal Commerce.

Price, Product Pricing, and Product Pricing UI

This set of modules enables a store site owner to establish how much things cost—a rather important functionality in an online store! These modules provide Rules elements, such as the ability to react when the price of goods is being calculated. Most of the rest of the Commerce suite relies on these modules.

Tax and Tax UI

Drupal Commerce supports both Sales and VAT tax calculations, using the Rules module to allow for special cases, such as different sales taxes in different states, or a higher tax for certain types of items.

Additional Drupal Commerce Add-Ons

If the modules that come with Drupal Commerce aren’t quite enough for your needs, there is also a rich library of contributed add-ons at http://www.drupalcommerce.org/contrib. Here you’ll find payment processor modules for services such as Authorize.Net and PayPal, modules to facilitate shipping and stock keeping, and modules that provide new features such as the ability to purchase and spend points or keep wishlists.

Spotlight: Managing Products with Drupal Commerce

Before we get to the first step in creating our store—adding products—it’s worth taking some time to discuss and understand how Drupal Commerce treats products within the system. While product management may appear unintuitive at first, the product management features in Drupal Commerce are designed to allow for maximum flexibility.

Products and Product Types

Products in Drupal Commerce are entities, which means that you can do anything with products that we’ve done with entities in the rest of this book, such as add fields to hold additional properties, display products in listings with the Views module, and so on. This seamless integration of store products with the rest of the content that Drupal can manage is a killer feature of Drupal Commerce.

All product types share a common set of required fields, which are:

Product SKU

A unique identifier for a product. Some stores might choose to make this the same as the UPC code, in the case of a physical product, but others may create their own naming convention, such as BOOK-123456789-A.

Title

The title describes the unique product configuration in human-readable terms, and is used in content listings to identify the product to store administrators.

Price

The product base price, which defaults to the site’s default currency.

Status

Either Active or Disabled. If a product is marked as Disabled, it cannot be added to the shopping cart (the “Add to Cart” button is replaced with a “Product not available” message). Product status can also be used as a filter in Views to remove disabled products from listing pages.

By default, Drupal Commerce provides a sample product type called Product. This is sufficient if you are only selling one style of product in your store, such as a club membership. Many online stores are more complex, however. Amazon.com sells books, movies, and, as we saw in Chapter 5, kitchen utensils (among other things). Books have properties like “author” and “ISBN,” and movies might have properties like “rating” and “movie studio.” Can you imagine how long the product form would be if it needed to provide a field for every single one of these properties for all possible types of products? No, thanks.

Luckily, the Drupal Commerce developers have a solution to this predicament: you can create as many product types as you’d like, and uniquely customize the fields on each of those product types. Other examples of product types might be Book, Music, Event Ticket, or Donation. A Book product type might have fields like Author and Publisher, whereas a Music product type could have Artist and Label. And the two product types might share an image field to facilitate showing them together in product listings.

Note that you must create a unique product with a unique SKU for each configuration of each product. Let’s say your store is selling movies. If each movie comes in VHS, DVD, or Blu-Ray format, that’s three different products with three different SKUs per individual movie title. If each format also comes in English, Spanish, or French, that’s nine different products with nine different SKUs. And if your store sells 3,000 movies, all in all that’s 27,000 products with 27,000 SKUs. Egads! As you can well imagine, it can become tedious to enter that much data by hand. We’ll cover bulk-importing product data in Hands-On: Bulk-Importing Product Data.

Hands-On: Products and Product Types

The first step in setting up our online T-shirt store is to turn on a formidable array of modules to enable the Drupal Commerce module, and then set up product types for the merchandise that Sweet Tees sells: T-shirts and stickers.

Initial Setup Tasks

  1. Log into the Sweet Tees site as the “admin” user if you have not done so already.

  2. Go to the Modules (admin/modules) page and enable the Product UI module. Choose Continue at the prompt to enable the large number of dependent modules (Commerce, Entity API, Rules, Entity tokens, Commerce UI, Product, Price, Views, and Chaos tools).

Configuring Product Types

  1. Go to StoreProducts (admin/commerce/products), the main product admin panel, and click the Product Types tab. By default, you’ll see a single product type listed there called Product. That’s a bit too generic for our tastes, so click the Delete link to remove it.

  2. Click “Add product type” and give it a Name of “T-shirt” and Description of “Our award-winning T-shirts.” Then click “Save and add fields.” At the Managed Fields screen for T-shirt (admin/commerce/products/types/t-shirt/fields), pictured in Figure 9-10, you’ll see we already have a few fields predefined: Product SKU, Title, Price, and Status.

    Default fields available to product types

    Figure 9-10. Default fields available to product types

  3. Add two new fields—Size and Color—to the T-shirt product type, using the values in Tables 9-1 and 9-2, respectively.

    Table 9-1. Settings for the T-shirt product type’s Size field

    Field

    Value

    Label

    Size

    Machine name

    size

    Field type

    List (text)

    WidgetSelect list
    Allowed values list

    S

    M

    L

    XL

    Required fieldChecked

    Table 9-2. Settings for the T-shirt product type’s Color field

    Field

    Value

    Label

    Color

    Machine name

    color

    Field type

    List (text)

    WidgetSelect list
    Allowed values list

    White

    Black

    Required fieldChecked
  4. We also want to add an image field, but thanks to the default Article content type, we already have one we can use. Under “Add existing field,” choose “Image: field_image (Image)” as the field to share, then provide a Label of “Image” and click Save. Leave the default settings.

  5. Finally, reorder the fields as indicated in Figure 9-11 (Product SKU, Title, Price, Image, Size, Color, and Status), and click Save.

    The completed T-shirt product type with reordered fields

    Figure 9-11. The completed T-shirt product type with reordered fields

  6. Return to the main Product Types screen and create a second product type at “Add product type” (admin/commerce/products/types/add) for Sticker. Give it a Name of “Sticker” and Description of “A sticker with a witty phrase.” We can just keep the default fields here, so simply click “Save product type.”

  7. As you did with T-shirt, add the existing image field to Sticker, leave the default settings, and drag it just above Status in the list of fields.

  8. When finished, your product types screen (admin/commerce/products/types) should look as pictured in Figure 9-12.

Product types for the Sweet Tees store

Figure 9-12. Product types for the Sweet Tees store

Creating Sample Products

Now that we have our product templates created, let’s work on populating some store content!

  1. Go to StoreProducts (admin/commerce/products) and click the “Add a product” link (admin/commerce/products/add) to see a menu of available product types.

    Note

    Since you’ll return to this screen fairly often over the course of managing your online store, you might want to hover over the plus sign (+) next to “Add a product” and click “Add to Default shortcuts” so the link is easily accessible from all pages in Drupal’s Shortcut bar at the top of the screen.

  2. Let’s start with a sticker, since that’s nice and easy. Click Create Sticker (admin/commerce/products/add/sticker). Give it the values in Table 9-3 and click “Save product.”

    Table 9-3. Values for a sample Sticker product

    Field

    Value

    Product SKU

    STICKER-001

    Title

    Druplicon sticker

    Price

    10.00
    Image(Upload the drupal-sticker.png file from the assets/ch09-store folder.)
    StatusActive (default)

    Note

    In almost all cases, you’ll leave the Status field as Active. The Disabled status is useful in the case of items that are discontinued. You wouldn’t want to delete the product, as that could destroy customer order data. Setting the product as Disabled will ensure it can’t be added to anyone’s shopping cart and will hide it from view.

  3. Now let’s add a T-shirt by clicking “Add a product” and then Create T-shirt (admin/commerce/products/add/t-shirt). Give it the values in Table 9-4 and click “Save product.”

    Table 9-4. Values for a sample T-shirt product

    Field

    Value

    Product SKU

    TSHIRT-001-M-WH

    Title

    Druplicon T-Shirt - Medium White

    Price1.99 (Note: this is a deliberate typo that we will fix in the next section!)
    Image(Upload the druplicon-tshirt-white.png file from the assets/ch09-store folder.)
    SizeM
    ColorWhite
    StatusActive (default)

    Note

    As mentioned in Spotlight: Drupal Commerce, Drupal Commerce needs one product with a unique SKU per product configuration. Our T-shirt store sells both multiple sizes (S, M, L, XL) and multiple colors (White, Black) of each of the three T-shirt designs. As a result, if we keep going along with this example, we would have to enter in a whopping 24 products by hand. Yowza! Let’s hope Sweet Tees doesn’t think about adding any new T-shirt designs or, heaven forbid, decide to offer women’s and children’s styles of each design as well!

    Luckily, there’s a way to bulk-import lots of products at once, which will be the focus of the next section of this chapter.

  4. Now that we’ve entered a couple of products, our product administration screen at StoreProducts (admin/commerce/products) should look as pictured in Figure 9-13.

Sample products for the Sweet Tees store

Figure 9-13. Sample products for the Sweet Tees store

Note

Remember: nearly all listing pages in Drupal Commerce are Views, including the product overview page. You can easily customize this page to add extra columns for the Image, Size, and Color fields; add an exposed filter or two to restrict the list by certain product types or provide a keyword search; or anything else you do with Views module. Be creative!

Of course, a company like Sweet Tees has many more products than just a single sticker and T-shirt they’d like to sell. However, entering their entire inventory by hand will quickly become tedious and carpal tunnel–inducing. Luckily, using standard Drupal data import tools, we have a solution to this problem.

Spotlight: Feeds Module

The Feeds module provides the capability to ingest data from any number of different sources and transform it into native Drupal constructs. It’s a versatile tool that can be used for things such as large-scale data migration, automatically populating a block of recent content from external sites, or synchronizing content posted among multiple sites.

Among its features are the ability to scan incoming data for already existing content and decide whether to ignore it or merge in the defaults. Content ingestion can be scheduled and queued, even for large jobs.

The Feeds module works by creating one or more “importers” to do the data ingestion. Importers have three basic components: the Fetcher, the Parser, and the Processor.

Fetcher

This component defines how the Feeds module should bring in the feed data. The default options are either “File upload,” which provides a field to upload a file from the computer’s hard drive (perfect for things like comma-separated values [CSV] files or XML), or “HTTP fetcher,” which provides a field to enter a URL of a remote data feed, such as http://drupal.org/node/feed.

Parser

When provided the format of the feed, the parser reads it into logical chunks. The default options are: “Common syndication parser” (handles RSS and Atom), “CSV parser” (for files stored with comma-separated values), “OPML” (Outline Processor Markup Language, a common format for sharing hierarchical lists), and “Sitemap” (which can read feeds stored in the http://www.xml-sitemaps.com/ format).

Processor

The processor turns data coming in from a feed parser into native Drupal structures. By default, processors are included for Nodes, Taxonomy Terms, and Users.

Figure 9-14 shows the default feed importer settings. This configuration creates an importer that fetches an RSS or Atom feed from a URL every 30 minutes, then imports the contents into Drupal as nodes. The fetcher, parser, and processor settings can then be customized to allow for other behaviors.

A feed importer showing default options

Figure 9-14. A feed importer showing default options

There are also several contributed modules that can extend the Feeds module’s capabilities. For example, the “Feeds YouTube parser” module (http://drupal.org/project/feeds_youtubehttp://drupal.org/project/feeds_comment_processor) provides the capability to read feeds of videos from YouTube; the “Feeds Comment Processor” module (http://drupal.org/project/feeds_comment_processor) allows importing feed content as comments; and the “Feeds Directory Fetcher” module (http://drupal.org/project/feeds_fetcher_directory) can monitor a directory for new files and turn them into a feed for parsing.

Note

Another option for data imports is using the Migrate module, and the Commerce Migrate module, which adds support for Drupal Commerce and Ubercart data migrations. These are particularly useful for larger-scale data migrations from legacy systems, and for situations where a lot of data needs to be transformed in order to be suitable for Drupal.

Hands-On: Bulk-Importing Product Data

Now that we’re familiar with the Feeds module’s data import tools, let’s turn our attention to importing T-shirt products for Sweet Tees.

Sweet Tees has kindly furnished us with a comma-separated values (CSV) file containing all of their T-shirt product data for this purpose. CSV is a common data export format from databases and spreadsheet programs. A CSV file is a simple text file that encodes a data set with each record on its own line, and a separator (such as a comma or tab) between the data values. We’ll examine the contents of this file more closely in Mapping CSV Data to Drupal Commerce Products.

We’ll use the Commerce Feeds module for this purpose, which provides two new Feeds processors: Commerce Customer Profile processor and Commerce Product processor.

Note

To follow along with this example, you will need the using_drupal_tshirts.csv file from the book’s source code, found in the assets/ch09-store folder.

Creating a Feed Importer for CSV Files

  1. Go to the Modules page and enable the following modules:

    • Commerce (contrib) package

      • Commerce Feeds

    • Feeds package

      • Feeds

      • Feeds Admin UI

    • Other package

      • Job Scheduler

  2. Go to StructureFeeds Importers (admin/structure/feeds) and click the “New importer” tab (admin/structure/feeds/create).

  3. Fill out the form with the values in Table 9-5 and click the Create button.

    Table 9-5. Settings for the Product importer

    Field

    Value

    Name

    T-shirt importer

    Description

    Import the Sweet Tees T-shirt catalog from CSV file.

  4. At the next screen, there is a table with many settings, most of which can be ignored. “Basic settings” allows you to configure things like how often to import from a feed and whether the process should happen in the background or immediately upon form submission. Then the Fetcher, Processor, and Parser sections affect the settings for each of those components.

  5. Under Fetcher, click Change, choose “File upload” instead of “HTTP fetcher,” and click Save. While the “HTTP fetcher” option would be useful for reading in feed data from a remote URL, the Sweet Tees product list is in a CSV file sitting on your computer’s hard drive, so it makes sense to show a file upload field instead of a URL field. If you wish, you can click Settings for the file upload fetcher to configure additional settings such as what file extensions are allowed, but that’s unnecessary for this example.

  6. Under Parser, click Change, choose “CSV parser,” and click Save. Once again, you can click Settings for the CSV parser to change options such as what delimiter is used in the file, but we don’t need to do that here.

  7. Under Processor, click Change, choose “Commerce Product Parser,” and click Save. The CSV items will now be imported as Drupal Commerce products, not nodes.

  8. Click the Settings link next to “Commerce Product processor,” enter the values found in Table 9-6, and click Save.

    Table 9-6. Settings for the Commerce Product processor

    Field

    Value

    Update existing commerce products

    Update existing products

    Text format

    Plain text (default)

    Product type

    T-shirt
    Authoradmin

    Note

    The one value worth mentioning here is “Update existing commerce products.” This value means that if incoming product data from the feed matches existing data within Drupal, the values coming in from the feed will “win” and override the site’s data. In this case, we want that, since it’s an initial import of the CSV data. In future imports, however, we’d probably want to leave that at “Do not update existing products” so only new products are added.

  9. When completed, the settings along the left side should look as shown in Figure 9-15.

Settings for the product feed importer

Figure 9-15. Settings for the product feed importer

Mapping CSV Data to Drupal Commerce Products

Now for the fun part: telling the Feeds module how to take incoming CSV data and turn it into Drupal products!

  1. Click the Mapping link next to the Commerce Product processor on the T-shirt importer edit page to view the “Mapping for Commerce Product processor” page (admin/structure/feeds/edit/t_shirt_importer/mapping).

  2. Take a peek inside the using_drupal_tshirts.csv file and examine its contents. Of particular note is the first row of the file, which lists the columns of the incoming data: SKU, Title, Price, Size, Color, and Image. These are the “source fields” we need to map. Here is an excerpt:

    SKU,Title,Price,Size,Color,Image
    TSHIRT-001-S-WH,Druplicon T-Shirt - Small White,1699,S,White,
        http://usingdrupal.com/sites/default/files/v7/ch09-store/druplicon-tshirt...
    TSHIRT-001-M-WH,Druplicon T-Shirt - Medium White,1499,M,White,
        http://usingdrupal.com/sites/default/files/v7/ch09-store/druplicon-tshirt...
    TSHIRT-001-L-WH,Druplicon T-Shirt - Large White,1499,L,White,
        http://usingdrupal.com/sites/default/files/v7/ch09-store/druplicon-tshirt...

    Note that the data intentionally charges more for Small shirts—both to show that it can be done, and also because skinny people have it way too easy in life.

    Note

    The first question you might reasonably ask is, “What’s up with those weird prices?” Because Drupal Commerce supports multiple currencies, and different currencies have different rules on how they’re formatted, the developers made the decision to store all pricing data in the “minor unit” of the amount (so the price in cents, in the case of US or Canadian Dollars). If your incoming data stores price information in the more predictable “16.99”-style format, try the Feeds Tamper module for manipulating the source data before it hits the Feed parser.

  3. Back in Drupal, examine the values under the “Select a target” drop-down: Product SKU, Product Title, and so on. These are the “target fields” in products, to which the source data will be mapped.

    Note

    If you find yourself puzzled by some of the options here, such as GUID, there’s a handy Legend fieldset down below that contains descriptions of each target.

  4. One after another, add the source-to-target mappings indicated in Table 9-7 by typing the name of the Source field from the CSV file, selecting the name of the Target field from the drop-down box, and clicking the Add button. If you make a mistake, check Remove next to the field and click the Save button at the bottom of the form.

    Table 9-7. Source-to-target mappings for product import

    Source

    Target

    SKU

    Product SKU

    Title

    Product title

    PricePrice: Amount
    SizeSize
    ColorColor
    ImageImage
  5. Check the Unique Target checkbox next to the SKU field and click Save, to indicate that this value uniquely identifies each record.

  6. When your mapping configuration is finished, your screen should look as pictured in Figure 9-16.

Mapping for the T-shirt feed importer

Figure 9-16. Mapping for the T-shirt feed importer

Importing CSV Product Data

And now, the moment we’ve all been waiting for.

  1. Close out of the Feeds administration screen and go to Import (import) in the Navigation block, then click on “T-shirt importer” (import/t_shirt_importer).

  2. Click “Choose file” on the File field and point it to the using_drupal_tshirts.csv file, then click Import.

  3. A progress bar should appear for a few seconds, and then you should see a notification that Drupal created 23 commerce products, and updated 1 commerce product. Score! Let’s check it out.

    Note

    If anything goes awry here, the Delete Items tab will present an option to remove all imported values and try again.

  4. To confirm, head to StoreProducts (admin/commerce/products), which should appear similar to Figure 9-17. You should see a heck of a lot more products there than before, and our previously mistyped $1.99 T-shirt from earlier should now be the correct $14.99 price. Yippee!

Mapping for the product feed importer

Figure 9-17. Mapping for the product feed importer

Spotlight: Building the Storefront and Shopping Cart

Now that all of this groovy product data is showing up fine in the administrative interface, there’s just one problem: how do we expose these products on our public website to our customers? And further, how do we avoid displaying a product catalog with 25 entries in it, when from a customer’s point of view we only sell four products (three T-shirts and a sticker)?

Drupal Commerce’s “Products” concept essentially acts as your “warehouse” or “product catalog”: any and all items your store sells or has sold in the past should be represented in Drupal as products. However, that only gets you part of the way there: while your products will show up great in the administrative listings, they’re not visible on the site and your users can’t actually purchase them yet. Additionally, in our movie store example, paging through 27,000 products with titles like “Airplane! Blu-Ray Spanish Version” and “Airplane! DVD English Version” won’t make much sense to our customers. They’ll simply want to search for individual movie titles, and then choose the format and language they want as they’re adding the movie to their shopping cart.

The way Drupal Commerce facilitates both of these needs is through the use of one or more content types with a Product Reference field attached. The Product Reference field can group together one or more products into a single product display node, and mark the required fields in those products as attributes (for example, the Size field on a T-shirt) and expose them as attribute selection fields on the “Add to Cart” form. Updating these fields will also switch product-specific properties, such as the image attached to a product, or its price.

Figure 9-18 illustrates the concept of products and product displays.

Product displays collect one or more products and expose their required fields as attributes for customers to select from

Figure 9-18. Product displays collect one or more products and expose their required fields as attributes for customers to select from

Now it’s time to create the storefront our users will view, from which they can add products to their shopping cart.

Hands-On: Product Displays

Let’s try putting what we just learned into action by creating a content type for product displays, and a few sample products to get the hang of how things work.

  1. Go to the Modules (admin/modules) page, enable the Cart module, and confirm the gaggle of dependent modules that it will prompt you to enable.

  2. First, we need to create a content type to hold our product displays. Go to Structure“Content types” and click “Add content type” (admin/structure/types/add).

  3. Give the new content type a Name of “Product display,” and a Description of “A publicly visible product on the website.” Click “Save and add fields.”

  4. Add a new field to the content type, using the settings in Table 9-8, and click Save.

    Table 9-8. Product reference field properties

    Field

    Value

    LabelProduct(s)
    Field name

    product

    Field typeProduct reference
    WidgetCheck boxes/radio buttons
  5. Click past the first settings page, then enter the settings in Table 9-9 and click “Save settings.”

    Table 9-9. Settings for the Product reference field

    Field

    Value

    Required fieldChecked
    Render fields from the referenced products when viewing this entity.

    Checked (default)

    Help textEnter one or more product SKUs.
    Product types that can be referenced(Leave unchecked for all)
    Default value(Leave blank)
    Number of valuesUnlimited
  6. Let’s test the new content type, starting with the Druplicon T-shirt. We’ll create a single product display for all variations of that product (S–XL, both Black and White).

  7. Go to “Add content”“Product display” (node/add/product-display), and fill in the settings in Table 9-10.

    Note

    As with the “Add product” form, you will probably be coming back here often. Feel free to hover over the plus sign (+) next to the title and click “Add to Default shortcuts” to add this page to your shortcut bar.

    Table 9-10. Settings for the T-shirt product display

    Field

    Value

    TitleDruplicon T-shirt
    DescriptionA T-shirt starring the charming Druplicon, mascot of the Drupal project.
    Product(s)(Check off all eight products starting with “TSHIRT-001.”)
  8. Click Save when finished, and as shown in Figure 9-19, you should not only see the product showing up with an “Add to cart” button, but also a selector to choose which product to buy. Switching between a white and black T-shirt should switch the image, and choosing between Small and Large should switch the price, as well.

  9. Repeat steps 7 and 8 for the other T-shirt SKUs as well. And for the sticker, you should only need to reference the single sticker product in its product display node.

A Drupal Commerce product display node

Figure 9-19. A Drupal Commerce product display node

Note

While this manual product assignment method is fairly tedious, there are other contributed modules that can help automate the task. Check out the http://drupal.org/project/commerce_product_display_manager module for an alternate way of assigning and creating product displays.

Hands-On: Creating a Product Catalog

Next, let’s create a nice interface for browsing products. We can categorize product displays using the Taxonomy system, and use the Views module for providing the browsing page:

  1. Go to the StructureTaxonomy (admin/structure/taxonomy) and click the “Add vocabulary” link (admin/structure/taxonomy/add).

  2. Give the vocabulary a name of “Catalog” and a description of “Sweet Tees product catalog.” Click the Save button.

  3. Now, let’s add a couple of product catalog categories. Click the “add terms” link (admin/structure/taxonomy/catalog/add).

  4. Add two terms, using the values in Tables 9-11 and 9-12. The terms’ descriptions will display at the top of the term listing pages at the specified URLs.

    Table 9-11. Settings for the T-shirt category

    Field

    Value

    NameT-shirts
    DescriptionHow Sweet Tees got its name! Check out our excellent selection of Drupal-themed T-shirts.
    URL aliascatalog/t-shirts

    Table 9-12. Settings for the Sticker category

    Field

    Value

    NameStickers
    DescriptionThe stickiest stickers that ever got stuck.
    URL aliascatalog/stickers
  5. Next, we need to add our product displays to the product catalog categories. Navigate to Structure“Content types” and click “managed fields” next to “Product display” (admin/structure/types/manage/product-display/fields).

  6. Add a new field with the settings in Table 9-13. All other settings can be left as their defaults.

    Table 9-13. Settings for the Catalog field for product displays

    Field

    Value

    LabelCatalog
    Field namecatalog
    Field typeTerm reference
    WidgetSelect list (default)
  7. Next, go back and edit each of the product displays from the Content menu (admin/content) to add them to their respective Catalog categories. When completed, if you go to http://example.com/catalog/t-shirts, you should see all three T-shirt product display nodes, with the term description at the top of the page, as pictured in Figure 9-20.

    Basic catalog taxonomy listing

    Figure 9-20. Basic catalog taxonomy listing

  8. Let’s see if we can clean up that display a little bit. For example, there are no images in this listing, nor is there a way to add the products to your shopping cart! Go to Structure“Content types” and click “manage display” next to the product display type (admin/structure/types/manage/product-display/display). Note that any fields here prefixed with “Product:” will inherit the settings of the parent product’s configuration, so configuring the display of teasers is actually a two-step process.

  9. First, let’s configure the display of the product display node fields. Click the Teaser subnavigation (admin/structure/types/manage/product-display/display/teaser) to change the settings for the product display node when it’s shown in teaser view, as it is in taxonomy listings.

  10. Drag the Catalog and Product(s) fields out of the Hidden section of the form, and place them as pictured in Figure 9-21. You’ll notice that when you do this, the Format column for each field will automatically change from “None” to “Add to cart form” in the case of Product(s), and to “Link” in the case of Catalog. Go ahead and leave these settings in place, but change the Label on Product(s) to <Hidden> so we don’t have a nonsensical Product(s) label next to the “Add to Cart” form. Click Save when finished.

    “Product display” content type’s Manage Display Settings

    Figure 9-21. “Product display” content type’s Manage Display Settings

  11. If you go back and look at the T-shirt listing, you’ll notice that it’s looking a little bit better already; the “Add to cart” button is there. Hooray! However, the product image is still missing. Because the product image is part of the “parent” product type, we need to change its display settings over in the Store settings instead.

  12. Navigate to StoreProducts“Product types” (admin/commerce/products/types), and click “manage display” next to the T-shirt product type (admin/commerce/products/types/t-shirt/display). Click on the “Node: Teaser” subnavigation, and drag the Image field just above Price.

  13. Click on the Image field’s configure (gear) icon, and change “Image style” to “medium,” and “Link image to” to “Content.” While we’re at it, change Label to Hidden since there’s no point in placing a label of “Image:” before an image. Click Update, then Save. Your screen should now look as pictured in Figure 9-22.

    T-shirt product type’s Manage Display Settings

    Figure 9-22. T-shirt product type’s Manage Display Settings

  14. Make similar adjustments to the Sticker product type’s display settings at StoreProducts“Product types” (admin/commerce/products/types/sticker/display/node_teaser). When finished, your product catalog listing pages should be looking much better! (See Figure 9-23.)

    Catalog category listing page

    Figure 9-23. Catalog category listing page

  15. Finally, let’s design a top-level catalog overview screen using the Views module. Go to StructureViews and click the “Add new view” link (admin/structure/views/add). Enter the settings listed in Table 9-14 and click the “Continue & edit” button.

    Table 9-14. Product catalog view settings

    Field

    Value

    View nameCatalog
    DescriptionChecked; “Sweet Tees product catalog.”
    ShowContent of type Product display sorted by Title
    Create a pageChecked
    Page titleCatalog
    Pathcatalog
    Display formatGrid of fields
    Items to display10 (default)
    Use a pagerChecked (default)
    Create a menu linkChecked
    MenuNavigation
    Include an RSS feedUnchecked (default)
    Create a blockUnchecked (default)
  16. At the moment, only product display titles are showing up in the preview. We want to also add Image and Price. But recall that those fields are both on the referenced product type, not the product display. So first, we must add a relationship to each product display node’s referenced products.

  17. Expand the Advanced fieldset, then click the “add” button in the Relationships section. Choose “Content: Referenced product” and click “Apply (all displays).” On the settings page, since all product displays have referenced products, choose “Require this relationship” and click “Apply (all displays)” once more.

  18. Uh oh! The Views preview is now showing multiples of the same product display nodes, as pictured in Figure 9-24. This is because each of the T-shirt product display nodes is actually referencing multiple unique products. We can fix this using a Views feature called aggregation, which allows you to group records together. Under the Advanced fieldset, then Other, click the No link next to “Use aggregation.” Check the Aggregate checkbox and click the “Apply (all displays)” button.

    Catalog view with duplicate titles in it after adding a relationship to the referenced product

    Figure 9-24. Catalog view with duplicate titles in it after adding a relationship to the referenced product

  19. The setting doesn’t appear to have done anything, but it will in a moment. Next, let’s add the fields that we want, now that the product relationship is in place. Click the “add” button in the Field area and check the following fields, then click the “Apply (all displays)” button.

    Table 9-15. Settings for the Catalog field for product displays

    Fields: Add Fields

    Value

    Content: PathChecked
    Field: ImageChecked
    Commerce Product: PriceChecked
    Content: CatalogChecked
  20. After you click the “Add and configure fields” button, Views will display configuration forms for each field, one by one. The first configuration screen will prompt for aggregation settings, then the standard field settings form. Enter each of the settings values from Table 9-16. When finished, your preview should look like Figure 9-25.

    New Views preview after adding fields and aggregation

    Figure 9-25. New Views preview after adding fields and aggregation

    Table 9-16. Individual field configuration for the catalog view

    Defaults: Configure field setting

    Value

    Commerce Product: Price

    Aggregation type: Group results together (default)

    Group column: Entity ID (default)

    Relationship: Product (default)

    Create a label: Unchecked

    Formatter: Formatted amount, Display the original price as loaded.

    Content: Catalog

    Aggregation type: Group results together (default)

    Group column: Entity ID

    Create a label: Unchecked

    Exclude from display: Checked

    Content: Path

    Aggregation type: Group results together (default)

    Create a label: Unchecked

    Exclude from display: Checked

    Field: Image

    Aggregation type: Group results together (default)

    Group column: Entity ID (default)

    Relationship: Product

    Create a label: Unchecked

    Image style: thumbnail

    Rewrite ResultsOutput this field as a link: Checked

    Rewrite ResultsLink path: [path]

  21. Finally, let’s make one last visual tweak. In the Format section, click Settings next to Format. Change the Grouping field “Nr.1 field” to “Content: Catalog.” This will visually group like products together. Make any other visual tweaks you’d like and then save your view; its configuration should now look as shown in Figure 9-26. And when you close out of the Overlay and return to your site, clicking on the Catalog navigation item should take you to your final, completed catalog as pictured in Figure 9-27.

Final views configuration for the product catalog

Figure 9-26. Final views configuration for the product catalog

Final product catalog

Figure 9-27. Final product catalog

Spotlight: Rules Module

It’s easy to imagine that different kinds of stores might have certain things they want to have happen when various events take place throughout the purchasing process. For example, if someone adds more than 10 of an item to his cart, a store might want to provide a 10% discount. Or if someone was anonymous and then registers or logs in, a store might want to assign his old shopping cart to his newly found account.

Traditionally, this kind of custom logic would have to be done in code by a programmer. However, the Rules module exposes a user interface for clicking together custom logic in a web-based interface. This increases accessibility to nonprogrammers, and also allows for bits of business logic to be shared among multiple sites with the Rules module’s import and export capabilities.

Because of the flexibility it provides, Drupal Commerce’s payment system relies on the Rules module, so it’s worth a quick diversion here before proceeding to setting up payments.

Rules module overview page

Figure 9-28. Rules module overview page

The following are the architectural blocks of Rules:

Events

Events are points in the system at which something occurs, has just occurred, or is about to occur. Examples are “A comment is viewed,” or “Before adding a product to the cart.” In Drupal developer-speak, events are “hooks” that fire during the processing of a page and allow other modules to react with their own customizations.

Actions

An action is custom programming logic for when an event fires and its associated condition(s) succeeds. Examples are “Add a product to the cart,” or “Send mail to all users of a role.” You can trigger multiple actions upon an event firing.

Conditions

A condition is an optional way to make a decision once an event is triggered—for example, checking to see if two field values match, or whether or not the current user has a particular role. Conditions can also be combined with either “and” or “or” logic. So you can create conditions to say, “User has role(s)” and “User is not blocked.”

Variables

Variables (also called parameters) are often passed into a condition or action to provide additional data required to complete it. For example, for a condition of “User has role(s),” the role or roles the user has would be variables passed to it.

Data selectors

Data selectors allow you to select the base system elements to pull parameters from, using Drupal’s token system syntax, as shown in Figure 9-29. For “User has role(s),” you need to be able to specify which user to check the roles of. For example, “node:author” would reference roles of the author of a node that was being posted or viewed, whereas “site:current-user” would reference the roles of the current user. Data selectors can chain as well; “comment:node:author” is the author of the node to which a comment is being posted. Whew!

Components

Components are collections of configuration that can be shared among different Rules. Drupal Commerce’s Tax module takes advantage of this capability and exposes tax rules as components.

The user interface for choosing Rules data selectors

Figure 9-29. The user interface for choosing Rules data selectors

Figure 9-30 shows a diagram of how the parts of the system work together. Not only does the Rules module expose events, conditions, and actions to play with, but Drupal Commerce and many other modules do as well. Two examples covered elsewhere in the book are the Flag module and the Workbench module.

The logic for processing rules

Figure 9-30. The logic for processing rules

Note

We won’t be able to cover every detail of the Rules module in this chapter, just the basics to finish up your store. However, NodeOne offers an incredibly helpful and detailed set of online videos covering the Rules module at http://dev.nodeone.se/en/learn-the-rules-framework. Also see the Rules documentation from Drupal.org at http://drupal.org/documentation/modules/rules.

Hands-On: Taxes

Let’s try a practical example of some Rules module concepts for the Sweet Tees store. Drupal Commerce’s Tax module stores its tax charging in Rules.

Before we can open up our store to the public, we need to ensure that all applicable sales taxes are being applied to our items. Because Sweet Tees is based in California, we will need to charge 7.25% sales tax on all products sold if the customer lives in the state of California.

Note

This example is for illustrative purposes only; you must determine what types of taxes you need to charge to sell products in your own store. The Tax and Tax UI modules, part of Drupal Commerce core, allow setting all sorts of complex tax rules to calculate different rates depending on whether purchasers are from the same state or a different state, for different product types, or for international orders.

  1. Enable the following modules at the Modules (admin/modules) page:

    • Commerce package

      • Tax

      • Tax UI

    • Rules package

      • Rules

      • Rules UI

  2. Visit ConfigurationRules (admin/config/workflow/rules) and you’ll see two additional rules, added by the Tax module: “Calculate taxes: Sales tax,” and “Calculate taxes: VAT.” Both rules trigger on the “Calculating the sell price of a product” system event.

  3. Go to StoreConfigurationTaxes (admin/commerce/config/taxes) and click the “Add a tax rate” link (admin/commerce/config/taxes/rates/add).

  4. Complete the form using the values from Table 9-17 and click the “Save tax rate” button to save the sales tax settings.

    Table 9-17. Tax form

    Field

    Value

    Name

    CA sales tax

    Display title(Leave blank)
    DescriptionCalifornia residents must pay 7.25% sales tax.

    Rate

    0.725

    Type

    Sales tax (default)

  5. Currently, a 7.25% sales tax will be added to all orders. To change this, we must add a condition to the rule to limit it only to California residents. Click the “configure component” link.

  6. Click the “Add condition” link under Conditions. Choose “Order address component comparison” under the Commerce Order group. The form will auto-expand to a configuration form.

  7. Fill out the values according to Table 9-18.

    Table 9-18. Sales tax rule configuration form

    Field

    Value

    Data selector

    commerce-line-item:order

    AddressAddress
    Address componentAdministrative Area (State / Province)
    Operatorequals (default)
    ValueCA
  8. When finished, click Save to save your changes. Your screen should look as pictured in Figure 9-31, and all orders coming from California will now receive a flat sales tax. We’ll confirm this in the next section.

Configured Rules component for CA sales tax

Figure 9-31. Configured Rules component for CA sales tax

Spotlight: Accepting Credit Card Payments Online

Of course, it’s one thing to have a bunch of products ready for purchase. But what Sweet Tees really cares about is raking in the dough. They want to be able to accept credit card transactions on their newfangled online store.

An online retailer must have a merchant account: a type of bank account provided by a financial institution that allows organizations to accept credit payments. A merchant account can be provided by a merchant bank or by a third party such as PayPal or Authorize.net that authorizes payments on behalf of banks. Fees vary between services, and should be evaluated based on anticipated transaction volume and average sale price.

While customers’ credit card details are entered into forms on the Drupal side, no sensitive information is ever stored by Drupal Commerce. Instead, it is passed on to the payment gateway for storage on their side.

Figure 9-32 outlines the process of Drupal handing off the request to the payment processor.

Drupal Commerce payment flow diagram

Figure 9-32. Drupal Commerce payment flow diagram

The spot where the customer’s credit card details are captured depends on the payment processor, and may require additional setup on your Drupal site. For example, PayPal offers a starter, no-setup fee tier of service, called Website Payments Standard, that will redirect the customer to PayPal.com upon checkout to enter her credit card details, then return her back to your site when the transaction is verified. In this case, no additional configuration is required.

However, many shop owners would rather have a fully integrated shopping experience, and want to gather the credit card details on their own site. PayPal’s Website Payments Pro offers this capability, but using it requires secure socket layer (SSL) encryption between your site and PayPal. Luckily, the Secure Pages module (http://drupal.org/project/securepages) provides this capability.

Hands-On: PayPal

PayPal is a popular payment processor, especially for new site owners. It allows credit card transactions as well as payments from within PayPal itself, which is common particularly within the eBay ecosystem. There are predominantly two “flavors” of PayPal’s payment processing tools:

Website Payments Standard (WPS)

PayPal’s entry-level tier. It enables sites to process credit card transactions securely by redirecting customers to PayPal’s website at checkout time in order to enter credit card details.

Website Payments Pro (WPP)

For a monthly fee, credit card payments can happen on your own site, seamlessly. PayPal handles the credit card processing behind the scenes, provided your site meets security standards.

For our purposes, we’ll be using Website Payments Standard, since there are no setup fees, no extra security setup required, and we can get started right away. Note that the setup steps for other payment processors vary depending on the provider; PayPal WPS is used in this chapter for illustrative purposes.

Note

PayPal’s developer network at https://www.x.com/developers/paypal runs on Drupal, too! Nifty.

  1. Go to https://developer.paypal.com/ and sign up for a development sandbox. The sandbox will act as a “safe space” to test financial transactions from Drupal Commerce.

  2. After confirming your email address, log into the sandbox, which will look similar to Figure 9-33.

    PayPal’s development sandbox

    Figure 9-33. PayPal’s development sandbox

  3. Click “preconfigured account” under Test Accounts.

  4. Fill out the values in Table 9-19 and click Create Account to create a fake “buyer” account with whom we’ll test.

    Table 9-19. Settings for the PayPal test buyer account

    Field

    Value

    Country(Your country)
    Account TypeBuyer
    First / Last nameTest Buyer
    Login Email(Your email)
    Password(Change to something memorable)
    Add Credit CardVisa (default)
    Add Bank AccountYes (default)
    Account Balance9999
  5. Create another “preconfigured” account, repeating the values from Table 9-19, but this time for the seller. Enter “Sweet Tees” as the account’s first and last name. When finished, your screen should look similar to Figure 9-34.

    PayPal’s development sandbox

    Figure 9-34. PayPal’s development sandbox

    Note

    PayPal will automatically generate nonworking email addresses based on your real email address. Don’t panic! These email addresses are not real; they’re simply used for testing.

  6. Copy and paste the autogenerated “Business (seller)” email address into a text file for safekeeping. You will need it in a few minutes to configure PayPal on the Drupal Commerce side.

  7. Let’s take a look around the sandbox. Select the radio button next to the Personal account and click the Enter Sandbox Test Site button.

  8. At the login screen, enter the buyer account password you created a few minutes ago (not your actual sandbox account’s password!) and click “Log in.” This allows you to masquerade as a buyer and see what happens through his eyes. Once logged in, you should see something like Figure 9-35, which shows the current balance of the account. Keep this window open, as we’ll want to refer to it while we’re testing transactions later.

Dashboard for PayPal test account

Figure 9-35. Dashboard for PayPal test account

Hands-On: Configuring a Payment Method

Now that we have the PayPal side of payments set up, it’s time to set up the Drupal side of things. We’ll do this with the Commerce PayPal module from http://drupal.org/project/commerce_paypal, and Drupal Commerce’s Order and Payment (UI) modules. Just as we saw with Taxes, Ubercart payment methods are Rules-enabled for maximum flexibility.

  1. Enable the following modules:

    • Commerce package

      • Order

      • Order UI

      • Payment

      • Payment UI

    • Commerce (PayPal) package

      • PayPal

      • PayPal WPS

  2. Navigate to StoreConfiguration“Payment methods” (admin/commerce/config/payment-methods).

  3. First, you must enable the PayPal WPS payment method. Click its “enable” link under the Operations column and confirm.

  4. Click “edit” in the Operations column. Oh, look. Another rule. This one only defines an event (“Select available payment methods for an order”) and an action (“Enable payment method: PayPal WPS”). We want to change the action so that we can point it to the PayPal sandbox. Click “edit” in the actions Operations column.

  5. In the PayPal email address field, fill in the autogenerated seller email from the previous section, and make sure the PayPal server value is set to “Sandbox.” Once you’re finished testing, you’ll want to come back and switch these settings to your real PayPal email address and “Live,” respectively. The form is shown in Figure 9-36.

  6. Click Save to submit the form and return to the PayPal WPS rule overview page.

Configuring PayPal WPS payment settings

Figure 9-36. Configuring PayPal WPS payment settings

Warning

Your Drupal site must be accessible from the Internet in order for PayPal transactions to complete properly. Either upload your practice files to a public domain, or use a service such as https://www.no-ip.com/ to expose your local development environment to PayPal.

Hands-On: Processing Orders

The remaining element of our site is actually implementing the ecommerce portions: an online shopping cart and the ability to process orders, as well as reporting tools to tell us how our store is doing. We will now complete our store configuration.

To complete this section, we must first enable one final set of modules. Go to Modules (admin/modules) and enable the remaining UI modules in the Commerce package:

  • Commerce package

    • Customer UI

    • Line Item UI

    • Order UI

Shopping Cart

Thanks to the Cart module that we enabled earlier, everything we need for a shopping cart is pretty much done. Let’s make some final tweaks:

  1. Drupal Commerce ships with an optional block that can display a visitor’s shopping cart on all pages. Go to StructureBlocks (admin/structure/block), drag the Shopping Cart block to the top of the “Sidebar first” region, and click “Save blocks.”

  2. Test it out by navigating to a product page and clicking the “Add to cart” button. You should see the product and total show up instantly in the left sidebar.

  3. Click the “View cart” button to see the full shopping cart. It’s looking a little bland. Luckily, the shopping cart (as well as the shopping cart block) is a view, which means we can make tweaks to it.

  4. Let’s add a product thumbnail image field as well. Hover over the larger shopping cart view, click the gear icon, and click “Edit view.”

  5. The view is currently showing order information. To add product information, we need to add a relationship to it. In the Relationships section, click “add,” and select “Commerce Line item: Referenced product.” Accept the default settings.

  6. Click the “add” button in the Fields section and check “Field: Image.” Uncheck “Create a label” and choose an image style of “thumbnail.” Click Apply to save changes.

  7. Finally, reorder the image field so it comes first in the list. In the Fields section, click the drop-down next to “add” and choose “rearrange.” Use the drag-and-drop handles to move “(Product) Field: Image” to the top of the list, then click Apply.

When finished, save and close the view and return to the shopping cart page, which should now be visible in all its glory, as pictured in Figure 9-37.

Drupal Commerce shopping cart, along with a sidebar block

Figure 9-37. Drupal Commerce shopping cart, along with a sidebar block

We now have our shopping cart ready to go. That was easy! Next, we’ll talk about what happens when someone clicks the Checkout button.

Checkout Process

Drupal Commerce provides the ability to fully customize the checkout workflow to your store’s specific needs. By default, the checkout process contains four distinct steps: “Checkout,” “Review order,” “Payment,” and “Checkout complete.” A variety of page elements called panes are provided and can be placed in any step in any order, and you can control certain cosmetic aspects of panes such as whether they appear in a fieldset.

  1. Go to StoreConfiguration“Checkout settings” (admin/commerce/config/checkout) to view the current checkout configuration settings.

  2. Because PayPal WPS forces a redirect to a third-party website when gathering payment details, it behooves us to make the checkout process as simple as possible. We can omit the “Review order” step of the process altogether by removing all of the panes within it. Drag the Payment pane to the bottom of the Checkout section, and the Review pane to the Disabled section.

  3. When you’re finished, your checkout settings should be as pictured in Figure 9-38. We’ll see this change in action in the next section.

The newly customized checkout workflow

Figure 9-38. The newly customized checkout workflow

Placing a Test Order

We are now ready to make our first test order! Here’s how:

  1. Click Checkout from either the left sidebar block or the shopping cart page.

  2. We are now on the checkout screen, pictured in Figure 9-39. By default, this page displays the contents of our shopping cart for confirmation, followed by account information, and fields to enter a billing address. Because we customized it to do this, it also contains the payment selector. Complete the billing information section with your information. Click “Continue to next step” when finished.

    The order summary and delivery details of the checkout screen

    Figure 9-39. The order summary and delivery details of the checkout screen

    Note

    If you wish to whittle down the exhaustive default country list to something more appropriate for your customer base, you can do so from Store“Customer profiles”“Profile types” (admin/commerce/customer-profiles/types). Click “manage fields,” then edit the Address field and change the “Available countries” selection.

  3. The next screen will inform you that you are being redirected to PayPal’s site. Wait for a few seconds, and you should see a screen similar to Figure 9-40. To test credit card transactions, choose the “Don’t have a PayPal account?” option. You’ll be prompted to enter your billing information and credit card details.

    PayPal’s billing information screen

    Figure 9-40. PayPal’s billing information screen

  4. Before proceeding, return to your browser tab with the PayPal developer sandbox we set up earlier (or log in again). Under “Test accounts,” click “View details” on the Personal account. Copy and paste the credit card number and expiration date there into the payment form. For CSC, fill in any 3-digit number.

  5. Complete the rest of the form and then submit it. Because you’re using a credit card number that PayPal knows about, you will be prompted to log in with your PayPal account. Choose the option to “Continue to pay as a guest and do not use my PayPal account.”

  6. If all goes well, you should see a PayPal confirmation page for your order. Click Pay Now. You’ll be taken to a final screen showing a confirmation message, as pictured in Figure 9-41. Click “Return to Sweet Tees’s Test Store” to go back to your Drupal site.

    PayPal’s order confirmation screen

    Figure 9-41. PayPal’s order confirmation screen

  7. Back on the Sweet Tees website, you’ll be presented with a short thank-you page, with a link to view the current order status from the Orders section of your user profile, shown in Figure 9-42. Click the “view your order” link, and you should see a screen similar to Figure 9-43.

    Note

    You can customize the text on this page in the checkout configuration at StoreConfiguration“Checkout settings” (admin/commerce/config/checkout). Click the “configure” link next to “Completion message,” and check the “Override the default checkout completion message” checkbox.

The final checkout confirmation form

Figure 9-42. The final checkout confirmation form

The completed order, as seen by the customer

Figure 9-43. The completed order, as seen by the customer

Access Control

Finally, let’s configure the permissions for the new modules that we enabled in this chapter. Go to PeoplePermissions (admin/people/permissions), set them as indicated in Table 9-20, and click “Save permissions.”

Table 9-20. Permissions for Drupal Commerce modules

Permission

anonymous user

authenticated user

editor

site administrator

Checkout

Administer checkout   

Checked

Access checkoutCheckedCheckedCheckedChecked

Commerce

Configure store settings   

Checked

Customer

Administer customer profile types   

Checked

Administer customer profiles  Checked

Checked

Create customer profiles of any type  Checked

Checked

Edit own customer profiles of any type  Checked

Checked

Edit any customer profile of any type  Checked

Checked

View own customer profiles of any type  Checked

Checked

View any customer profile of any type  CheckedChecked
Create Billing information customer profiles   Checked
Edit own Billing information customer profiles   Checked
Edit any Billing information customer profile   Checked
View own Billing information customer profiles   Checked
View any Billing information customer profile   Checked

Line item

Administer line item types

   

Checked

Administer line items  Checked

Checked

Order

Administer orders  Checked

Checked

Create orders of any type  CheckedChecked
Edit own orders of any type  CheckedChecked
Edit any order of any type  CheckedChecked
View own orders of any typeCheckedCheckedCheckedChecked
View any order of any type  CheckedChecked
Create Order orders   Checked
Edit own Order orders   Checked
Edit any Order order   Checked
View own Order orders   Checked
View any Order order   Checked

Payment

Administer payment methods   

Checked

Administer payments  CheckedChecked
View payments  CheckedChecked
Create payments  CheckedChecked
Update payments  CheckedChecked
Delete payments  CheckedChecked

Product

Administer product types   

Checked

Administer products   Checked
Create products of any type  CheckedChecked
Edit own products of any type  CheckedChecked
Edit any product of any type  CheckedChecked
View own products of any type  CheckedChecked
View any product of any type  CheckedChecked
Create Product Type products  CheckedChecked
Edit own Product Type products  CheckedChecked
Edit any Product Type product  CheckedChecked
View own Product Type products  CheckedChecked
View any Product Type product   Checked

Product Pricing UI

Administer product pricing  Checked

Checked

Rules

Administer rule configurations   

Checked

Bypass Rules access control   Checked
Access the Rules debug log   Checked
Tax UI
Administer taxes  CheckedChecked

Taking It Further

In this chapter, we have covered the basics of setting up an online storefront and shopping cart using the Drupal Commerce package for Drupal. However, there are several additional modules that you will likely want to consider before taking your online store live:

Secure Pages (http://drupal.org/project/securepages)

When collecting sensitive, personal information online—particularly credit card information—it is highly recommended that you do it via an SSL connection. The Secure Pages module allows you to specify certain Drupal paths that should be visited only via HTTPS. The recommended paths to protect are user/* and cart/*.

Commerce Shipping (http://drupal.org/project/commerce_shipping)

Since Sweet Tees is in the business of shipping physical goods, it probably makes sense to charge shipping for them. The Commerce Shipping module provides a framework for shipping calculation, and there are modules available for “Flat rate shipping,” and “US Postal Service,” among others.

Commerce Stock (http://drupal.org/project/commerce_stock)

Particularly when you are selling something like T-shirts, it is a good idea to keep track of the current available stock level to avoid selling someone a product that is not available. The Commerce Stock module maintains stock levels for each product, and validates each time a purchase is made to ensure that products are never oversold.

Summary

In this chapter, we were able to set up a complete online store for our customer, Sweet Tees, using Drupal Commerce, a powerful, flexible ecommerce framework built on Drupal. We set up a payment system through PayPal’s Website Payments Standard. We also delved into the topic of data imports with the Feeds module, and covered tweaking Drupal’s functionality at various system points with the Rules module.

Here are the modules we referenced in this chapter:

Here are the additional resources that we referenced in this chapter:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset