# Advanced Matching

Advanced matching allows TikTok to match events to users more accurately by sending hashed user identifiers.

### Requirements

1. **Enable Advanced Matching:**
   ```html
   <script>
       window.handl_advanced_matching = 1;
       window.handl_tiktok_pixel_id = 'YOUR_PIXEL_ID';
   </script>
   ```

2. **Collect User Data:**
   The HandL library automatically collects user data from forms when advanced matching is enabled. It looks for:
   - Email fields (email, email_address, e-mail, mail)
   - Phone fields (phone, telephone, mobile, cell, phone-number, tel)

### How It Works

1. **Data Collection:**
   - When users fill out forms, HandL automatically captures email and phone number
   - Data is stored in `localStorage` with keys: `em` (email) and `ph` (phone)

2. **Automatic Hashing:**
   - All identifiers are automatically hashed using SHA-256 before sending to TikTok
   - Email is normalized (lowercase, trimmed)
   - Phone numbers are cleaned (digits only)

3. **External ID:**
   - Uses the `first_handlID` cookie as `external_id`
   - This is automatically generated on first visit

4. **Automatic Identification:**
   - When TikTok Pixel loads and advanced matching is enabled, `ttq.identify()` is called automatically
   - Identification is updated whenever new email/phone data is saved

### Manual Data Collection

You can manually save user data for advanced matching:

```javascript
HandL.saveAdvancedMatchingParams({
    em: 'user@example.com',  // Email (will be hashed)
    ph: '+1-555-123-4567'     // Phone (will be cleaned and hashed)
});
```

**Note:** The data will be automatically hashed when sent to TikTok.

### Advanced Matching Parameters

TikTok supports the following identifiers (all SHA-256 hashed):

| Parameter | Description | Source |
|-----------|-------------|--------|
| `email` | User's email address | `localStorage.getItem('em')` |
| `phone_number` | User's phone number | `localStorage.getItem('ph')` |
| `external_id` | Unique identifier | `Cookies.get('first_handlID')` |

### Verification

To verify advanced matching is working:

1. Open browser DevTools (F12)
2. Go to **Console** tab
3. Look for: `UTMSimple: TikTok advanced matching parameters sent`
4. Check **Network** tab for requests containing hashed identifiers