Files
WooNooW/SETUP_WIZARD_DESIGN.md
dwindown 247b2c6b74 feat: Implement Payment Gateways backend foundation
 Phase 1 Backend Complete:

📦 PaymentGatewaysProvider.php:
- Read WC gateways from WC()->payment_gateways()
- Transform to clean JSON format
- Categorize: manual/provider/other
- Extract settings: basic/api/advanced
- Check requirements (SSL, extensions)
- Generate webhook URLs
- Respect WC bone structure (WC_Payment_Gateway)

📡 PaymentsController.php:
- GET /woonoow/v1/payments/gateways (list all)
- GET /woonoow/v1/payments/gateways/{id} (single)
- POST /woonoow/v1/payments/gateways/{id} (save settings)
- POST /woonoow/v1/payments/gateways/{id}/toggle (enable/disable)
- Permission checks (manage_woocommerce)
- Error handling with proper HTTP codes
- Response caching (5 min)

🔌 Integration:
- Registered in Api/Routes.php
- Auto-discovers all WC-compliant gateways
- No new hooks - listens to WC structure

📋 Checklist Progress:
- [x] PaymentGatewaysProvider.php
- [x] PaymentsController.php
- [x] REST API registration
- [ ] Frontend components (next)
2025-11-05 21:09:49 +07:00

29 KiB

Settings & Setup Wizard - Implementation Guide

Living Document - Track progress, maintain standards, keep on track

Overview

WooNooW Settings act as a "better wardrobe" for WooCommerce configuration - reading WC's bone structure, transforming complexity into simplicity, and enhancing performance.

Core Philosophy

  1. Read WooCommerce Structure - Listen to WC's registered entities (gateways, shipping, settings)
  2. Transform & Simplify - Convert complex WC settings into clean, categorized UI
  3. Enhance Performance - Direct DB operations where safe (30s → 1-2s)
  4. Respect Ecosystem - Auto-support WC-compliant addons
  5. No New Hooks - Listen to WC hooks, don't create parallel system

Goals

  1. Fast Setup - Get store operational in < 10 minutes (wizard)
  2. Smart Defaults - Pre-configure based on location/industry
  3. Progressive - Can skip and complete later
  4. Educational - Teach key concepts without overwhelming
  5. Performance - Settings save in 1-2s (not 30s like WC)

IMPLEMENTATION CHECKLIST

Phase 1: Payment Gateways Foundation

Backend - Payment Gateways Provider

  • Create includes/Compat/PaymentGatewaysProvider.php
    • get_gateways() - Read from WC()->payment_gateways()->payment_gateways()
    • categorize_gateway() - Classify as manual/provider/other
    • transform_gateway() - Convert WC format to clean JSON
    • get_gateway_settings() - Read gateway form fields
    • categorize_settings() - Group into basic/api/advanced
    • check_requirements() - Validate PHP extensions, dependencies
    • get_webhook_url() - Generate webhook URLs for gateways
    • Handle gateways that don't extend WC_Payment_Gateway gracefully

Backend - REST API Controller

  • Create includes/API/PaymentsController.php
    • GET /woonoow/v1/payments/gateways - List all gateways
    • GET /woonoow/v1/payments/gateways/{id} - Get single gateway
    • POST /woonoow/v1/payments/gateways/{id} - Save gateway settings
    • POST /woonoow/v1/payments/gateways/{id}/toggle - Enable/disable
    • Permission checks (manage_woocommerce)
    • Error handling with proper HTTP codes
    • Validation using gateway's own validation methods
    • Response caching headers

Frontend - Generic Form Builder

  • Create src/components/settings/GenericGatewayForm.tsx
    • Support field types: text, password, checkbox, select, textarea
    • Support field types: number, email, url
    • Unsupported field types → Show link to WC settings
    • Field validation (required, pattern, min, max)
    • Field descriptions and help text
    • Conditional field visibility
    • Multi-page form for 20+ fields (tabs: Basic, API, Advanced)
    • Loading states
    • Error states with helpful messages
    • Success feedback

