HubSpot Sync - Milli

A comprehensive WordPress plugin that provides complete WooCommerce-to-HubSpot integration with advanced abandoned cart tracking, device management, and external system integration. Built by Team Outsiders as a modern, consolidated replacement for multiple HubSpot gateway plugins.

✨ Key Features

πŸ›’ Advanced Abandoned Cart Tracking

  • Real-Time Monitoring: Tracks 21+ checkout fields with debounced AJAX calls
  • Smart Cart Conversion: Converts abandoned cart deals to completed orders (prevents duplicates)
  • Persistent Hash System: Maintains cart identity across sessions and page reloads
  • Customer Journey Tracking: Complete lifecycle from abandonment to conversion in single HubSpot deal

πŸ”„ Comprehensive Sync System

  • Contact Management: Bi-directional sync with custom field mapping
  • Deal Lifecycle: Automated deal creation, updates, and stage transitions
  • Device Integration: Serial number tracking from fulfillment to HubSpot custom objects
  • Background Processing: Non-blocking async sync with cron job scheduling
  • External API Ready: REST endpoints for ShipHero and other fulfillment systems

πŸ“± Device & Serial Number Management

  • Order Item Tracking: Serial numbers stored in WooCommerce order meta
  • HubSpot Device Objects: Automatic device creation with full property mapping
  • Association Management: Links devices to contacts, deals, and companies
  • ShipHero Integration: Automatic monitoring of existing ShipHero webhooks for serial numbers
  • Batch Processing: Handle multiple serial number assignments efficiently
  • Manual Sync Options: Admin controls for immediate device synchronization

βš™οΈ Enterprise-Grade Configuration

  • Environment Detection: Staging, Production, Development modes with safe testing
  • Custom Field Mapping: Flexible mapping between WooCommerce and HubSpot properties
  • Deal Stage Management: Configurable stages for all order statuses including abandonment
  • Sync Triggers: Granular control over when syncing occurs
  • Rate Limiting: Built-in API throttling to prevent HubSpot rate limits

πŸ›‘οΈ Security & Reliability

  • Nonce Verification: Secure AJAX endpoints with proper authentication
  • Data Sanitization: All inputs sanitized and validated
  • Error Handling: Comprehensive try-catch blocks with detailed logging
  • Fault Tolerance: Graceful degradation when external services are unavailable
  • Debug Mode: Detailed logging for troubleshooting and monitoring

πŸš€ Installation

  1. Upload the hubspot-sync-milli folder to /wp-content/plugins/
  2. Activate the plugin through the WordPress β€˜Plugins’ menu
  3. Configure settings at Settings β†’ HubSpot Sync

Requirements:

  • WordPress 5.0+
  • WooCommerce 4.0+
  • PHP 7.4+
  • HubSpot Private App with CRM permissions

⚑ Quick Configuration

1. HubSpot API Setup

Create a HubSpot Private App with these scopes:

β€’ crm.objects.contacts.read
β€’ crm.objects.contacts.write
β€’ crm.objects.deals.read
β€’ crm.objects.deals.write
β€’ crm.objects.companies.read
β€’ crm.objects.companies.write
β€’ crm.objects.custom.read
β€’ crm.objects.custom.write

2. Essential Settings

  • API Token: Your HubSpot Private App access token
  • Site Prefix: Unique identifier for this site (e.g., β€œMyStore”)
  • Deal Pipeline: HubSpot pipeline ID for WooCommerce deals
  • Owner ID: Default HubSpot owner for new contacts/deals

3. Deal Stage Mapping

| Order Status | HubSpot Stage | Purpose | |————–|β€”β€”β€”β€”β€”|β€”β€”β€”| | Abandoned Cart | abandoned_cart | Real-time cart tracking | | Pending Payment | pending_payment | Payment gateways like AfterPay | | On Hold | on_hold | Orders awaiting payment processing | | Processing | processing | Orders being fulfilled | | Completed | won | Successfully completed orders | | Cancelled | cancelled | Customer cancellations | | Refunded | refunded | Processed refunds | | Failed | failed | Payment failures |

🎯 Core Functionality

Abandoned Cart System

Real-time tracking prevents deal duplication:

graph LR
    A[Checkout Form] -->|Field Changes| B[Debounced AJAX]
    B --> C[Cart Hash Generated]
    C --> D[HubSpot Deal Created]
    D -->|Customer Returns| E[Same Deal Updated]
    E -->|Order Complete| F[Deal Converted]
    F --> G[Single Deal Journey]

