Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 40 ยท Practice and Review

E-commerce Cheat Sheet

A one-page e-commerce cheat sheet: money rules, order states, payment flow, webhook and security checklists, a launch checklist and links to every lesson.

This is the page to keep open while you build or review a shop. It does not teach anything new: every line is a rule from an earlier lesson, shortened until it fits in your head. Use it as a design review checklist, and follow the links when a rule needs the full explanation.

The sheet is organized in the order a request travels: money, catalog, stock, pricing, cart, order, payment, shipping, then the cross-cutting concerns (webhooks, security, growth) and a launch checklist. Two runnable snippets sit in the middle, a money toolkit you can copy and a launch checklist scorer you can adapt.

Money rules

Rule Why
Store amounts as integers in minor units, plus a currency code Floats cannot hold decimal fractions exactly
The currency decides the exponent (JPY 0, USD 2, KWD 3) Never hard-code / 100
Never add amounts of different currencies Convert explicitly with a stored rate
Round only at named points, always with the same rule (half up is the common choice) Cart, email, invoice and export must agree
Allocate with floor plus largest remainders The parts must add up to the whole
Tax-inclusive: round net, tax = gross - net Net plus tax equals what was paid
Snapshot prices, tax and addresses on the order History must not change when the catalog does
The client sends intent (SKU, quantity, code), never amounts Everything from the browser can be edited

More in Representing Money Correctly, Pricing Models and Currencies and Localization.

JS A money toolkit you can copy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Catalog, stock and pricing

  • Product vs variant vs SKU: the product is the thing people read about, the variant is what they buy (size, color), the SKU identifies a sellable unit and its stock. Price, image and stock belong to the variant. See Product Catalogs and Data Modeling and Variants and Options.
  • Stock is a ledger, not a number: on hand, committed, incoming and available are derived from movements. available = on hand - active holds.
  • Take stock atomically: UPDATE ... SET qty = qty - n WHERE sku = ? AND qty >= n, then check the row count. Never SELECT then UPDATE.
  • Holds expire: reserve when checkout starts, release on timeout, payment failure or cancel. See Inventory Tracking and Reservations and Overselling.
  • Promotions are data: conditions, actions, priority, exclusivity, usage limits; allocate each discount across lines and log which rule produced it. See Building a Promotions Engine.
  • Tax: decide inclusive or exclusive per market, choose line or invoice rounding once, store the rate that applied. Not legal advice; use a tax service for anything beyond one jurisdiction. See Sales Tax, VAT and GST.

Cart and order rules

Topic Rule
Cart Store SKU and quantity; price on every read; validate stock on every change
Guest to user Merge quantities, cap by stock and limits, delete the guest cart, tell the customer
Checkout Re-validate everything, then change state; convert the cart once
Order Immutable snapshot; changes are events (payment, shipment, refund, note)
Statuses Separate payment status from fulfillment status; legal moves in a table
History Record every transition with a time, an actor and a reason
stateDiagram-v2
  [*] --> pending_payment
  pending_payment --> paid: payment confirmed
  pending_payment --> cancelled: cancel or hold expired
  paid --> fulfilled: shipped
  paid --> refunded: full refund
  fulfilled --> refunded: return accepted
  cancelled --> [*]
  refunded --> [*]

One legal set of order transitions; everything not drawn is rejected.

See Designing the Cart, Checkout Flow and Conversion and The Order Lifecycle and State Machines.

Payment flow

sequenceDiagram
  participant C as Customer
  participant S as Shop
  participant P as Payment provider
  C->>S: Pay (Idempotency-Key)
  S->>P: Create payment (token, amount, key)
  P-->>S: Authorized or requires action
  S-->>C: Confirmation page (pending)
  P->>S: Webhook: payment succeeded (signed)
  S->>S: Verify, de-duplicate, mark order paid

The webhook, not the redirect, marks the order paid.

  • Authorize, then capture when you ship later; void an authorization you will not use; refund the original method, partially if needed.
  • Never touch card numbers: hosted fields or redirect, keep only the token and last four digits (PCI scope). Plan for 3-D Secure/SCA in Europe.
  • Idempotency key per intent: store the result, return it for repeats, refuse a reused key with a different body, record in-flight work before awaiting it.
  • A decline is a stored result too: a new card attempt gets a new key.
  • Disputes: keep the order snapshot, delivery proof and communication ready; watch the chargeback ratio.