Frontend - Update Payments Page

  • Update src/routes/Settings/Payments.tsx
    • Replace mock data with API calls
    • Use useQuery for fetching gateways
    • Use useMutation for saving settings
    • Optimistic updates for enable/disable toggles
    • Refetch on window focus
    • Manual refresh button
    • Loading skeleton while fetching
    • Empty state (no gateways)
    • Error boundary for gateway cards
    • Group by category (manual, providers, other)

UI Components

  • Create src/components/settings/GatewayCard.tsx

    • Show gateway icon, name, description
    • Show enabled/disabled badge
    • Show connected/not connected badge (for providers)
    • Show requirements warning if not met
    • "Manage" button → Opens settings modal/page
    • "Enable/Disable" toggle
    • "View in WooCommerce" link for complex gateways
    • Keyboard accessible (tab, enter)
    • Mobile responsive
  • Create src/components/settings/GatewaySettingsModal.tsx

    • Modal wrapper for gateway settings
    • Renders GenericGatewayForm or custom component
    • Save/Cancel buttons
    • Dirty state detection
    • Confirm before closing if unsaved changes
  • Create src/components/settings/WebhookHelper.tsx

    • Display webhook URL
    • Copy to clipboard button
    • Instructions for common gateways (Stripe, PayPal)
    • Test webhook button (if gateway supports)

Testing & Quality

  • ESLint: 0 errors, 0 warnings
  • TypeScript: strict mode passes
  • Test with WooCommerce not installed
  • Test with no gateways registered
  • Test with 1 gateway
  • Test with 10+ gateways
  • Test enable/disable toggle
  • Test save settings (valid data)
  • Test save settings (invalid data)
  • Test with Stripe gateway installed
  • Test with PayPal gateway installed
  • Test with custom gateway
  • Test in all 3 admin modes (normal, fullscreen, standalone)
  • Test keyboard navigation
  • Test mobile responsive
  • Performance: API response < 500ms
  • Performance: Settings save < 2s

Phase 2: Custom Gateway UIs

Stripe Custom UI

  • Create src/components/settings/gateways/StripeSettings.tsx
    • Categorized tabs: Basic, API Keys, Advanced
    • Live/Test mode toggle with visual indicator
    • API key validation (format check)
    • Webhook URL helper
    • Test connection button
    • Supported payment methods checklist
    • 3D Secure settings
    • Statement descriptor preview

PayPal Custom UI

  • Create src/components/settings/gateways/PayPalSettings.tsx
    • Categorized tabs: Basic, API, Advanced
    • Sandbox/Live mode toggle
    • Client ID & Secret fields
    • Webhook URL helper
    • Test connection button
    • PayPal button customization preview
    • Invoice prefix settings

Gateway Registry

  • Create src/lib/gatewayRegistry.ts
    • Map gateway IDs to custom components
    • Fallback to GenericGatewayForm
    • Feature flags for gradual rollout

Phase 3: Shipping Methods

Backend - Shipping Provider

  • Create includes/Compat/ShippingMethodsProvider.php
    • get_zones() - Read from WC_Shipping_Zones::get_zones()
    • get_zone_methods() - Get methods for each zone
    • transform_zone() - Convert WC format to clean JSON
    • transform_method() - Convert method settings
    • get_available_methods() - List all registered shipping methods
    • Handle methods that don't extend WC_Shipping_Method gracefully

Backend - REST API Controller

  • Create includes/API/ShippingController.php
    • GET /woonoow/v1/shipping/zones - List all zones
    • GET /woonoow/v1/shipping/zones/{id} - Get single zone
    • POST /woonoow/v1/shipping/zones/{id}/methods/{method_id} - Save method
    • POST /woonoow/v1/shipping/zones/{id}/methods/{method_id}/toggle - Enable/disable
    • Permission checks
    • Error handling
    • Validation

Frontend - Update Shipping Page

  • Update src/routes/Settings/Shipping.tsx
    • Replace mock data with API calls
    • Use useQuery for fetching zones
    • Use useMutation for saving
    • Optimistic updates
    • Refetch on focus
    • Loading/error states