Benefits:

  • βœ… Single deal tracks complete customer journey
  • βœ… No duplicate deals for same customer
  • βœ… Accurate conversion rate reporting
  • βœ… Preserved attribution and source data

Device Management Workflow

Complete serial number to HubSpot integration:

  1. Order Completion: Customer places order
  2. Fulfillment: ShipHero (or external system) ships product
  3. Serial Assignment: Webhook or API call adds serial number to order
  4. Automatic Detection: Plugin monitors order meta updates (non-destructive)
  5. Device Creation: HubSpot device object created automatically
  6. Association: Device linked to contact, deal, and company

πŸ“Š Field Mapping

πŸ›’ Checkout Fields Configuration

The plugin supports two checkout field implementations:

Full Checkout Fields (Default)

  • Multi-step conditional form with acquisition source dropdown
  • Healthcare provider conversation questions
  • Conditional provider referral questions
  • Provider detail collection (name, clinic, state)

Simplified Checkout Fields

  • Single radio button: β€œWere you referred by a healthcare provider?”
  • Yes/No options only
  • Streamlined user experience

To Switch to Simplified Checkout:

  1. Open hubspot-sync-milli.php
  2. Change: define( 'HUBSPOT_SYNC_MILLI_USE_SIMPLE_CHECKOUT', true );
  3. Save the file

Note: Both implementations map to the same HubSpot properties, ensuring data consistency.

Checkout Fields β†’ HubSpot Properties

| Checkout Field | HubSpot Property | Type | Description | Available In | |β€”|β€”|β€”|β€”|β€”| | Acquisition Source | how_did_you_hear_about_us_consumer | Dropdown | Marketing attribution | Full Only | | Clinician Name | referring_clinician | Text | Healthcare provider | Full Only | | Clinic State | referring_state | Dropdown | Provider location | Full Only | | Clinic Name | referring_clinic | Text | Practice name | Full Only | | Provider Conversation | have_you_talked_to_healthcare_provider | Yes/No | Consultation status | Full Only | | Provider Referral | did_your_provider_refer_you_to_milli_ | Yes/No | Referral verification | Both Versions |

Device Properties

| Property | Source | Description | |β€”β€”β€”-|——–|β€”β€”β€”β€”-| | serial_number | Order meta | Unique device identifier | | order_id | WooCommerce | Associated order number | | customer_email | Order billing | Device owner | | assignment_date | Current time | When device was assigned | | product_name | Order items | Product associated with device |

πŸ”Œ API Integration

REST Endpoints

Add Serial Number

POST /wp-json/hubspot-sync-milli/v1/serial-number
Authorization: Bearer {token}
Content-Type: application/json

{
    "order_id": 12345,
    "serial_number": "SN123456789"
}

Test Connection

POST /wp-admin/admin-ajax.php
Content-Type: application/x-www-form-urlencoded

action=hubspot_sync_milli_test_connection
&nonce={admin_nonce}

Webhook Integration

ShipHero Integration (Automatic)

The plugin automatically monitors existing ShipHero webhook processing:

// No code changes needed - plugin hooks into existing ShipHero workflow:
// 1. ShipHero webhook β†’ api-shiphero.php (existing)
// 2. Serial numbers saved to order meta (existing) 
// 3. Plugin detects meta update β†’ triggers HubSpot device creation (new)

// Monitoring is added via WordPress hooks:
add_action('updated_post_meta', 'on_order_meta_updated', 10, 4);

External Webhook Integration (Manual)

// External systems can trigger serial number assignment
add_action('wp_ajax_nopriv_external_webhook', function() {
    $data = json_decode(file_get_contents('php://input'), true);
    
    foreach ($data as $shipment) {
        HubSpot_Sync_Milli_Serial_Number_Manager::add_serial_number(
            $shipment['Order ID'],
            $shipment['Product Serial Number Shipped']
        );
    }
    
    wp_die('OK');
});

πŸ“ File Structure

