> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Usercentrics

> Integre el CMP de Usercentrics con Kameleoon para gestionar automáticamente el consentimiento del visitante y ejecutar tests A/B en su banner de consentimiento de Usercentrics.

La Consent Management Platform (CMP) de Usercentrics proporciona toda la información requerida y actualizada sobre la privacidad de los datos.

Con la integración de Usercentrics, Kameleoon se conecta automáticamente a Usercentrics, lee la política de consentimiento y la aplica al mostrar experimentos y personalizaciones en su sitio web.

La integración ofrece las siguientes ventajas:

* Gestiona automáticamente el consentimiento del usuario a través del CMP de Usercentrics sin necesidad de configuración adicional.
* Garantiza una gestión coherente del consentimiento para un cumplimiento fluido.
* Tranquiliza a los usuarios al saber que Kameleoon trata sus datos de forma conforme.

## Añadir Kameleoon como Data Processing Service en Usercentrics

Para añadir Kameleoon como Data Processing Service, complete los siguientes pasos:

1. En la interfaz de administración de Usercentrics, haga clic en **Service Settings**.
2. Haga clic en **Add DPS via Database** > **Kameleoon**.

<Frame>
  ![](https://storage.googleapis.com/kameleoon-storage-documentation/user-manual/images/integrations/as-a-source/cmp/usercentrics/Capture-decran-2023-07-20-a-14.05.13.png)
</Frame>

3. Seleccione su categoría en el menú desplegable **Category**.

Kameleoon proporciona los siguientes IDs de Template:

* Kameleoon AB Testing & Personalization / Template ID: H1yDxp7JN
* Kameleoon Only AB Testing Module / Template ID: 9FYjH37-J
* Kameleoon Only Personalization Module / Template ID: 2lh8-reEz

<Frame>
  ![](https://storage.googleapis.com/kameleoon-storage-documentation/user-manual/images/integrations/as-a-source/cmp/usercentrics/Capture-decran-2023-07-20-a-14.06.43-1920x743.png)
</Frame>

## Configurar IAB TCF en Usercentrics

Para habilitar IAB TCF 2.3 en Usercentrics y Kameleoon, complete los siguientes pasos:

1. Configure Kameleoon como vendor (ID: 820) en Usercentrics.
2. En la interfaz de administración de Usercentrics, vaya a **Service Settings**.
3. Establezca la versión del CMP en **Version 2**.

<Frame>
  ![](https://storage.googleapis.com/kameleoon-storage-documentation/user-manual/images/integrations/as-a-source/cmp/usercentrics/Capture-decran-2023-07-20-a-15.18.10.png)
</Frame>

4. Haga clic en **Configuration**.
5. Habilite **Transparency & Consent Framework 2.3 (TCF)**.

<Frame>
  ![](https://storage.googleapis.com/kameleoon-storage-documentation/user-manual/images/integrations/as-a-source/cmp/usercentrics/image-33.png)
</Frame>

6. [Habilite la integración de IAB TCF en Kameleoon](./iab-transparency-and-consent-framework).

## Integración personalizada del consentimiento legal de Kameleoon

Si no puede habilitar TCF 2.3 en Usercentrics, puede utilizar una configuración con script personalizado.

<Warning>
  No bloquee Kameleoon cuando el estado del consentimiento sea desconocido (en la primera visita de un visitante). Bloquear Kameleoon con un estado de consentimiento desconocido hace que la configuración con script personalizado sea ineficaz.
</Warning>

<Note>
  El script personalizado muestra a los usuarios las campañas cuando el estado del consentimiento es desconocido, sin realizar seguimiento. También puede mostrar cambios de A/B testing en las páginas de entrada de su proyecto.
</Note>

1. En Kameleoon, [defina su política de gestión de consentimientos](../../../project-management/consent-management-policy#cómo-definir-su-política-de-gestión-del-consentimiento) y elija **Consent required**.
2. Integre las siguientes funciones de Kameleoon:
   * `enableLegalConsent`
   * `disableLegalConsent`

<Note>
  Para obtener más información sobre el consentimiento legal en Kameleoon, consulte la [referencia de la API de consentimiento legal](../../../../developer-docs/apis/activation-api-js/api-reference/api-reference#enablelegalconsent). Para obtener más información sobre los estados y modos de consentimiento, consulte la [documentación de gestión del consentimiento](../../../../developer-docs/privacy-and-compliance/consent-management).
</Note>

Puede añadir un script personalizado directamente en una página, en Google Tag Manager o en el **Global custom script** dentro de la aplicación de Kameleoon.

Para utilizar un script personalizado en el **Global custom script**, siga estos pasos:

1. Vaya al menú **Projects**.
2. Haga clic en **Configuration** en la tarjeta de su sitio o aplicación móvil.

<Frame>
  ![](https://storage.googleapis.com/kameleoon-storage-documentation/user-manual/images/integrations/as-a-source/cmp/usercentrics/Capture-decran-2021-05-10-a-14.44.41-1.png)
</Frame>

3. Despliegue la sección **General**.
4. Copie y pegue uno de los siguientes bloques de código, según la Template de Kameleoon que haya elegido.

<Tabs>
  <Tab title="Web CMP v2">
    ### Ejemplo de script personalizado si A/B testing y Personalización están en el mismo servicio

    ```javascript theme={null}
    Kameleoon AB Testing&Personalization / Template ID: H1yDxp7JN

    function setConsentStatus(type, status, action) {
            if (status) {
                window.kameleoonQueue.push(function() {
                    Kameleoon.API.Core.enableLegalConsent(type);
                    console.log('enableLegalConsent ' + type)
                });
            } else if (!status) {
                window.kameleoonQueue.push(function() {
                    Kameleoon.API.Core.disableLegalConsent(type);
                    console.log('disableLegalConsent ' + type)
                });
            }
        }

        function initKameleoonLegalConsent(type) {
            window.kameleoonQueue = window.kameleoonQueue || [];
            window.kameleoonQueue.push(function() {
                Kameleoon.API.Core.runWhenConditionTrue(() => typeof UC_UI !== 'undefined' 
                && UC_UI.isInitialized() === true
                && window.localStorage.getItem('uc_user_interaction') === 'true', () => {
                    const abtesting = UC_UI.getServicesBaseInfo().filter((service) => service && service.id === 'H1yDxp7JN');
                    if (abtesting.length > 0) {
                        setConsentStatus('BOTH', abtesting[0].consent.status);
                    }
                }, 200);
            });
        }
        initKameleoonLegalConsent();
    ```

    ### Ejemplo de script personalizado si A/B testing y Personalización están en servicios distintos

    * Kameleoon Only AB Testing Module = Template ID: 9FYjH37-J
    * Kameleoon Only Personalization Module = Template ID: 2lh8-reEz

    ```javascript theme={null}
    function setConsentStatus(type, status, action) {
            if (status) {
                window.kameleoonQueue.push(function() {
                    Kameleoon.API.Core.enableLegalConsent(type);
                    console.log('enableLegalConsent ' + type)
                });
            } else if (!status) {
                window.kameleoonQueue.push(function() {
                    Kameleoon.API.Core.disableLegalConsent(type);
                    console.log('disableLegalConsent ' + type)
                });
            }
        }

        function initKameleoonLegalConsent(type) {
            window.kameleoonQueue = window.kameleoonQueue || [];
            window.kameleoonQueue.push(function() {
                Kameleoon.API.Core.runWhenConditionTrue(() => typeof UC_UI !== 'undefined' 
                && UC_UI.isInitialized() === true
                && window.localStorage.getItem('uc_user_interaction') === 'true', () => {
                    const abtesting = UC_UI.getServicesBaseInfo().filter((service) => service && service.id === '9FYjH37-J');
                    if (abtesting.length > 0) {
                        setConsentStatus('AB_TESTING', abtesting[0].consent.status);
                    }
                    const perso = UC_UI.getServicesBaseInfo().filter((service) => service && service.id === '2lh8-reEz');
                    if (perso.length > 0) {
                        setConsentStatus('PERSONALIZATION',perso[0].consent.status);
                    }
                }, 200);
            });
        }
        initKameleoonLegalConsent();
    ```
  </Tab>

  <Tab title="Web CMP v3">
    <Tabs>
      <Tab title="Both (H1yDxp7JN) – Global script">
        ```javascript theme={null}
        const UcConsent = () => {
            const serviceID = 'H1yDxp7JN';

            function setConsentStatus(type, status) {
                if (status === true) {
                    Kameleoon.API.Core.enableLegalConsent(type);
                } else if (status === false) {
                    Kameleoon.API.Core.disableLegalConsent(type);
                }
            }

            function checkConsentStatus() {
                if (window.__ucCmp?.getConsentDetails === undefined) return;
                window.__ucCmp.getConsentDetails().then((details) => {
                    const consent = details.services?.[serviceID]?.consent?.given;
                    if (consent === undefined) return;
                    setConsentStatus('BOTH', consent);
                });
            }

            const checkConsentInteraction = (event) => {
                if (window.__ucCmp?.isConsentRequired === undefined) return;
                window.__ucCmp.isConsentRequired().then((isRequired) => {
                    if (isRequired) return;
                    const consentStatus = event?.detail?.consent?.status;
                    if (consentStatus === 'ALL_ACCEPTED') {
                        setConsentStatus('BOTH', true);
                    } else if (consentStatus === 'ALL_DENIED') {
                        setConsentStatus('BOTH', false);
                    } else {
                        checkConsentStatus();
                    }
                });
            };

            checkConsentInteraction();

            Kameleoon.API.Utils.addEventListener(window, 'UC_CONSENT', checkConsentInteraction);
        };

        UcConsent();
        ```
      </Tab>

      <Tab title="Both (H1yDxp7JN) – kameleoonQueue">
        ```javascript theme={null}
        const UcConsent = () => {
            const serviceID = 'H1yDxp7JN';

            function setConsentStatus(type, status) {
                if (status === true) {
                    Kameleoon.API.Core.enableLegalConsent(type);
                } else if (status === false) {
                    Kameleoon.API.Core.disableLegalConsent(type);
                }
            }

            function checkConsentStatus() {
                if (window.__ucCmp?.getConsentDetails === undefined) return;
                window.__ucCmp.getConsentDetails().then((details) => {
                    const consent = details.services?.[serviceID]?.consent?.given;
                    if (consent === undefined) return;
                    setConsentStatus('BOTH', consent);
                });
            }

            const checkConsentInteraction = (event) => {
                if (window.__ucCmp?.isConsentRequired === undefined) return;
                window.__ucCmp.isConsentRequired().then((isRequired) => {
                    if (isRequired) return;
                    const consentStatus = event?.detail?.consent?.status;
                    if (consentStatus === 'ALL_ACCEPTED') {
                        setConsentStatus('BOTH', true);
                    } else if (consentStatus === 'ALL_DENIED') {
                        setConsentStatus('BOTH', false);
                    } else {
                        checkConsentStatus();
                    }
                });
            };

            checkConsentInteraction();

            Kameleoon.API.Utils.addEventListener(window, 'UC_CONSENT', checkConsentInteraction);
        };

        window.kameleoonQueue = window.kameleoonQueue || [];
        window.kameleoonQueue.push(UcConsent);
        ```
      </Tab>

      <Tab title="A/B testing + Personalization – Global script">
        ```javascript theme={null}
        function setConsentStatus(type, status) {
          if (status === true) {
            Kameleoon.API.Core.enableLegalConsent(type);
          } else if (status === false) {
            Kameleoon.API.Core.disableLegalConsent(type);
          }
        }

        function initKameleoonLegalConsent() {
          Kameleoon.API.Core.runWhenConditionTrue(
            () => typeof window.UC_UI !== 'undefined' && window.UC_UI.isInitialized() === true,
            () => {
              window.UC_UI.getServicesBaseInfo()
                .then((services) => {
                  const abtestingService = services.find((service) => service?.id === '9FYjH37-J');
                  if (abtestingService?.consent && typeof abtestingService.consent.status === 'boolean') {
                    setConsentStatus('AB_TESTING', abtestingService.consent.status);
                  }

                  const persoService = services.find((service) => service?.id === '2lh8-reEz');
                  if (persoService?.consent && typeof persoService.consent.status === 'boolean') {
                    setConsentStatus('PERSONALIZATION', persoService.consent.status);
                  }
                })
                .catch(console.error);
            },
            200
          );
        }

        initKameleoonLegalConsent();
        ```
      </Tab>

      <Tab title="A/B testing + Personalization – kameleoonQueue">
        ```javascript theme={null}
        window.kameleoonQueue = window.kameleoonQueue || [];
        window.kameleoonQueue.push(() => {

          function setConsentStatus(type, status) {
            if (status === true) {
              Kameleoon.API.Core.enableLegalConsent(type);
            } else if (status === false) {
              Kameleoon.API.Core.disableLegalConsent(type);
            }
          }

          function initKameleoonLegalConsent() {
            Kameleoon.API.Core.runWhenConditionTrue(
              () => typeof window.UC_UI !== 'undefined' && window.UC_UI.isInitialized() === true,
              () => {
                window.UC_UI.getServicesBaseInfo()
                  .then((services) => {
                    const abtestingService = services.find((service) => service?.id === '9FYjH37-J');
                    if (abtestingService?.consent && typeof abtestingService.consent.status === 'boolean') {
                      setConsentStatus('AB_TESTING', abtestingService.consent.status);
                    }

                    const persoService = services.find((service) => service?.id === '2lh8-reEz');
                    if (persoService?.consent && typeof persoService.consent.status === 'boolean') {
                      setConsentStatus('PERSONALIZATION', persoService.consent.status);
                    }
                  })
                  .catch(console.error);
              },
              200
            );
          }

          initKameleoonLegalConsent();
        });
        ```
      </Tab>
    </Tabs>
  </Tab>
</Tabs>

Si tiene alguna pregunta, no dude en ponerse en contacto con su Customer Success Manager de Kameleoon.

## Ejecutar un test A/B en el banner de consentimiento de Usercentrics

<Note>
  Ejecute solo un experimento de consentimiento por sitio.
</Note>

Para ejecutar un test A/B en el banner de consentimiento de Usercentrics, primero cree un objetivo:

1. Haga clic en **Configure** > **Goals** > **New goal**.
2. En **Website Selection**, elija el sitio web que definió cuando creó su cuenta.
3. Seleccione **Custom Goal** en **Type**.
   * Usercentrics admite varios eventos personalizados para objetivos personalizados. Para ver la lista completa de eventos disponibles, consulte los [eventos de UI disponibles en la documentación de Usercentrics](https://docs.usercentrics.com/#/ab-test?id=available-ui-events).
4. Haga clic en **Next**.
5. Introduzca un nombre para su objetivo en el campo **Name your goal**.
6. En el campo **Describe your goal**, introduzca `Kameleoon.API.Goals.processConversion` seguido del ID único.
   * Puede encontrar el ID en el pop-in **New goal** al final del texto de la función.

<Frame>
  ![](https://docs.usercentrics.com/assets/ab-testing/kam6.png)
</Frame>

Después de crear el objetivo, cree un experimento:

1. Abra el [panel de experimentos](https://app.kameleoon.com/experiments/dashboard).
2. Haga clic en **New Experiment**. Se abrirá un pop-in preguntando qué tipo de experimento quiere crear.
3. Haga clic en **In the code editor** > **JS/CSS**.
4. Introduzca el **Name**, **Website** y **URL of the page where you want to launch your experiment**.
5. Haga clic en **Validate**. Se abrirá el editor de código.

<Frame>
  ![](https://docs.usercentrics.com/assets/ab-testing/kam8.png)
</Frame>

6. Haga clic en **Experiment** (encima de **Variations** en el menú de la izquierda) y, a continuación, haga clic en **Test specific code** en el menú de la derecha.
7. Añada el siguiente código:

```javascript theme={null}
window.UC_AB_VARIANT = "variant0";
 window.addEventListener('UC_UI_CMP_EVENT', function (data) {
      console.log("TEST: source =>", data.detail.source);
      console.log("TEST: type =>", data.detail.type);
      console.log("TEST: Variant =>", data.detail.abTestVariant);
      //These are our custom events for each basic action
      //in our Consent Management Platform
      if (data.detail.type === "CMP_SHOWN") Kameleoon.API.Goals.processConversion(Your Unique ID);
      if (data.detail.type === "ACCEPT_ALL") Kameleoon.API.Goals.processConversion(Your Unique ID);
      if (data.detail.type === "DENY_ALL") Kameleoon.API.Goals.processConversion(Your Unique ID);
      if (data.detail.type === "SAVE") Kameleoon.API.Goals.processConversion(Your Unique ID);
      if (data.detail.type === "MORE_INFORMATION_LINK") Kameleoon.API.Goals.processConversion(Your Unique ID);
      if (data.detail.type === "IMPRINT_LINK") Kameleoon.API.Goals.processConversion(Your Unique ID);
      if (data.detail.type === "PRIVACY_POLICY_LINK") Kameleoon.API.Goals.processConversion(Your Unique ID);
  });
```

* `variant0` es la variante por defecto, vacía. No realiza ningún cambio en la consent management platform. Si su variante por defecto tiene otro nombre, actualice `window.UC_AB_VARIANT` en consecuencia.
* El event listener se activa cada vez que se produce un evento personalizado. Para ver la lista completa de eventos personalizados para A/B testing, consulte los [eventos de UI disponibles en la documentación de Usercentrics](https://docs.usercentrics.com/#/ab-test?id=available-ui-events).
* Las tres instrucciones `console.log` muestran información sobre el evento. Por ejemplo, al hacer seguimiento de `ACCEPT_ALL` se generan estos logs:

```
 TEST: source => FIRST_LAYER
 TEST: type => ACCEPT_ALL
 TEST: Variant => variant1
```

Puede añadir más objetivos al experimento.

Para añadir un objetivo, inserte el siguiente código después de la última instrucción `if`:

`if (data.detail.type === "Consent Management Platform event here") Kameleoon.API.Goals.processConversion(goalID)`

8. Vuelva a la pestaña **Variations**.

9. En **Variation 1**, añada el siguiente código:

   `window.UC_AB_VARIANT = "variant1";`

10. Si dio otro nombre a su variante, sustituya `variant1` en consecuencia.

11. En la pestaña **Finalize**, seleccione su distribución de tráfico, segmentación, seguimiento y objetivos.
    * Añada el objetivo que ha creado. Puede buscar por el ID único del objetivo. Si la búsqueda no devuelve resultados, pruebe a introducir solo los primeros dígitos del ID del objetivo.

12. Haga clic en **Publish** para finalizar la configuración del experimento.

Para ver un tutorial sobre el A/B testing interno de Usercentrics, consulte la [guía de A/B testing de Usercentrics](https://docs.usercentrics.com/#/ab-test?id=ab-testing-with-third-party-tool).