UI Components

  • Create src/components/settings/ShippingZoneCard.tsx
  • Create src/components/settings/ShippingMethodCard.tsx
  • Create src/components/settings/GenericShippingForm.tsx

Phase 4: Store Settings

Backend - Store Settings Provider

  • Create includes/Compat/StoreSettingsProvider.php
    • Read WC general settings
    • Read WC product settings
    • Transform to clean format
    • Group by category

Backend - REST API

  • Create includes/API/StoreController.php
    • GET /woonoow/v1/store/settings - Get all store settings
    • POST /woonoow/v1/store/settings - Save settings
    • Direct DB operations for performance
    • Validation

Frontend - Update Store Page

  • Update src/routes/Settings/Store.tsx
    • Replace mock data with API calls
    • Currency selector with live preview
    • Country/timezone auto-detection
    • Address autocomplete
    • Save performance < 2s

Phase 5: Setup Wizard

Wizard Flow (5 Steps)

Step 1: Store Basics

  • Store name, email, country (required)
  • Auto-detect currency, timezone
  • Industry selector (optional)
  • Save to WC general settings

Step 2: Payments

  • Show recognized gateways if installed
  • Enable manual methods (Bank Transfer, COD)
  • Minimal fields (enable/disable only)
  • Link to full settings for advanced config

Step 3: Shipping

  • Simple flat rate setup
  • Domestic/International zones
  • Free shipping threshold
  • Link to full settings

Step 4: Taxes

  • Auto-calculate toggle
  • Tax rate from country
  • Manual rate option
  • Can skip

Step 5: First Product

  • Create sample product
  • Import CSV
  • Skip option

Wizard Components

  • Create src/routes/Setup/index.tsx
  • Create src/routes/Setup/StepProgress.tsx
  • Create src/routes/Setup/steps/StoreBasics.tsx
  • Create src/routes/Setup/steps/Payments.tsx
  • Create src/routes/Setup/steps/Shipping.tsx
  • Create src/routes/Setup/steps/Taxes.tsx
  • Create src/routes/Setup/steps/FirstProduct.tsx
  • Create src/routes/Setup/Complete.tsx

Wizard State

  • Create Zustand store for wizard state
  • Save progress at each step
  • Resume from last step
  • Dashboard banner to resume incomplete setup

Phase 6: Polish & Enhancement

Error Handling

  • Error boundaries for each gateway/method card
  • Fallback to WC settings on error
  • Helpful error messages
  • Retry mechanisms

Performance

  • Monitor API response times
  • Cache gateway/method lists (5 min stale time)
  • Optimistic updates for toggles
  • Direct DB writes where safe
  • Lazy load custom gateway components

Accessibility

  • Keyboard navigation (tab, enter, escape)
  • ARIA labels and roles
  • Focus management in modals
  • Screen reader announcements
  • Color contrast compliance

Documentation

  • Inline help text for all fields
  • Tooltips for complex options
  • Link to docs for advanced features
  • Video tutorials (future)

Analytics

  • Track gateway configuration time
  • Track wizard completion rate
  • Track which gateways are used
  • Track settings save performance

TECHNICAL SPECIFICATIONS

API Response Format

Payment Gateway

{
  "id": "stripe",
  "title": "Stripe Payments",
  "description": "Accept Visa, Mastercard, Amex",
  "enabled": true,
  "type": "provider",
  "icon": "credit-card",
  "connected": true,
  "test_mode": false,
  "requirements": {
    "met": true,
    "missing": []
  },
  "settings": {
    "basic": [...],
    "api": [...],
    "advanced": [...]
  },
  "webhook_url": "https://example.com/wc-api/stripe",
  "has_custom_ui": true,
  "wc_settings_url": "admin.php?page=wc-settings&tab=checkout&section=stripe"
}

Shipping Zone

{
  "id": 1,
  "name": "Domestic",
  "regions": ["ID"],
  "methods": [
    {
      "id": "flat_rate:1",
      "instance_id": 1,
      "title": "Flat Rate",
      "enabled": true,
      "method_id": "flat_rate",
      "settings": {...}
    }
  ]
}

Performance Targets