hubspot-sync-milli/
β”œβ”€β”€ hubspot-sync-milli.php              # Main plugin file
β”œβ”€β”€ README.md                           # This overview documentation
β”œβ”€β”€ docs/                              # Complete documentation library
β”‚   β”œβ”€β”€ index.md                       # Documentation homepage
β”‚   β”œβ”€β”€ ABANDONED_CART.md              # Abandoned cart guide
β”‚   β”œβ”€β”€ SERIAL_NUMBERS.md              # Device integration guide
β”‚   β”œβ”€β”€ CHECKOUT_FIELDS.md             # Checkout fields configuration
β”‚   β”œβ”€β”€ HOOKS_AND_TRIGGERS.md          # Developer reference
β”‚   β”œβ”€β”€ HUBSPOT-SETUP.md               # HubSpot configuration guide
β”‚   └── UPDATES.md                     # Update system documentation
β”œβ”€β”€ includes/
β”‚   β”œβ”€β”€ class-hubspot-sync-milli.php    # Core plugin orchestration
β”‚   β”œβ”€β”€ class-admin-settings.php        # Admin interface & settings
β”‚   β”œβ”€β”€ class-hubspot-api.php          # HubSpot API wrapper
β”‚   β”œβ”€β”€ class-checkout-fields.php       # Full checkout fields implementation
β”‚   β”œβ”€β”€ class-checkout-fields-simple.php # Simplified checkout fields
β”‚   β”œβ”€β”€ class-sync-manager.php         # Sync orchestration & logic
β”‚   β”œβ”€β”€ class-abandoned-cart-tracker.php # Real-time cart tracking
β”‚   └── class-serial-number-manager.php # Device management utilities
β”œβ”€β”€ assets/
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   β”œβ”€β”€ admin.css                  # Admin interface styling
β”‚   β”‚   └── checkout.css               # Checkout field styling
β”‚   └── js/
β”‚       β”œβ”€β”€ admin.js                   # Admin functionality
β”‚       β”œβ”€β”€ checkout.js                # Checkout interactions
β”‚       └── abandoned-cart-tracker.js  # Real-time form monitoring
β”œβ”€β”€ examples/
β”‚   └── serial-number-examples.php     # Integration code examples
└── tests/
    β”œβ”€β”€ complete-system-breakdown.php   # Detailed functionality trace
    └── executable-test.php            # Runnable test simulation

πŸ§ͺ Testing & Debugging

Comprehensive Testing Framework

The plugin includes detailed testing tools:

Executable Test Suite

# Run complete system test via WP-CLI
wp eval-file wp-content/plugins/hubspot-sync-milli/tests/executable-test.php

# Output shows complete buying process simulation:
# βœ“ Stage 1: Checkout page load
# βœ“ Stage 2: Form interaction (abandonment)
# βœ“ Stage 3: HubSpot sync
# βœ“ Stage 4: Customer return
# βœ“ Stage 5: Order completion  
# βœ“ Stage 6: Cart conversion
# βœ“ Stage 7: Background sync
# βœ“ Stage 8: Device assignment

Debug Logging

Enable in Settings β†’ HubSpot Sync β†’ Advanced:

[HubSpot Sync] Generated cart hash: abc123... for email: customer@example.com
[HubSpot Sync] Abandoned cart synced. Deal ID: 12345678
[HubSpot Sync] Converting cart abc123... to order 12345
[HubSpot Sync] Device SN123456 created with ID: 87654321

Manual Testing Checklist

  • Abandoned Cart: Fill checkout form, verify HubSpot deal creation
  • Cart Return: Modify form, confirm same deal updated
  • Order Completion: Complete purchase, verify deal conversion
  • Device Assignment: Add serial number, confirm HubSpot device creation
  • ShipHero Integration: Test with existing api-shiphero.php webhook
  • Admin Interface: Test connection, manual sync, bulk actions

βš™οΈ Advanced Usage

Background Sync System

// Orders sync in background (60-second delay)
wp_schedule_single_event(time() + 60, 'hubspot_sync_milli_cron', [$order_id]);

// Rate limiting prevents API throttling  
usleep(110000); // 110ms between API calls

Custom Field Integration

// Add custom fields to checkout
add_action('woocommerce_after_order_notes', function($checkout) {
    woocommerce_form_field('custom_field', [
        'type' => 'text',
        'label' => 'Custom Information',
        'id' => 'custom_field'
    ]);
});

// Map to HubSpot property
add_filter('hubspot_sync_milli_contact_data', function($data, $order) {
    $data['custom_property'] = $order->get_meta('custom_field');
    return $data;
}, 10, 2);

Serial Number Batch Processing

// Process CSV export from fulfillment system
$csv_data = [
    ['Order ID' => '12345', 'Product Serial Number Shipped' => 'SN123456'],
    ['Order ID' => '12346', 'Product Serial Number Shipped' => 'SN789012']
];

$result = HubSpot_Sync_Milli_Serial_Number_Manager::batch_add_serial_numbers($csv_data);
// Result: ['success' => true, 'processed' => 2, 'errors' => []]

πŸ› οΈ Hooks & Filters

Custom Actions

