| name | checkout-flow |
| description | Implement e-commerce checkout flow. Use when: building cart, shipping, payment, order confirmation steps; adding promo codes; validating checkout forms; handling payment errors; integrating payment gateways (Stripe, PayPal); managing checkout state; securing PII and payment data. |
| argument-hint | Describe what part of checkout to implement (e.g., cart page, payment step, order confirmation) |
電商結帳流程 (E-Commerce Checkout Flow)
何時使用 (When to Use)
- 實作購物車、結帳、付款、訂單確認等功能
- 新增折扣碼 / 優惠券欄位
- 串接金流(Stripe、PayPal、綠界、藍新等)
- 處理表單驗證與錯誤回饋
- 保護個人資料與信用卡資訊(PCI DSS)
- 管理結帳流程狀態(多步驟 wizard)
結帳流程步驟 (Checkout Steps)
標準結帳流程共五步,依序實作:
購物車確認 → 填寫資料 → 選擇配送 → 付款 → 訂單確認
(Cart) (Info) (Shipping) (Payment) (Confirm)
Step 1 — 購物車確認 (Cart Review)
目標:讓用戶確認品項、數量、價格,並可修改。
實作清單
安全注意
- 不在前端信任價格計算,所有合計由後端確認
- 折扣碼在伺服器端驗證後才套用
Step 2 — 填寫顧客資料 (Customer Information)
目標:收集姓名、Email、電話、送貨地址。
欄位
| 欄位 | 驗證規則 |
|---|
| 姓名 | 必填,2–50 字元 |
| Email | 必填,合法 email 格式 |
| 電話 | 必填,依國碼格式驗證 |
| 地址(收件人、縣市、區、路、號) | 必填 |
| 郵遞區號 | 必填,依地區格式驗證 |
實作清單
Step 3 — 選擇配送方式 (Shipping Method)
目標:讓用戶選擇運送方式,計算並顯示運費。
實作清單
Step 4 — 付款 (Payment)
目標:安全收集付款資訊並送出。
金流串接原則
絕不在自己伺服器收集或儲存原始卡號。使用金流 SDK 在前端 tokenize。
Stripe 範例流程
1. 頁面載入 → 初始化 Stripe Elements / Payment Element
2. 用戶填寫卡號(在 Stripe iframe 內,不碰 DOM)
3. 點擊「確認付款」→ 呼叫 stripe.confirmPayment()
4. 前端取得 paymentMethod token → 送至自家後端
5. 後端呼叫 Stripe API 建立 PaymentIntent → 扣款
6. 後端回傳成功/失敗 → 前端導向對應頁面
實作清單
Step 5 — 訂單確認 (Order Confirmation)
目標:告知用戶訂單已成立,提供後續追蹤資訊。
實作清單
狀態管理建議 (State Management)
checkoutState {
step: 1 | 2 | 3 | 4 | 5
cart: CartItem[]
discountCode: string | null
discountAmount: number
customer: CustomerInfo | null
shippingMethod: ShippingOption | null
paymentToken: string | null // 來自金流 SDK,非原始卡號
orderId: string | null
}
- 步驟間保留已填資料(用戶返回上一步不需重填)
- 刷新頁面時從 sessionStorage 或後端 session 還原
- 訂單建立成功後清除 state
錯誤處理模式 (Error Handling)
| 情境 | 處理方式 |
|---|
| 表單驗證失敗 | 欄位旁顯示紅色提示,聚焦到第一個錯誤欄位 |
| 庫存不足(送出時) | 顯示哪些品項缺貨,引導用戶更新購物車 |
| 付款被拒 | 顯示金流回傳的具體原因,允許重試 |
| 網路逾時 | 顯示重試按鈕,避免重複建立訂單(冪等性) |
| 訂單建立失敗 | 保留輸入資料,提供客服聯繫方式 |
安全性檢查清單 (Security Checklist)
參考資源 (References)