Operation Target Current WC
Load gateways < 500ms ~2s
Save gateway settings < 2s ~30s
Load shipping zones < 500ms ~3s
Save shipping method < 2s ~30s
Wizard completion < 10min N/A

Browser Support

  • Chrome 90+
  • Firefox 88+
  • Safari 14+
  • Edge 90+
  • Mobile Safari 14+
  • Chrome Android 90+

COMPATIBILITY MATRIX

Supported Payment Gateways

Gateway Type Custom UI Status
Bank Transfer (BACS) Manual Generic Built-in
Cash on Delivery Manual Generic Built-in
Check Payments Manual Generic Built-in
Stripe Provider Custom 🔄 Phase 2
PayPal Provider Custom 🔄 Phase 2
Square Provider Generic Auto-support
Authorize.net Provider Generic Auto-support
Other WC-compliant Any Generic Auto-support

Supported Shipping Methods

Method Custom UI Status
Flat Rate Generic Built-in
Free Shipping Generic Built-in
Local Pickup Generic Built-in
Table Rate Generic Auto-support
Other WC-compliant Generic Auto-support

WIZARD FLOW DETAILS


Wizard Flow (5 Steps)

Step 1: Store Basics (2 min)

Purpose: Essential store identity

Fields:

  • Store name (required)
  • Store email (required)
  • Country (required) → Auto-detects currency, timezone
  • Industry (optional) → Suggests products/categories

Smart Defaults:

  • Currency from country
  • Timezone from country
  • Language from browser

Skip: Cannot skip (required for operation)


Step 2: Payments (2 min)

Purpose: Enable at least one payment method

Options:

  1. Quick Start (Recommended)

    • Enable manual methods (Bank Transfer, COD)
    • "Set up Stripe later" button
  2. Connect Payment Provider

    • Stripe (OAuth flow)
    • PayPal (OAuth flow)
    • Other providers

Smart Defaults:

  • Bank Transfer: Enabled
  • Cash on Delivery: Enabled if physical products

Skip: ⚠️ Warning: "Customers won't be able to checkout"


Step 3: Shipping (2 min)

Purpose: Configure basic shipping

Options:

  1. Simple Shipping

    • Flat rate for domestic
    • Flat rate for international
    • Free shipping threshold (optional)
  2. Advanced Setup

    • Multiple zones
    • Calculated rates
    • Carrier integrations

Smart Defaults:

  • Domestic zone: Country from Step 1
  • Flat rate: $10 (or currency equivalent)

Skip: ⚠️ Warning: "Only for digital products"


Step 4: Taxes (1 min)

Purpose: Basic tax compliance

Options:

  1. Auto-calculate (Recommended)

    • Based on customer location
    • Standard rates from database
  2. Manual rates

    • Set fixed percentage
    • Per-country rates
  3. No taxes

    • For tax-exempt stores

Smart Defaults:

  • Auto-calculate: ON
  • Tax rate from country (e.g., 10% for Indonesia VAT)

Skip: Can skip (configure later)


Step 5: First Product (3 min)

Purpose: Create sample product to test checkout

Options:

  1. Create Sample Product (Recommended)

    • Pre-filled with dummy data
    • Can edit or delete later
    • Helps test checkout flow
  2. Import Products

    • CSV upload
    • WooCommerce import
  3. Skip for now

    • Add products later

Smart Defaults:

  • Sample product based on industry from Step 1

Skip: Can skip


Technical Architecture

Frontend Components

/routes/Setup/
├── index.tsx           # Wizard container
├── StepProgress.tsx    # Progress indicator (1/5, 2/5, etc)
├── steps/
│   ├── StoreBasics.tsx
│   ├── Payments.tsx
│   ├── Shipping.tsx
│   ├── Taxes.tsx
│   └── FirstProduct.tsx
└── Complete.tsx        # Success screen

Backend API

// REST API Endpoints
POST /woonoow/v1/setup/store-basics
POST /woonoow/v1/setup/payments
POST /woonoow/v1/setup/shipping
POST /woonoow/v1/setup/taxes
POST /woonoow/v1/setup/first-product
POST /woonoow/v1/setup/complete