// Before/after sync events
do_action('hubspot_sync_milli_before_contact_sync', $contact_data, $order);
do_action('hubspot_sync_milli_after_contact_sync', $hubspot_contact_id, $order);
do_action('hubspot_sync_milli_before_deal_sync', $deal_data, $order);
do_action('hubspot_sync_milli_after_deal_sync', $hubspot_deal_id, $order);

// Device processing
do_action('hubspot_sync_milli_process_serial_number', $order_id, $serial_number);

Data Filters

// Modify data before HubSpot sync
add_filter('hubspot_sync_milli_contact_data', 'modify_contact_data', 10, 2);
add_filter('hubspot_sync_milli_deal_data', 'modify_deal_data', 10, 2);
add_filter('hubspot_sync_milli_device_data', 'modify_device_data', 10, 2);

πŸ”§ Troubleshooting

Common Issues

❌ Connection Test Failed

  • Verify API token format and permissions
  • Check HubSpot app scopes include CRM read/write
  • Ensure token belongs to correct portal

❌ Duplicate Deals Created

  • Check cart hash generation in browser storage
  • Verify session persistence across page loads
  • Enable debug logging to trace cart hash flow

❌ Device Sync Failed

  • Confirm device folder mapping in settings
  • Verify association IDs are configured
  • Check HubSpot custom object permissions

❌ Fields Not Syncing

  • Validate HubSpot property names match exactly
  • Check property exists in your HubSpot portal
  • Verify data types match (text, number, datetime, etc.)

Debug Mode

  1. Go to Settings β†’ HubSpot Sync β†’ Advanced
  2. Enable Debug Logging
  3. Save settings
  4. Check /wp-content/debug.log for detailed information

Performance Optimization

  • Rate Limiting: Built-in 110ms delays prevent API throttling
  • Background Sync: 60-second delay keeps checkout fast
  • Debounced AJAX: 1000ms debouncing prevents request spam
  • Batch Processing: Multiple records processed efficiently

πŸ“ˆ Reporting & Analytics

HubSpot Reports

Create custom reports using these properties:

  • Abandoned Cart Conversion Rate: order_source = "converted_from_abandoned_cart"
  • Device Assignment Status: Track devices per customer/order
  • Customer Journey Time: Time from abandonment to conversion
  • Source Attribution: Original acquisition source preserved through conversion

WordPress Admin

  • Order Sync Status: Visible on individual order pages
  • Manual Sync Actions: Force immediate synchronization
  • Bulk Operations: Process multiple orders simultaneously
  • Connection Testing: Validate API connectivity

πŸ“ž Support & Documentation

πŸ“– Complete Documentation

View Full Documentation β†’

Our comprehensive documentation includes:

Professional Support

For enterprise implementation, custom development, or technical support: Team Outsiders - Professional WordPress & HubSpot Integration Services

πŸ“„ License & Credits

License: GPL-3.0+
Author: Team Outsiders
Based On: HubSpot Gateway for WooCommerce by Jerome Cloutier (Globalia)
Version: 1.0.0


πŸ”„ Changelog

Version 1.0.1 - Simplified Checkout Fields

  • ✨ New: Simplified checkout fields implementation option
  • ✨ New: Single healthcare provider referral question (class-checkout-fields-simple.php)
  • ✨ New: Easy switching between full and simplified checkout via configuration constant
  • ✨ New: CHECKOUT_FIELDS.md documentation for implementation switching
  • πŸ”§ Enhanced: Dynamic class loading system supports multiple checkout implementations
  • πŸ”§ Enhanced: Backward compatibility maintained for existing field mappings
  • πŸ“– Updated: README with checkout configuration documentation

Version 1.0.0 - Complete Rewrite

  • ✨ New: Advanced abandoned cart tracking with conversion prevention
  • ✨ New: Device and serial number management system
  • ✨ New: External system integration via REST API
  • ✨ New: ShipHero webhook monitoring with automatic device creation
  • ✨ New: Non-destructive integration hooks for existing systems
  • ✨ New: Comprehensive testing framework
  • ✨ New: Background sync processing
  • πŸ”§ Enhanced: Modern admin interface with real-time connection testing
  • πŸ”§ Enhanced: Flexible field mapping system
  • πŸ”§ Enhanced: Error handling and debug logging
  • πŸ”§ Enhanced: Security with nonce verification and data sanitization
  • πŸ›‘οΈ Fixed: Deal duplication issues from original plugin
  • πŸ›‘οΈ Fixed: Session persistence and cart hash consistency
  • πŸ›‘οΈ Fixed: Rate limiting to prevent API throttling

This version represents a complete architectural rewrite focused on reliability, extensibility, and enterprise-grade functionality.