# OneTrust

Connect Shoplift with OneTrust Cookie Consent to ensure A/B testing respects visitor privacy preferences managed through OneTrust.

#### Overview

OneTrust is a leading privacy management platform that helps businesses comply with GDPR, CCPA, and other privacy regulations. This guide shows how to integrate OneTrust's consent signals with Shoplift's analytics tracking.

#### Prerequisites

* OneTrust Cookie Consent implemented on your Shopify store
* OneTrust script loaded before Shoplift
* Performance/Analytics cookies category configured in OneTrust

#### Implementation

**Basic Integration**

Add this code after your OneTrust script but before any analytics tracking:

```javascript
// OneTrust + Shoplift Consent Integration
(function() {
  // Function to sync OneTrust consent with Shoplift
  function syncOneTrustWithShoplift() {
    if (!window.OnetrustActiveGroups) {
      // OneTrust not ready yet
      setTimeout(syncOneTrustWithShoplift, 100);
      return;
    }
    
    // Check if performance/analytics cookies are accepted
    // C0002 is typically Performance Cookies - verify your OneTrust configuration
    const hasAnalyticsConsent = window.OnetrustActiveGroups.includes('C0002');
    
    // Update Shoplift consent
    if (window.shoplift && window.shoplift.setAnalyticsConsent) {
      window.shoplift.setAnalyticsConsent(hasAnalyticsConsent)
        .then(() => {
          console.log('Shoplift consent synchronized with OneTrust:', hasAnalyticsConsent);
        })
        .catch(error => {
          console.error('Failed to update Shoplift consent:', error);
        });
    } else {
      // Retry if Shoplift isn't ready
      setTimeout(syncOneTrustWithShoplift, 100);
    }
  }
  
  // Initial sync on page load
  syncOneTrustWithShoplift();
  
  // Listen for consent changes
  window.OneTrust.OnConsentChanged(function() {
    syncOneTrustWithShoplift();
  });
})();
```

#### Advanced Integration with Cookie Categories

OneTrust uses specific category codes. Map these to Shoplift's consent:

```javascript
// Advanced OneTrust + Shoplift Integration
const OneTrustShopliftBridge = {
  // Map your OneTrust categories (check your OneTrust dashboard)
  CATEGORY_MAPPING: {
    'C0001': 'strictly_necessary',  // Always active
    'C0002': 'performance',          // Analytics/Statistics
    'C0003': 'functional',           // Functionality
    'C0004': 'targeting'             // Marketing/Advertising
  },
  
  // Categories that enable Shoplift analytics
  ANALYTICS_CATEGORIES: ['C0002'],  // Performance/Analytics
  
  initialize() {
    // Wait for OneTrust to be ready
    if (window.OneTrust && window.OneTrust.IsAlertBoxClosed()) {
      this.syncConsent();
      this.setupListeners();
    } else {
      setTimeout(() => this.initialize(), 100);
    }
  },
  
  syncConsent() {
    const hasConsent = this.checkAnalyticsConsent();
    this.updateShopliftConsent(hasConsent);
  },
  
  checkAnalyticsConsent() {
    if (!window.OnetrustActiveGroups) return false;
    
    // Check if any analytics categories are active
    return this.ANALYTICS_CATEGORIES.some(category => 
      window.OnetrustActiveGroups.includes(category)
    );
  },
  
  async updateShopliftConsent(consent) {
    // Wait for Shoplift to be available
    let attempts = 0;
    while (!window.shoplift && attempts < 50) {
      await new Promise(resolve => setTimeout(resolve, 100));
      attempts++;
    }
    
    if (window.shoplift && window.shoplift.setAnalyticsConsent) {
      try {
        await window.shoplift.setAnalyticsConsent(consent);
        console.log('✅ Shoplift consent updated via OneTrust:', consent);
        
        // Track consent event for debugging
        if (window.shoplift.getVisitorData) {
          const visitorData = window.shoplift.getVisitorData();
          console.log('Visitor test assignments:', visitorData.visitorTests);
        }
      } catch (error) {
        console.error('❌ Failed to update Shoplift consent:', error);
      }
    }
  },
  
  setupListeners() {
    // Listen for consent changes
    window.OneTrust.OnConsentChanged(() => {
      console.log('OneTrust consent changed, updating Shoplift...');
      this.syncConsent();
    });
    
    // Also listen for the banner close event
    window.OptanonWrapper = window.OptanonWrapper || function() {};
    const originalWrapper = window.OptanonWrapper;
    window.OptanonWrapper = function() {
      originalWrapper();
      OneTrustShopliftBridge.syncConsent();
    };
  },
  
  // Utility method to check current status
  getConsentStatus() {
    return {
      oneTrustReady: !!window.OneTrust,
      activeGroups: window.OnetrustActiveGroups || 'none',
      analyticsConsent: this.checkAnalyticsConsent(),
      shopliftReady: !!window.shoplift
    };
  }
};

// Initialize on page load
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    OneTrustShopliftBridge.initialize();
  });
} else {
  OneTrustShopliftBridge.initialize();
}

// Expose for debugging
window.OneTrustShopliftBridge = OneTrustShopliftBridge;
```

#### OneTrust Configuration

**Finding Your Category IDs**

1. Log in to your OneTrust dashboard
2. Navigate to **Cookie Consent > Categorizations**
3. Find your Performance/Analytics category
4. Note the category ID (e.g., C0002)

#### Testing Your Integration

**Debug Console Commands**

Test your integration using these console commands:

```javascript
// Check integration status
OneTrustShopliftBridge.getConsentStatus();

// Manually test consent states
// Grant consent
window.shoplift.setAnalyticsConsent(true);

// Revoke consent
window.shoplift.setAnalyticsConsent(false);

// Check current OneTrust groups
console.log('Active OneTrust groups:', window.OnetrustActiveGroups);

// Check Shoplift visitor data
console.log('Shoplift visitor:', window.shoplift.getVisitorData());
```

**Testing Consent Scenarios**

1. **First-time visitor (no consent)**
   * Clear cookies and local storage
   * Verify banner appears
   * Confirm no analytics tracking before consent
2. **Accepting analytics cookies**
   * Accept performance cookies in OneTrust banner
   * Verify Shoplift receives consent signal
   * Check that test data is being tracked
3. **Rejecting analytics cookies**
   * Reject performance cookies
   * Verify test variants still display
   * Confirm no analytics data is sent
4. **Changing consent mid-session**
   * Use OneTrust preference center to toggle consent
   * Verify Shoplift updates accordingly


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.shoplift.ai/api-reference/guides/consent-management-integrations/onetrust.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