// Option to track wizard state
update_option('wnw_setup_completed', true);
update_option('wnw_setup_step', 3); // Current step

State Management

// Zustand store for wizard state
interface SetupState {
  currentStep: number;
  completed: boolean;
  data: {
    storeBasics: StoreBasicsData;
    payments: PaymentsData;
    shipping: ShippingData;
    taxes: TaxesData;
    firstProduct: ProductData;
  };
  goToStep: (step: number) => void;
  saveStep: (step: string, data: any) => Promise<void>;
  completeSetup: () => Promise<void>;
}

Payment Provider Integration

Architecture

Problem: How to support payment addons (Stripe, PayPal, Xendit, Midtrans, etc)?

Solution: WordPress filter hooks + React components

Backend: Payment Provider Registry

<?php
// includes/Compat/PaymentProviderRegistry.php

class PaymentProviderRegistry {
    
    /**
     * Get all registered payment providers
     * Allows addons to register their providers
     */
    public static function get_providers(): array {
        $providers = [
            // Built-in manual methods
            [
                'id' => 'bacs',
                'name' => 'Bank Transfer (BACS)',
                'type' => 'manual',
                'enabled' => true,
                'icon' => 'banknote',
            ],
            [
                'id' => 'cod',
                'name' => 'Cash on Delivery',
                'type' => 'manual',
                'enabled' => true,
                'icon' => 'banknote',
            ],
        ];
        
        /**
         * Filter: Allow addons to register payment providers
         * 
         * @param array $providers List of payment providers
         * 
         * Example addon usage:
         * add_filter('woonoow_payment_providers', function($providers) {
         *     $providers[] = [
         *         'id' => 'stripe',
         *         'name' => 'Stripe Payments',
         *         'type' => 'gateway',
         *         'description' => 'Accept Visa, Mastercard, Amex',
         *         'icon' => 'credit-card',
         *         'enabled' => false,
         *         'connected' => false,
         *         'setup_url' => admin_url('admin.php?page=wc-settings&tab=checkout&section=stripe'),
         *         'component_url' => plugins_url('build/stripe-settings.js', __FILE__),
         *         'fees' => '2.9% + $0.30 per transaction',
         *     ];
         *     return $providers;
         * });
         */
        return apply_filters('woonoow_payment_providers', $providers);
    }
    
    /**
     * Get provider configuration
     */
    public static function get_provider_config(string $provider_id): array {
        $providers = self::get_providers();
        foreach ($providers as $provider) {
            if ($provider['id'] === $provider_id) {
                return $provider;
            }
        }
        return [];
    }
    
    /**
     * Save provider settings
     */
    public static function save_provider_settings(string $provider_id, array $settings): bool {
        // Save to WooCommerce payment gateway settings
        $gateway = WC()->payment_gateways()->payment_gateways()[$provider_id] ?? null;
        if ($gateway) {
            foreach ($settings as $key => $value) {
                $gateway->update_option($key, $value);
            }
            return true;
        }
        return false;
    }
}

REST API Endpoint

<?php
// includes/API/PaymentsController.php

class PaymentsController {
    
    public static function register_routes() {
        register_rest_route('woonoow/v1', '/payments/providers', [
            'methods' => 'GET',
            'callback' => [self::class, 'get_providers'],
            'permission_callback' => [self::class, 'check_permission'],
        ]);
        
        register_rest_route('woonoow/v1', '/payments/providers/(?P<id>[a-zA-Z0-9_-]+)', [
            'methods' => 'POST',
            'callback' => [self::class, 'save_provider'],
            'permission_callback' => [self::class, 'check_permission'],
        ]);
    }
    
    public static function get_providers(WP_REST_Request $request) {
        $providers = PaymentProviderRegistry::get_providers();
        return rest_ensure_response($providers);
    }
    
    public static function save_provider(WP_REST_Request $request) {
        $provider_id = $request->get_param('id');
        $settings = $request->get_json_params();
        
        $success = PaymentProviderRegistry::save_provider_settings($provider_id, $settings);
        
        if ($success) {
            return rest_ensure_response(['success' => true]);
        }
        
        return new WP_Error('save_failed', 'Failed to save provider settings', ['status' => 500]);
    }
}