See How Online Payments Work, Authorization, Capture, Refunds and Chargebacks, PCI DSS Scope and 3-D Secure and Idempotency and Reliable Payments.

Webhook checklist

  1. Read the raw body before any JSON parsing.
  2. Verify the HMAC signature with a constant-time comparison; accept several signatures during secret rotation.
  3. Check the timestamp is within a tolerance (for example five minutes) to stop replays.
  4. Deduplicate by event id; handlers must be safe to run twice.
  5. Accept out-of-order events: compare the event's state with the current state, and ignore events that would move an order backwards.
  6. Acknowledge quickly with a 2xx, then do slow work in a queue; return 4xx for invalid signatures, 5xx only when you want a retry.
  7. Log the event id and outcome; alert on a stream of failures.
  8. Keep a reconciliation job that compares your orders with the provider's records.

See Webhooks and Signature Verification.

Security checklist

  • Prices, totals, discounts and tax are computed on the server only.
  • Every order, address and download id is checked against the logged-in owner (no IDOR).
  • Rate-limit login, coupon, checkout and card-attempt endpoints (card testing is common).
  • Use CSRF protection and output escaping on every form; sessions rotate on login.
  • Admin: separate login, strong authentication, least privilege, audit log.
  • Secrets live in environment configuration, never in the repository; rotate API keys and webhook secrets.
  • Keep dependencies and platform plugins patched; remove unused ones.

See Securing an Online Shop, Fraud and Risk Management and GDPR, Consumer Law and Accessibility.

Shipping, search and growth in one glance

Area Remember
Shipping Flat, table or carrier rates; free-shipping threshold after discounts; split shipments need per-parcel tracking
Returns An RMA has its own states; decide restock, refund, exchange or credit
Search Index products, fix typos, facet counts must match the filters, handle zero results
SEO One canonical URL per product, JSON-LD Product and Offer, sitemaps, sensible out-of-stock pages
Analytics Define the funnel, measure conversion rate and average order value, respect consent
Email Order confirmation, shipping notice, receipt; SPF, DKIM and DMARC for deliverability
Scale Cache product pages, queue slow work, offload search, degrade non-essentials first

Lessons: Shipping Methods and Rates, Fulfillment, Returns and Refunds, Product Search, Filters and Facets, SEO for Online Shops, Analytics, Funnels and Metrics, Transactional Email and Customer Lifecycle and Architecture, Scaling and Peak Traffic.

Launch checklist

Before the first real order, walk through this list. The snippet scores a shop configuration against it so you can adapt the list to your own team.

JS A launch checklist scorer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Add your own items for your market: tax registration, carrier contracts, customer support hours, a rollback plan and a load test of the checkout path with the expected peak plus a safety margin.

One-page summary

  • Money: integers, currency codes, explicit rounding, allocation by largest remainder.
  • Truth: the server prices; the order is a snapshot; the webhook confirms payment.
  • Stock: derived from a ledger and holds; taken atomically.
  • Reliability: idempotency keys, deduplicated events, a state machine for every long-lived record.
  • Trust: verify signatures, check ownership, rate-limit, keep card data out.
  • Operations: cache the read path, queue the slow path, watch the money path.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which rule keeps net and tax adding up for a tax-inclusive price?

    Deriving one part from the other guarantees that net plus tax equals what the customer paid, whatever the rounding.
  2. 2. What marks an order as paid in a robust payment flow?

    The browser can fail to return, and some methods complete later. The signed server-to-server event is the reliable signal.
  3. 3. Which webhook step prevents an attacker from replaying an old, valid request?

    A captured request is valid forever unless the signature covers a timestamp and the receiver rejects old ones.
  4. 4. Stock needs to be taken for an order. Which pattern is correct?

    One atomic statement both checks and takes, so two buyers cannot both succeed on the last unit.
  5. 5. Why separate payment status from fulfillment status on an order?

    Money and goods move independently. Separate states keep each state machine small and make impossible combinations easier to spot.

Summary

  • Keep this page as a review checklist: money, stock, orders, payments, webhooks, security and launch.
  • Every rule exists because of a real failure: lost cents, oversold stock, double charges, forged events and tampered prices.
  • Use the linked lessons for the reasoning behind a rule, and the projects to see the rules working together.
  • Adapt the launch checklist to your market and platform, and re-run it before every major sale.

Back to the start of the course: How Online Shops Work