# MarkTag for WooCommerce

A lightweight, reliable tracking plugin that captures WooCommerce events and sends them to the MarkTag analytics platform with the same event schema as your Shopify pixel.

## Features

- **Hybrid Architecture**: JavaScript for view events, PHP for action events (maximum reliability)
- **Event Tracking**: ViewItem, ViewCart, AddToCart, RemoveFromCart, BeginCheckout, Purchase
- **Tag ID Support**: Unique identifier for each user/store sent with every event
- **Settings Page**: Easy configuration via WordPress Admin (Settings → MarkTag)
- **Session Management**: UUID-based session tracking with sessionStorage
- **Cookie Management**: First-party `muid` cookie with 1-year expiry
- **Marketing Attribution**: Captures Facebook Pixel (`fbp`, `fbc`), TikTok (`ttclid`, `ttp`), Google Analytics (`_ga`, `_gid`)
- **Phone Validation**: International phone number formatting with E.164 standard
- **Email/Phone Persistence**: Stores customer data in localStorage for cross-session tracking
- **WooCommerce HPOS Compatible**: Fully compatible with High-Performance Order Storage
- **Works with All Themes**: Compatible with classic themes, block themes, and WooCommerce Blocks

## Installation

### Option 1: Upload via WordPress Admin (Recommended)

1. Download the latest release zip file or build it yourself:
   ```bash
   ./build.sh
   ```
2. Go to WordPress Admin → Plugins → Add New → Upload Plugin
3. Choose the zip file from `dist/marktag-for-woocommerce-{version}.zip`
4. Click "Install Now" and then "Activate"

### Option 2: Manual Installation

Copy the `marktag-for-woocommerce` folder to your WordPress plugins directory:

```bash
cp -r marktag-for-woocommerce /path/to/wordpress/wp-content/plugins/
```

For Docker setup:
```bash
cp -r marktag-for-woocommerce ./wp-content/plugins/
```

Then activate via WordPress Admin → Plugins.

## Development with Docker (HTTPS Enabled)

This repository includes a Docker Compose setup with **HTTPS support** for WooCommerce development. HTTPS is required for WooCommerce REST API authentication.

### Quick Start

1. **Generate SSL certificates** (first time only):
   ```bash
   cd docker
   ./generate-ssl.sh
   cd ..
   ```

2. **Start WordPress with HTTPS**:
   ```bash
   docker-compose up -d
   ```

3. **Access WordPress**:
   - HTTPS: https://localhost (recommended)
   - HTTP: http://localhost (redirects to HTTPS)

4. **Accept the security warning** in your browser (self-signed certificate for local development)

5. **Complete WordPress setup** and install WooCommerce

📚 **Full documentation**: See [`docker/README.md`](docker/README.md) for detailed setup instructions, troubleshooting, and WooCommerce API configuration.

### Why HTTPS?

WooCommerce REST API requires HTTPS for authentication. Without it, API requests return "Unauthorized" errors. This Docker setup uses nginx as a reverse proxy with SSL certificates to enable HTTPS on localhost.

## Configuration

### 1. Configure Tag ID (Required)

1. Go to **WordPress Admin → Settings → MarkTag**
2. Enter your **Tag ID** (UUID format, e.g., `b3a63bb6-3018-42b2-a318-73ba557ec5e9`)
3. Optionally customize the **Webhook URL** (default: `https://mtag.markopolo.ai/mark`)
4. Click **Save Settings**

### 2. Verify Tracking

1. Open your WooCommerce store in a browser
2. Open DevTools → Network tab
3. Browse products, add to cart, checkout
4. Look for POST requests to your webhook URL
5. Verify `tag_id` is included in the payload

## Architecture

This plugin uses a **hybrid approach** for maximum reliability:

### JavaScript Layer (Client-Side)
- **View Events**: ViewItem, ViewCart, BeginCheckout
- **Cookie Management**: Creates and manages `muid` cookie
- **Session Tracking**: Manages session ID in sessionStorage
- **Marketing Pixels**: Captures Facebook, TikTok, Google Analytics cookies
- **Browser Context**: Viewport, screen size, user agent, referrer

### PHP Layer (Server-Side)
- **Action Events**: AddToCart, RemoveFromCart, Purchase
- **WooCommerce Hooks**: Uses native `woocommerce_add_to_cart`, `woocommerce_cart_item_removed`, `woocommerce_new_order`
- **Direct Webhook Calls**: Sends events directly to MarkTag server via `wp_remote_post`
- **No CORS Issues**: All action events bypass browser restrictions

**Why Hybrid?**
- View events happen without server actions (JavaScript required)
- Action events need WooCommerce hooks (PHP required)
- Cookie/session management needs browser access (JavaScript required)
- Maximum reliability across all WooCommerce setups (blocks, classic, AJAX)

## Building the Plugin

This plugin uses plain JavaScript (no build tools required). To create a distribution zip:

```bash
# Make build script executable (first time only)
chmod +x build.sh

# Build the plugin
./build.sh
```

This creates `dist/marktag-for-woocommerce-{version}.zip` ready for WordPress upload.

### Project Structure

```
marktag-for-woocommerce/
├── marktag-for-woocommerce.php  # Main plugin file (PHP hooks + settings)
├── assets/
│   └── js/
│       └── marktag-woo-tracking.js   # Client-side tracking (view events + cookies)
├── build.sh                           # Build script for creating zip
├── readme.txt                         # WordPress.org plugin readme
└── README.md                          # This file
```