Frontend: Dynamic Provider Loading

// src/routes/Settings/Payments.tsx

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';

export default function PaymentsPage() {
  // Fetch providers from API (includes addon providers)
  const { data: providers = [], isLoading } = useQuery({
    queryKey: ['payment-providers'],
    queryFn: () => api.get('/payments/providers'),
  });
  
  return (
    <SettingsLayout title="Payments">
      {/* Manual Methods */}
      <SettingsCard title="Manual Payment Methods">
        {providers
          .filter(p => p.type === 'manual')
          .map(provider => (
            <PaymentMethodCard key={provider.id} provider={provider} />
          ))}
      </SettingsCard>
      
      {/* Payment Gateways */}
      <SettingsCard title="Payment Providers">
        {providers
          .filter(p => p.type === 'gateway')
          .map(provider => (
            <PaymentProviderCard key={provider.id} provider={provider} />
          ))}
      </SettingsCard>
    </SettingsLayout>
  );
}

Addon Example: Stripe Integration

<?php
/**
 * Plugin Name: WooNooW Stripe Addon
 * Description: Stripe payment gateway for WooNooW
 */

// Register Stripe provider
add_filter('woonoow_payment_providers', function($providers) {
    $stripe_settings = get_option('woocommerce_stripe_settings', []);
    
    $providers[] = [
        'id' => 'stripe',
        'name' => 'Stripe Payments',
        'type' => 'gateway',
        'description' => 'Accept Visa, Mastercard, Amex, and more',
        'icon' => 'credit-card',
        'enabled' => $stripe_settings['enabled'] === 'yes',
        'connected' => !empty($stripe_settings['publishable_key']),
        'setup_url' => admin_url('admin.php?page=wc-settings&tab=checkout&section=stripe'),
        'component_url' => plugins_url('build/stripe-settings.js', __FILE__),
        'fees' => '2.9% + $0.30 per transaction',
        'test_mode' => $stripe_settings['testmode'] === 'yes',
    ];
    
    return $providers;
});

Shipping Methods Integration

Backend: Shipping Method Registry

<?php
// includes/Compat/ShippingMethodRegistry.php

class ShippingMethodRegistry {
    
    /**
     * Get all shipping zones with methods
     * Allows addons to register custom shipping methods
     */
    public static function get_zones(): array {
        $zones_data = [];
        $zones = WC_Shipping_Zones::get_zones();
        
        foreach ($zones as $zone) {
            $zone_obj = new WC_Shipping_Zone($zone['id']);
            $methods = $zone_obj->get_shipping_methods();
            
            $zone_methods = [];
            foreach ($methods as $method) {
                $zone_methods[] = [
                    'id' => $method->id,
                    'instance_id' => $method->instance_id,
                    'title' => $method->title,
                    'enabled' => $method->enabled === 'yes',
                    'method_id' => $method->id,
                    'settings' => $method->instance_settings,
                ];
            }
            
            $zones_data[] = [
                'id' => $zone['id'],
                'name' => $zone['zone_name'],
                'regions' => $zone['formatted_zone_location'],
                'methods' => $zone_methods,
            ];
        }
        
        /**
         * Filter: Allow addons to modify shipping zones
         * 
         * @param array $zones_data List of shipping zones with methods
         * 
         * Example addon usage:
         * add_filter('woonoow_shipping_zones', function($zones) {
         *     // Add custom shipping method to each zone
         *     foreach ($zones as &$zone) {
         *         $zone['methods'][] = [
         *             'id' => 'custom_shipping',
         *             'title' => 'Custom Shipping',
         *             'enabled' => true,
         *             'component_url' => plugins_url('build/custom-shipping.js', __FILE__),
         *         ];
         *     }
         *     return $zones;
         * });
         */
        return apply_filters('woonoow_shipping_zones', $zones_data);
    }
    
