Cross-Platform E-Commerce Plugin Patterns
Overview
E-commerce plugins share a common set of concerns regardless of the target platform. Payment processing, shipping integration, product data modeling, checkout customization, security compliance, and testing strategies follow consistent architectural patterns whether the plugin targets WooCommerce, Shopify, Magento, PrestaShop, or any other platform. This skill provides the foundational patterns that apply universally, enabling faster development and more robust implementations by reusing proven approaches.
Apply these patterns before diving into platform-specific APIs. Each section below describes the core concept and links to detailed reference files for implementation guidance.
Payment Gateway Integration
Payment processing is the most critical and most regulated area of e-commerce plugin development. Every payment gateway plugin must implement four core lifecycle operations:
- Authorize -- Place a hold on funds without capturing them. Store the authorization token for later capture or void.
- Capture -- Collect previously authorized funds. Support partial captures when the gateway allows it.
- Refund -- Return captured funds to the customer. Support partial and full refunds with reason codes.
- Void -- Cancel an authorization before capture. Must be idempotent to handle network retries safely.
Tokenization
Never store raw card numbers in the plugin. Use gateway-provided tokenization (Stripe tokens, Braintree nonces, Adyen encrypted data) to replace sensitive card data with a non-sensitive reference token. The token is stored in the platform database; the raw card data never touches the plugin server.
Webhook Verification
Payment providers send webhook notifications for asynchronous events (charge succeeded, refund completed, dispute opened). Always verify webhook signatures using HMAC-SHA256 or the provider-specific mechanism before processing the payload. Never trust unverified webhook data.
3D Secure and SCA
Strong Customer Authentication (SCA) under PSD2 requires 3D Secure for European transactions. Implement the redirect or inline authentication flow, handle the callback, and complete the payment only after successful authentication.
For complete patterns including error codes, retry logic, and PCI scope considerations, see references/payment-gateway-patterns.md.
Shipping Integration
Shipping plugins connect the e-commerce platform to carrier APIs (UPS, FedEx, DHL, USPS, national postal services). The three core functions are:
- Rate Calculation -- Accept origin, destination, package dimensions, and weight; return available shipping methods with prices. Cache rates for a configurable TTL to reduce API calls.
- Label Generation -- Create shipping labels after order placement. Store the label URL/PDF and tracking number on the order.
- Tracking -- Poll or receive webhooks for tracking updates. Map carrier-specific statuses to a normalized set (in transit, out for delivery, delivered, exception).
Dimensional Weight
Carriers charge by the greater of actual weight and dimensional weight (L x W x H / divisor). Always calculate dimensional weight and compare it to actual weight before returning rates.
Multi-Package Shipments
Support splitting an order across multiple packages. Each package generates its own label and tracking number. The order-level tracking must aggregate statuses from all packages.
For carrier API patterns, tracking webhook integration, and rate caching strategies, see references/shipping-integration.md.
Product Data Models
E-commerce platforms model products differently, but all share core concepts that plugins must handle:
Variants and Options
A product may have multiple variants (size/color combinations). Each variant has its own SKU, price, inventory count, and optionally its own images. Plugins that import, export, or transform product data must map between the platform's variant model and the plugin's internal representation.
Inventory Management
Track inventory at the variant level. Support inventory reservations during checkout (decrement on order placement, restore on cancellation). Handle concurrent inventory updates with optimistic locking or atomic decrement operations to prevent overselling.
Pricing Models
Support multiple pricing structures:
- Simple pricing -- One price per variant.
- Tiered pricing -- Different unit prices based on quantity (buy 10+ at $8 each, 100+ at $6 each).
- Wholesale/customer-group pricing -- Different prices for logged-in wholesale customers.
- Subscription pricing -- Recurring charges with billing intervals.
- Sale/promotional pricing -- Time-limited price overrides.
Digital Products
Digital products require download URL management, access control (expiry, download count limits), and license key generation. Avoid serving files directly from the application server; use signed URLs from cloud storage (S3 presigned URLs, GCS signed URLs).
For complete data model patterns including normalization strategies, see references/product-data-models.md.
Cart and Checkout Extension
Many plugins extend the cart or checkout flow. Common extension points include:
Custom Fields
Add fields to the checkout form (gift message, VAT number, delivery instructions). Validate custom fields server-side before order submission. Store field values as order metadata.
Fee Calculation
Add fees or discounts during cart calculation (handling fee, insurance, loyalty discount). Register the fee with the platform's cart calculation pipeline so taxes and totals recalculate correctly.
Validation Rules
Enforce business rules before checkout completion (minimum order amount, restricted products by region, age verification). Return clear error messages that the frontend can display to the customer.
Order Status Extensions
Add custom order statuses for platform workflows (awaiting verification, in production, ready for pickup). Register status transitions and trigger notifications when statuses change.
Security Patterns
E-commerce plugins handle financial data and personal information, making security a non-negotiable concern.
PCI-DSS Basics for Plugin Developers
Most plugins should aim for SAQ-A compliance by using hosted payment fields (Stripe Elements, Braintree Drop-in, PayPal hosted buttons). This means card data never touches the plugin server. If the plugin must handle card data directly, SAQ-D applies, which requires a full PCI audit.
CSRF Protection
All state-changing endpoints (place order, update cart, process refund) must include and validate CSRF tokens. Use the platform's built-in CSRF mechanism when available.
Input Validation for Financial Data
Validate currency amounts as integers (cents, not dollars) to avoid floating-point errors. Reject negative amounts. Validate currency codes against ISO 4217. Sanitize all user-provided strings to prevent XSS and SQL injection.
Data Encryption
Encrypt sensitive data at rest (API keys, tokens, customer PII stored beyond platform defaults). Use AES-256-GCM or the platform's built-in encryption service. Never log sensitive data.
For comprehensive security requirements and platform-specific implementation details, see references/security-and-pci.md.
Testing Strategies
E-commerce plugins require thorough testing because failures directly impact revenue and customer trust.
Unit Testing Payment Flows
Mock the payment gateway API to test authorize, capture, refund, and void operations. Test both success paths and every error code the gateway returns. Verify that webhook signature verification rejects tampered payloads.
Integration Testing with Sandboxes
Use sandbox/test environments provided by payment gateways and shipping carriers. Test the full order lifecycle: add to cart, checkout, payment, fulfillment, refund. Verify idempotency by replaying the same request.
Order Lifecycle Testing
Test the complete order state machine: pending -> processing -> shipped -> delivered, with branches for cancellation, refund, and partial fulfillment. Verify that inventory, customer notifications, and accounting entries update correctly at each transition.
Load Testing Checkout
Simulate concurrent checkout sessions to identify race conditions in inventory management, coupon usage limits, and payment processing. Use tools like k6, Artillery, or Locust.
For detailed testing patterns, sandbox configuration, and mocking strategies, see references/testing-strategies.md.
Multi-Currency and Internationalization
E-commerce plugins operating across borders must handle multiple currencies and locales.
Currency Handling
- Store amounts as integers in the smallest currency unit (cents for USD, yen for JPY).
- Use ISO 4217 currency codes (USD, EUR, GBP).
- Fetch exchange rates from a reliable provider (Open Exchange Rates, European Central Bank, Fixer.io) and cache them with a TTL.
- Apply exchange rates at the time of checkout, not at display time.
- Store the original currency and converted amount on the order for reconciliation.
Zero-Decimal Currencies
Some currencies (JPY, KRW, VND) have no decimal places. The plugin must detect zero-decimal currencies and skip the cents conversion.
Tax Localization
Tax rules vary by country (VAT in EU, GST in Australia, sales tax in US by state/county). Use a tax calculation service (TaxJar, Avalara, built-in platform tax engine) rather than hardcoding tax rates. Display prices tax-inclusive or tax-exclusive based on the customer's locale.
Translation and RTL
If the plugin includes a customer-facing UI, support translation via the platform's i18n system. Test with RTL languages (Arabic, Hebrew) and verify layout integrity.
Webhook Patterns
Webhooks are the backbone of asynchronous communication between e-commerce platforms, payment providers, shipping carriers, and third-party services.
Verification and Security
Always verify incoming webhooks using HMAC signatures, API keys, or IP whitelisting. Return HTTP 200 immediately to acknowledge receipt, then process the payload asynchronously.
Idempotency
Webhook providers may deliver the same event multiple times. Track processed event IDs and skip duplicates. Design handlers to be idempotent -- processing the same event twice must produce the same result.
Retry Handling
If the webhook endpoint returns a non-2xx response, the provider will retry with exponential backoff. Implement dead letter queues for events that fail after all retries.
For webhook verification patterns, event ordering strategies, and dead letter queue design, see references/webhook-patterns.md.
Reference Files
- Payment Gateway Patterns -- Lifecycle operations, webhook handling, error codes, retry logic, 3D Secure, tokenization, PCI scope
- Shipping Integration -- Carrier API patterns, rate calculation, label generation, tracking webhooks, dimensional weight
- Product Data Models -- Variant/option patterns, inventory management, pricing tiers, digital products
- Security and PCI -- PCI-DSS requirements, credential storage, CSRF, XSS prevention, SQL injection prevention, data encryption
- Testing Strategies -- Unit testing payments, integration testing with sandboxes, mocking APIs, order lifecycle testing, load testing
- Webhook Patterns -- Webhook verification, idempotency, retry handling, event ordering, dead letter queues