## Event Schema

All events follow the MarkTag schema, matching your Shopify pixel implementation:

### Common Attributes

```javascript
{
  event: "EventType",
  event_source: "woocommerce_pixel",
  isWooCommerce: true,
  pageUrl: "https://...",
  sessionId: "uuid-v4",
  muid: "uuid-v4",
  external_id: "uuid-v4",
  tag_id: "b3a63bb6-3018-42b2-a318-73ba557ec5e9",  // Your unique Tag ID
  email: "customer@example.com",
  phone: "+1234567890",
  fbp: "_fbp_cookie_value",
  fbc: "_fbc_cookie_value",
  ttclid: "tiktok_click_id",
  ttp: "tiktok_pixel_value",
  referrer: "https://...",
  user_agent: "Mozilla/...",
  viewport: { height: 1080, width: 1920 },
  screen: { height: 1080, width: 1920 },
  shop: "Your Store Name",
  all_cookies: { /* all captured cookies */ }
}
```

### Event-Specific Data

**ViewItem**
```javascript
{
  event: "ViewItem",
  content_type: "product",
  products: [{ id, name, price, quantity, currency, category, sku }],
  value: 99.99,
  currency: "USD"
}
```

**AddToCart / RemoveFromCart**
```javascript
{
  event: "AddToCart",
  products: [{ id, variant_id, name, quantity, price, currency }],
  value: 99.99,
  currency: "USD"
}
```

**BeginCheckout**
```javascript
{
  event: "BeginCheckout",
  products: [...],
  value: 199.99,
  currency: "USD",
  tax: 15.00,
  shipping_cost: 10.00
}
```

**Purchase**
```javascript
{
  event: "Purchase",
  products: [...],
  value: 224.99,
  currency: "USD",
  transaction_id: "12345",
  tax: 15.00,
  shipping_cost: 10.00,
  email: "customer@example.com",
  phone: "+1234567890",
  shipping_address: {
    first_name: "John",
    last_name: "Doe",
    address1: "123 Main St",
    city: "New York",
    province: "NY",
    country: "US",
    zip: "10001"
  }
}
```

## Phone Number Formatting

The plugin includes advanced phone validation matching your Shopify pixel:

- Detects country codes (1-3 digits)
- Maps region codes (US → 1, IN → 91, etc.)
- Removes trunk prefixes (leading 0)
- Validates minimum digit requirements
- Formats to E.164 standard (+CountryCodeLocalNumber)

Example transformations:
- `01234567890` (IN) → `+911234567890`
- `+88001316314566` → `+8801316314566` (removes trunk 0)
- `(555) 123-4567` (US) → `+15551234567`

## Cookie Management

### First-Party Cookie: `muid`
- 1-year expiry
- UUID v4 format
- Used as `external_id` in events

### Marketing Cookies Captured
- Facebook: `_fbp`, `_fbc`
- TikTok: `ttclid`, `ttp`
- Google Analytics: `_ga`, `_gid`, `_gat`, `_gcl_au`
- Microsoft: `_uetsid`

## WooCommerce Integration

### PHP Hooks Used

- `wp_enqueue_scripts` - Enqueues tracking script
- `wp_footer` - Injects page-specific data
- `woocommerce_thankyou` - Captures purchase events

### JavaScript Events

- `added_to_cart` - WooCommerce AJAX add to cart
- `removed_from_cart` - WooCommerce cart item removal
- Page load detection for ViewItem, ViewCart, BeginCheckout

## Troubleshooting

### Events Not Sending

1. Check browser console for errors
2. Verify webhook URL is correct
3. Check network tab for failed requests
4. Ensure WooCommerce is active

### Build Errors

```bash
# Clean and rebuild
rm -rf node_modules package-lock.json
npm install
npm run build
```

### TypeScript Errors

The `@types/node` error in tsconfig.json is expected before running `npm install`.

## Requirements

- WordPress 5.0+
- PHP 7.4+
- WooCommerce 5.0+

## WordPress.org Plugin Directory Submission

To submit this plugin to the WordPress.org plugin directory:

1. **Create an account** at https://wordpress.org/plugins/developers/
2. **Review guidelines** at https://developer.wordpress.org/plugins/wordpress-org/
3. **Prepare assets** (see `.wordpress-org/` folder):
   - Plugin icon (256x256 and 128x128)
   - Plugin banner (1544x500 and 772x250)
   - Screenshots (1200x900 recommended)
4. **Submit plugin** via https://wordpress.org/plugins/developers/add/
5. **Wait for review** (typically 2-14 days)

See `CONTRIBUTING.md` for detailed submission guidelines.

## Development

To modify the JavaScript tracking code:

1. Edit `assets/js/marktag-woo-tracking.js` directly (no build process needed)
2. Test in your WooCommerce store
3. Check browser console and network tab for errors
4. Run `./build.sh` to create distribution zip

## License

GPL v2 or later

## Support

For issues or questions:
- GitHub Issues: [Create an issue](https://github.com/markopolo-inc/woocommerce-tracking-plugin/issues)
- Email: support@markopolo.ai
- Documentation: https://docs.markopolo.ai