    /**
     * Get available shipping methods (for adding to zones)
     */
    public static function get_available_methods(): array {
        $wc_methods = WC()->shipping()->get_shipping_methods();
        $methods = [];
        
        foreach ($wc_methods as $method) {
            $methods[] = [
                'id' => $method->id,
                'title' => $method->method_title,
                'description' => $method->method_description,
            ];
        }
        
        /**
         * Filter: Allow addons to register custom shipping methods
         */
        return apply_filters('woonoow_available_shipping_methods', $methods);
    }
}

REST API Endpoint

<?php
// includes/API/ShippingController.php

class ShippingController {
    
    public static function register_routes() {
        register_rest_route('woonoow/v1', '/shipping/zones', [
            'methods' => 'GET',
            'callback' => [self::class, 'get_zones'],
            'permission_callback' => [self::class, 'check_permission'],
        ]);
        
        register_rest_route('woonoow/v1', '/shipping/methods', [
            'methods' => 'GET',
            'callback' => [self::class, 'get_methods'],
            'permission_callback' => [self::class, 'check_permission'],
        ]);
    }
    
    public static function get_zones(WP_REST_Request $request) {
        $zones = ShippingMethodRegistry::get_zones();
        return rest_ensure_response($zones);
    }
    
    public static function get_methods(WP_REST_Request $request) {
        $methods = ShippingMethodRegistry::get_available_methods();
        return rest_ensure_response($methods);
    }
}

Frontend: Dynamic Shipping Loading

// src/routes/Settings/Shipping.tsx

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';

export default function ShippingPage() {
  // Fetch zones from API (includes addon methods)
  const { data: zones = [], isLoading } = useQuery({
    queryKey: ['shipping-zones'],
    queryFn: () => api.get('/shipping/zones'),
  });
  
  return (
    <SettingsLayout title="Shipping & Delivery">
      {/* Shipping Zones */}
      <SettingsCard title="Shipping Zones">
        {zones.map(zone => (
          <ShippingZoneCard key={zone.id} zone={zone} />
        ))}
      </SettingsCard>
    </SettingsLayout>
  );
}

Implementation Timeline

Phase 1: Foundation (Week 1)

  • Create PaymentProviderRegistry.php
  • Create ShippingMethodRegistry.php
  • Add REST API endpoints
  • Update Payments.tsx to use API
  • Update Shipping.tsx to use API

Phase 2: Setup Wizard (Week 2)

  • Create wizard UI components
  • Implement 5-step flow
  • Add smart defaults
  • Add skip logic
  • Create completion screen

Phase 3: Addon Support (Week 3)

  • Document filter hooks
  • Create example addons
  • Test with real payment gateways
  • Test with shipping plugins

Phase 4: Polish (Week 4)

  • Add animations/transitions
  • Improve error handling
  • Add help documentation
  • User testing & feedback

Success Metrics

  1. Setup Time - < 10 minutes average
  2. Completion Rate - > 80% complete wizard
  3. Payment Setup - > 90% enable at least one method
  4. Shipping Setup - > 70% configure shipping
  5. First Sale - < 24 hours after setup

Future Enhancements

  1. AI-Powered Suggestions

    • Detect industry from store name
    • Suggest products based on industry
    • Recommend payment methods by country
  2. Video Tutorials

    • Embedded help videos
    • Step-by-step guides
  3. Templates

    • Pre-configured setups by industry
    • "Fashion Store", "Digital Products", etc.
  4. Import Wizards

    • Import from Shopify
    • Import from WooCommerce
    • Import from CSV

Questions & Answers

Q: How do payment addons register themselves?

A: Use the woonoow_payment_providers filter hook to add providers to the list. The addon provides metadata (name, icon, fees) and optionally a React component URL for custom settings UI.

Q: Can addons have custom settings UI?

A: Yes! Addons can provide a component_url that points to a React component. WooNooW will dynamically load and render it in the settings page.

Q: How does the wizard handle incomplete setup?

A: The wizard saves progress at each step. Users can exit and resume later. A dashboard banner reminds them to complete setup.

Q: Can merchants skip the wizard?

A: Yes, but they'll see a persistent banner until they complete essential steps (store basics, at least one payment method).

Q: How do we handle payment gateway OAuth flows?

A: Payment addons provide a setup_url that can be an OAuth redirect. After completion, the addon updates its connection status via the API.