Guía del desarrollador
This guide is designed to help you integrate our SDK into your application code.Primeros pasos
Primero debe instalar nuestro SDK. Una vez descomprimido, verá dos directorios: kameleoon/ y job/.Instalación del cliente PHP (Composer package)
El paquete de instalación está disponible en Packagist. Puede instalar el SDK de PHP añadiéndolo como dependencia mediante Composer:composer.json
With a cron job (Recommended)
El directorio job/ corresponde a un trabajo que debe ejecutarse mediante un planificador de tareas estándar (como cron). Le sugerimos instalar el script en/usr/local/opt/kameleoon/kameleoon-client-php-process-queries.sh y usar nuestra entrada de crontab predeterminada. Sin embargo, puede instalarlo en otra ubicación y modificar la entrada de crontab en consecuencia.
Without a cron job
If you cannot install the cron job, you can use Kameleoon in hybrid mode to benefit from the Kameleoon Application Engine’s,engine.js (previously named, kameleoon.js) tracking capabilities. Our SDK provides the getEngineTrackingCode() method, which sends exposure events to Kameleoon or any other analytics solution you use on your website.
Configuración adicional
You can customize the behavior of the PHP SDK via a configuration file. We provide a sample configuration file namedclient-php.json.sample in the SDK archive. You can also download a sample configuration file. We suggest to install this file to the default path of /tmp/kameleoon/client-php.json. La siguiente tabla muestra las propiedades disponibles que puede configurar:
| Clave | Descripción | Valor predeterminado |
|---|---|---|
clientId / client_id (obligatorio) | Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su client_id, consulte la documentación de credenciales de API. | |
clientSecret / client_secret (obligatorio) | Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su client_secret, consulte la documentación de credenciales de API. | |
kameleoonWorkDir / kameleoon_work_dir (opcional) | Specifies a working directory for the PHP client (which will create files in this directory). The directory needs to be writable by the PHP user. | /tmp/kameleoon/client-php/ |
refreshIntervalMinute / refresh_interval_minute (opcional) | Specifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers. | 60 minutos |
defaultTimeoutMillisecond / default_timeout_millisecond (opcional) | Specifies the timeout, in milliseconds, for network requests from the SDK. Set the value to 30 seconds or more if you do not have a stable connection. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value. | 10000 milisegundos |
cookieOptions->topLevelDomain / cookie_options.domain (obligatorio en modo híbrido) | El dominio de nivel superior actual de su sitio web. Use el formato: example.com. No incluya https://, www ni otros subdominios. Kameleoon utiliza esta información para establecer la cookie correspondiente en el dominio de nivel superior. | null |
cookieOptions->secure / cookie_options.secure (opcional) | Controls the Secure cookie attribute. | false |
cookieOptions->httpOnly / cookie_options.http_only (opcional) | Controls the HttpOnly cookie attribute. | false |
cookieOptions->sameSite / cookie_options.samesite (opcional) | Controls the SameSite cookie attribute. | Lax |
environment / environment (opcional) | Entorno desde el cual se debe utilizar la configuración del feature flag. El valor puede ser production, staging o development. Consulte el artículo de gestión de entornos para más detalles. | production |
networkDomain / network_domain (opcional) | Dominio personalizado utilizado por los SDKs para las solicitudes salientes, a menudo para proxy. Debe ser un dominio válido (por ejemplo, example.com o sub.example.com). Los formatos no válidos se sustituyen por el valor de Kameleoon. | null |
requestBodySizeLimitBytes / request_body_size_limit_bytes (optional) | Limits the size of tracking packages (in bytes) — files that store data collected between cron job runs. In some cases, reducing the package size may be necessary due to server or network restrictions. The maximum allowed value is 2.5 MB (2621440 bytes). | 2621440 |
debugMode / debug_mode (deprecated) | The parameter sends additional information to our tracking servers to help analyze issues. It should usually be off (false), but activating it (true) has no impact on SDK performance. This field is deprecated and will be removed in SDK version 5.0.0. Use KameleoonLogger::setLogLevel instead. | false |
If you do not use the default path (
/tmp/kameleoon/client-php.json) for the configuration file, you will need to:- pass your configuration file’s path as a third argument to the
KameleoonClientFactory::create()method; - modify your crontab entry to add the —conf argument to the job script (so, for instance, it would be
bash /usr/local/opt/bin/kameleoon-client-php-process-queries.sh --conf /my/path/kameleoon.json).
To learn more about
client_id and client_secret, and how to obtain them, refer to the API credentials article. Tenga en cuenta que el Kameleoon PHP SDK uses the Automation API and follows the OAuth 2.0 client credentials flow.Inicialización del cliente Kameleoon
After installing the SDK into your application and configuring the correct credentials (in/tmp/kameleoon/client-php.json), the next step is to create the Kameleoon client in your application code. Por ejemplo:
/tmp/kameleoon/client-php.json will be used, but you can use a different path for the configuration file by providing an optional third argument to the KameleoonClientFactory::create() method.
It’s your responsibility as the application developer to use correct logic in your application code within the context of A/B testing via Kameleoon. A good practice is to always assume that the current visitor can be left out of the experiment because the experiment has not yet been launched. Leaving out the current visitor is simple, as it corresponds to the implementation of the default / reference variation logic. The code samples in the next paragraph show examples of such an approach.
Activación de un feature flag
Asignación de un ID único a un usuario
Para asignar un ID único a un usuario, puede utilizar el métodogetVisitorCode(). Si no existe un visitor code (en la cookie de los encabezados de la solicitud), el método genera un ID único aleatorio o utiliza un defaultVisitorCode que usted haya generado. A continuación, el ID se establece en una cookie en los encabezados de respuesta.
Si está usando Kameleoon en modo híbrido, llamar al método getVisitorCode() garantiza que el ID único (visitor code) se comparta entre el archivo de aplicación engine.js (anteriormente llamado kameleoon.js) y el SDK.
Recuperación de la configuración de un flag
Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon. Para determinar el estado o la variación de un feature flag para un usuario específico, debe utilizar el métodogetVariation() o isFeatureActive() para recuperar la configuración basada en el featureKey.
El método getVariation() gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del featureKey y el visitorCode.
El método isFeatureActive() puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación.
If your feature flag has associated variables (such as specific behaviors tied to each variation) getVariation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=true, the SDK will send the exposure event to the specified experiment on one of the next tracking request, which is automatically performed by the cron job. De forma predeterminada, its interval is 1 minute.
El método getVariation() le permite controlar si se realiza el seguimiento. Si track=false, el SDK no enviará eventos de exposición. Esto es útil si prefiere no realizar el seguimiento de los datos a través del SDK y, en su lugar, basarse en el seguimiento del lado del cliente gestionado por el motor de Kameleoon, por ejemplo. Además, establecer track=false resulta útil cuando se utiliza el método getVariations(), donde puede que solo necesite las variaciones de todos los flags sin desencadenar eventos de seguimiento. Si desea saber más sobre cómo funciona el seguimiento, consulte este artículo
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
Para segmentar a un usuario, asegúrese de haber añadido los puntos de datos relevantes a su perfil antes de recuperar la variación de la funcionalidad o comprobar si el flag está activo. Utilice el métodoaddData() para añadir estos puntos de datos al perfil del usuario.
Para recuperar puntos de datos recopilados en otros dispositivos o acceder a datos pasados del usuario (recopilados en el lado del cliente cuando se utiliza Kameleoon en modo híbrido), utilice el método getRemoteVisitorData(). Este método obtiene datos de los servidores de forma asíncrona. Es importante llamar a getRemoteVisitorData() antes de recuperar la variación o comprobar si el feature flag está activo, ya que estos datos pueden ser necesarios para asignar a un usuario a una variación determinada.
Para obtener más información sobre las condiciones de segmentación disponibles, consulte el artículo detallado sobre este tema.
Además, los puntos de datos que añade al perfil del visitante estarán disponibles al analizar sus experimentos, lo que le permite filtrar y desglosar sus resultados por factores como el dispositivo y el navegador. El modo híbrido de Kameleoon recopila automáticamente una variedad de puntos de datos en el lado del cliente, lo que facilita desglosar sus resultados en función de estos puntos de datos previamente recopilados. Consulte la lista completa aquí.
Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la funcionalidad de Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método flush() para enviar los datos recopilados a los servidores de Kameleoon para su análisis.
Para asegurarse de que sus resultados sean precisos, se recomienda filtrar los bots utilizando el tipo de dato
UserAgent.Seguimiento de conversiones de objetivos
Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el métodotrackConversion() y proporcione los parámetros requeridos visitorCode y goalId.
La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos en el crontab de intervalo de seguimiento). Si prefiere enviar la solicitud de inmediato, utilice el método flush() con el parámetro instant=true.
Envío de eventos a soluciones de analítica
Para realizar el seguimiento de las conversiones y enviar eventos de exposición a su solución de analítica de cliente, primero debe implementar Kameleoon en modo híbrido. A continuación, utilice el métodogetEngineTrackingCode().
El método getEngineTrackingCode() recupera el código de seguimiento único necesario para enviar eventos de exposición a su solución de analítica. El uso de este método le permite registrar eventos y enviarlos a la plataforma de analítica que desee.
Experimentación entre dispositivos
Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el artículo sobre experimentación entre dispositivos.Sincronización de datos personalizados entre dispositivos
Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado: Mismo ID de usuario en todos los dispositivos Si el mismo ID de usuario se utiliza de forma consistente en todos los dispositivos, la sincronización se gestiona automáticamente sin necesidad de una sincronización de mapeo personalizado. Basta con llamar al métodogetRemoteVisitorData() cuando desee sincronizar los datos recopilados entre varios dispositivos.
Instancias multi-servidor con IDs consistentes
En configuraciones complejas que involucran varios servidores (por ejemplo, instancias de servidor distribuidas), donde el mismo ID de usuario está disponible en todos los servidores, la sincronización entre servidores (con getRemoteVisitorData()) es suficiente sin necesidad de una sincronización adicional de mapeo personalizado.
Los clientes que necesiten datos adicionales pueden consultar la descripción del método getRemoteVisitorData() para obtener más orientación. En el código siguiente se asume que el mismo identificador único (en este caso, el visitorCode, que también puede denominarse userId) se utiliza de manera consistente entre los dos dispositivos para una recuperación precisa de los datos.
Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
Device A
Device B
Uso de datos personalizados para la fusión de sesiones
La experimentación entre dispositivos permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utiliceCustomData para proporcionar un identificador único del visitante. Para más información, consulte la documentación dedicada.
Una vez habilitada la reconciliación entre dispositivos, al llamar a getRemoteVisitorData() con el parámetro userId se recuperan todos los datos conocidos para un usuario determinado.
Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante.
La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen aquí.
Siga la guía de activación de la reconciliación de historial entre dispositivos para configurar sus datos personalizados en la plataforma Kameleoon.
Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:
getRemoteVisitorData()conUniqueIdentifier(true)añadido: para recuperar datos de todos los visitantes vinculados.trackConversion()oflush()con datosUniqueIdentifier(true)añadidos: para hacer seguimiento de datos de un visitante específico asociado con otro visitante.
getVisitorCode(). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.
Uso de una clave de bucketing personalizada
De forma predeterminada, Kameleoon utiliza un ID de visitante anónimo y único (visitorCode) para asignar usuarios a las variaciones de los feature flags. Este ID se genera y almacena habitualmente en el dispositivo del usuario (en una cookie del navegador para los SDKs del lado del cliente y del lado del servidor, y en almacenamiento persistente para los SDKs móviles). Sin embargo, en determinados escenarios puede necesitar asegurarse de que todos los usuarios de la misma organización vean la misma variante de un feature flag.
La opción Custom Bucketing Key le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del visitorCode predeterminado.
Casos de uso
El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:- Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como
accountId. Las claves de bucketing personalizadas son cruciales para probar mediante A/B funcionalidades que afecten a todo un equipo o empresa.
Detalles técnicos
Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:- Proporcionar la clave personalizada: Usted proporciona su identificador personalizado al SDK de Kameleoon mediante el método
addData(). En este método, pasará la clave de bucketing personalizada que haya elegido como un objetoCustomData. Aquí,newVisitorCodehace referencia al identificador que desea usar para el bucketing (por ejemplo, el nuevouserIdoaccountId).
- Lógica de bucketing: Una vez que se proporciona una clave de bucketing personalizada a través del método
addData(), todos los cálculos de hash para asignar usuarios a las variaciones utilizarán estenewVisitorCode(su clave personalizada) en lugar delvisitorCodepredeterminado. Usar elnewVisitorCodesignifica que la decisión de bucketing queda ligada a su identificador personalizado, garantizando asignaciones consistentes en los diversos contextos en los que esté presente ese identificador. - Seguimiento de datos y analítica: Es crucial tener en cuenta que, aunque el
newVisitorCode(su clave personalizada) se utiliza para las decisiones de bucketing, todos los datos posteriores (eventos de seguimiento y conversiones, por ejemplo) se envían y se asocian con elvisitorCodeoriginal. Esta separación garantiza que su analítica refleje con precisión los recorridos e interacciones individuales de los usuarios dentro del contexto más amplio de su experimento, incluso cuando el bucketing se realiza a un nivel superior (como una cuenta) o a través de varios dispositivos/sesiones. Sus datos originales del visitante permanecen intactos para una elaboración de informes completa.
Requisitos técnicos
Para utilizar eficazmente una clave de bucketing personalizada:- The key must be a
string. - Debe ser única para la entidad que pretende agrupar (por ejemplo, si utiliza un
userId, el ID de cada usuario debe ser único). - La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.
Condiciones de segmentación
Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte usar el historial de visitas para segmentar a los usuarios. También puede utilizar sus propios datos externos para segmentar a los usuarios.Registro de eventos
El SDK genera registros que reflejan diversos procesos internos y problemas.Niveles de registro
El SDK admite la configuración para limitar el registro mediante un nivel de log.Gestión personalizada de los registros
El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
Referencia
This is a full reference documentation of the PHP SDK.Inicialización
create()
This method inKameleoon\KameleoonClientFactory creates a KameleoonClient instance by providing your SDK configuration in a configuration file. You need to initialize the SDK by creating this instance of KameleoonClient before you can use other SDK methods. All interactions with the SDK use this KameleoonClient instance. To provide the configuration as a KameleoonClientConfig object instead, see the createWithConfig method.
Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| siteCode | String | Es la clave única del proyecto de Kameleoon que está utilizando con el SDK. Este campo es obligatorio. |
| configurationFilePath | String | Ruta al archivo de configuración del SDK. This field is optional and set to /tmp/kameleoon/client-php.json by default. |
Valor de retorno
| Type | Description |
|---|---|
| Kameleoon\KameleoonClient | An instance of the KameleoonClient class that will be used to manage your experiments and feature flags. |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
| SiteCodeIsEmpty | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| KameleoonException | Exception that may indicate that the SDK is unable to access the Kameleoon working directory. |
createWithConfig()
This method inKameleoon\KameleoonClientFactory creates a KameleoonClient instance and allows you to pass your SDK configuration in a KameleoonClientConfig object. You need to initialize the SDK by creating this KameleoonClient instance before you can use other SDK methods. All interactions with the SDK use this KameleoonClient instance. To provide your SDK configuration in a file instead, use the create method.
Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| siteCode | String | Code of the website you want to run experiments on. This unique code ID can be found in the Kameleoon app. Este campo es obligatorio. |
| kameleoonConfig | KameleoonClientConfig | Configuration SDK object that you pass. Este campo es opcional. |
Valor de retorno
| Tipo | Descripción |
|---|---|
| KameleoonClient | An instance of the KameleoonClient class that you use to manage your experiments and feature flags. |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
| SiteCodeIsEmpty | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| KameleoonException | Exception that may indicate that the SDK is unable to access the Kameleoon working directory. |
Feature flags y variaciones
isFeatureActive()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
This method was previously called
activateFeature, which was removed in SDK version 4.0.0.visitorCode, the isFeatureActive() method uses it as the unique visitor identifier, which is useful for cross-device experimentation. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro
isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as
isFeatureActive(), getVariation() or getVariations().Use el valor predeterminado true para el parámetro track cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro track en false solo si llama a estos métodos antes de exponer a los visitantes.Por ejemplo, if you call getVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
| track | bool | An optional parameter to enable or disable tracking of the feature evaluation (true by default). |
Valor de retorno
| Tipo | Descripción |
|---|---|
| bool | Value of the feature flag that is registered for a given visitorCode. |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getVariation()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Variation asignada a un visitante dado para un feature flag específico.
Este método toma un visitorCode and featureKey as mandatory arguments. The track argument is optional and defaults to true.
Devuelve la Variation asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la Variation predeterminada para el feature flag dado.
Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
Argumentos
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| featureKey (obligatorio) | string | Clave de la funcionalidad que desea exponer a un visitante. | |
| track (opcional) | bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|---|
Variation | An assigned Variation to a given visitor for a specific feature flag. |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FeatureNotFound | Excepción que indica que la clave de funcionalidad solicitada no se encontró en la configuración interna del SDK. Esto suele significar que el feature flag no está activado en la aplicación de Kameleoon (pero el código que implementa la funcionalidad ya está desplegado en la aplicación). |
FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
getVariations()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Variation asignados a un visitante dado para todos los feature flags.
Este método itera sobre todos los feature flags disponibles y devuelve la Variation asignada para cada flag asociado con el visitante especificado. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.
- Si
onlyActivese establece entrue, el métodogetVariations()devolverá las variaciones de los feature flags siempre que el usuario no esté asignado a la variaciónoff. - El parámetro
trackcontrola si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set totrue. Si se establece enfalse, el seguimiento estará deshabilitado.
Variation correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la Variation predeterminada para ese flag.
Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
Argumentos
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| onlyActive (opcional) | bool | Parámetro opcional que indica si se deben devolver las variaciones para los feature flags activos (true) o todos (false). | false |
| track (opcional) | bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|---|
array<string, Types\Variation> | Map que contiene los objetos Variation asignados de los feature flags utilizando las claves de las funcionalidades correspondientes. |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
setForcedVariation()
El método permite you to programmatically assign a specificVariation to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing.
Cuando se establece una variación forzada, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
Argumentos
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| experimentId (obligatorio) | int | Experiment Id que será segmentado y seleccionado durante el proceso de evaluación. | |
| variationKey (obligatorio) | ?string | Variation Key correspondiente a una Variation que debe forzarse como valor devuelto para el experimento. Si el valor es null, la variación forzada se restablecerá. | |
| forceTargeting (opcional) | bool | Indica si la segmentación para el experimento debe forzarse y omitirse (true) o aplicarse como en el proceso de evaluación estándar (false). | true |
| timeout (opcional) | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. | null |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FeatureExperimentNotFound | Excepción que indica que el experiment id solicitado no se encontró en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la regla todavía no se ha activado del lado de Kameleoon. |
FeatureVariationNotFound | Excepción que indica que la variation key (id) solicitada no se ha encontrado en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |
En la mayoría de los casos, solo es necesario gestionar el error básico
KameleoonException, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.evaluateAudiences()
- 📨 Envía datos de seguimiento a Kameleoon
evaluateAudiences() should be called after all relevant visitor data has been set or updated, and just before getting a feature variation or checking a feature flag. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|---|---|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| timeout (opcional) | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. | null |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
En la mayoría de los casos, solo es necesario gestionar el error básico
KameleoonException, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.getDataFile()
Devuelve la configuración actual del SDK como un objetoDataFile.
Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| timeout (opcional) | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|---|
DataFile | El DataFile que contiene la configuración del SDK |
Datos del visitante
getVisitorCode()
Este método se llamaba anteriormente
obtainVisitorCode, que fue eliminado en la versión 4.0.0 del SDK.- First, we check if there is a kameleoonVisitorCode cookie or query parameter associated with the current Solicitud HTTP. If so, we use this as the visitor identifier.
- If no cookie or parameter is present in the current request, we have two options for generating an identifier. One option is to create a new identifier randomly, and the other is to use the defaultVisitorCode argument if it has been provided. This feature allows our customers to input their own identifiers as visitor codes, which can be beneficial; it seamlessly matches Kameleoon visitors with their own users, eliminating the need for extra look-ups in a matching table.
- In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. El método devuelve this visitor value.
If you provide your own
visitorCode, its uniqueness must be guaranteed on your end - the SDK cannot check it. Also note that the length of visitorCode is limited to 255 characters. Any excess characters will throw an exception.El método
getVisitorCode() le permite establecer variaciones simuladas para un visitante. Cuando las cookies (de una request o document) contienen la clave kameleoonSimulationFFData, se omite el proceso de evaluación estándar. En su lugar, el método devuelve directamente una Variation basada en los datos proporcionados.Puede aplicar simulaciones de dos formas:- Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
- Manualmente: Establezca la cookie
kameleoonSimulationFFDatamanualmente.
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
kameleoonSimulationFFData siga este formato:kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simula la variación convarIddel experimentoexpIdpara elfeatureKeyindicado.kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simula la variación predeterminada (definida en la sección Then, for everyone else in Production, serve) para elfeatureKeyindicado.
encodeURIComponent.Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| defaultVisitorCode | String | This parameter will be used as the visitorCode if no existing kameleoonVisitorCode cookie is found on the request. This field is optional, and, by default, a random visitorCode will be generated. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|---|
| String | A visitorCode that will be associated with this particular user and should be used with most of the methods of the SDK. |
Excepciones lanzadas
| Type | Description |
|---|---|
| InvalidArgumentException | Exception indicating that the cookie’s domain value was not provided (either via the configuration file, or via the topLevelDomain parameter on the method). |
addData()
El métodoaddData() añade datos de segmentación al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual.
El método addData() no devuelve ningún valor y no interactúa por sí mismo con los servidores backend de Kameleoon. En su lugar, todos los datos declarados se guardan para su transmisión futura mediante el método flush(). Este enfoque reduce el número de llamadas al servidor, ya que los datos se agrupan habitualmente en una única llamada al servidor que desencadena el flush().
El método trackConversion() también envía cualquier dato previamente asociado, al igual que flush(). The same holds true for getVariation() and getVariations() methods if an experimentation rule is triggered.
Argumentos
| Nombre | Tipo | Descripción | Valor predeterminado |
|---|---|---|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| track (opcional) | bool | Especifica si los datos añadidos son aptos para el seguimiento. Cuando se establece en false, los datos se almacenan localmente y se utilizan solo para la evaluación de segmentación; no se envían a la Data API de Kameleoon. | true |
| data (obligatorio) | ...Data | Colección de tipos de datos de Kameleoon. |
Excepciones
| Tipo | Descripción |
|---|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
flush()
- 📨 Envía datos de seguimiento a Kameleoon
flush() method is responsible for sending the Kameleoon data linked to a specific visitor. It triggers a tracking request that includes all the data previously added with the addData method, which has not yet been sent during an earlier call to one of the methods. flush() is non-blocking, as the server call is made asynchronously, unless the instant parameter is set to true.
La función flush() le permite decidir cuándo se envían a nuestros servidores los datos vinculados a un visitorCode específico. Por ejemplo, si llama a addData() varias veces, digamos una docena, sería ineficiente enviar datos al servidor cada vez que realiza una llamada. En su lugar, puede recopilar todos los datos primero y luego llamar a flush() una sola vez al final para enviarlos todos a la vez.
Si especifica un visitorCode, el método flush() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro
isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
| instant | bool | Boolean flag indicating whether the data should be sent instantly (true) or according to the scheduled tracking interval (false). If not provided, el valor predeterminado es false. Este campo es opcional. |
getRemoteData()
Este método se llamaba anteriormente
retrieveDataFromRemoteSource, que fue eliminado en la versión 4.0.0 del SDK.getRemoteData() method lets you retrieve data based on a key you provide for a specific siteCode (set in KameleoonClientFactory.create()). A Kameleoon server stores this data. The Data API is typically used to save this data on our remote servers. This method, combined with our scalable servers, makes storing large amounts of data easy. You can then access this data later for each visitor or user.
Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| key | string | The key that the data you try to get is associated with. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|---|
| Object | Object associated with retrieving data for specific key. |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
| Exception | Exception indicating that the request timed out or retrieved data can’t be decoded with json_decode method. |
getRemoteVisitorData()
getRemoteVisitorData() es un método asíncrono para recuperar los datos de visitas de Kameleoon para el visitorCode desde la Data API de Kameleoon. El método añade data to storage for other methods to use when making targeting decisions.
Los datos obtenidos mediante este método desempeñan un papel importante cuando desea:
- use data collected from other devices.
- access a user’s history, such as previously visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
El parámetro
isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode | string | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| addData | bool | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. If not specified, el valor predeterminado es true. Este campo es opcional. |
| filter | Kameleoon\Types\RemoteVisitorDataFilter | Filter for specifying what data should be retrieved from visits, by default only CustomData is retrieved from the current and latest previous visit (new RemoteVisitorDataFilter(1, true, true) or new RemoteVisitorDataFilter()). Other filters parameters are set to false. This filed is optional. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
Valor de retorno
| Tipo | Descripción |
|---|---|
array<Kameleoon\Data> | A list of data assigned to the given visitor. |
Uso de parámetros en getRemoteVisitorData()
El métodogetRemoteVisitorData() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Whether you’re targeting based on goals, experiments, or variations, the same approach applies across all data types.
Por ejemplo, let’s say you want to retrieve data on visitors who completed a goal “Order transaction”. Puede especificar parámetros dentro del método getRemoteVisitorData() para refinar su segmentación. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.
La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método getRemoteVisitorData() para recuperar datos sobre una variedad de comportamientos del visitante.
Here is the list of available
Kameleoon\Types\RemoteVisitorDataFilter options:| Name | Type | Description | Default |
|---|---|---|---|
| previousVisitAmount (opcional) | int | Número de visitas previas de las que recuperar datos. Number between 1 and 25 | 1 |
| currentVisit (opcional) | bool | If true, current visit data will be retrieved | true |
| customData (opcional) | bool | If true, custom data will be retrieved. | true |
| pageViews (opcional) | bool | If true, page data will be retrieved. | false |
| geolocation (opcional) | bool | If true, geolocation data will be retrieved. | false |
| device (opcional) | bool | If true, device data will be retrieved. | false |
| browser (opcional) | bool | If true, browser data will be retrieved. | false |
| operatingSystem (opcional) | bool | If true, operating system data will be retrieved. | false |
| conversions (opcional) | bool | If true, conversion data will be retrieved. | false |
| experiments (opcional) | bool | If true, experiment data will be retrieved. | false |
| kcs (opcional) | bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
| visitorCode (opcional) | bool | If true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variation across visits for Cross-device experimentation. | true |
| cbs (opcional) | bool | If true, Contextual Bandit score data will be retrieved. | false |
| personalization (opcional) | bool | If true, personalization data will be retrieved. This is required for the personalization condition. | false |
getVisitorWarehouseAudience()
Este método recupera all audience data associated with the visitor in your data warehouse using the specifiedvisitorCode and warehouseKey. The warehouseKey is typically your internal user ID. The customDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method passes the result to the returned future as a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode | string | The unique identifier of the visitor for whom you want to retrieve and add the data. |
| customDataIndex | int | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. |
| warehouseKey | string | The unique key to identify the warehouse data (usually, your internal user ID). Este campo es opcional. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|---|
?Customdata | CustomData instance confirming that the data has been added to the visitor. If value is null, the request is failed and CustomData wasn’t added to the visitor. |
Excepciones lanzadas
| Type | Description |
|---|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido (está vacío o tiene más de 255 caracteres). |
setLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use thier personal data. Setting thelegalConsent parameter to false limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.
Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| legalConsent | bool | Valor booleano que representa el estado del consentimiento legal. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. Este campo es obligatorio. |
Excepciones lanzadas
| Type | Description |
|---|---|
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
Comportamiento al revocar el consentimiento
Cuando llama asetLegalConsent() con legalConsent=false, el SDK no elimina la cookie kameleoonVisitorCode. En su lugar, deja de prorrogar la fecha de expiración de la cookie, permitiendo que esta persista hasta que expire de forma natural.
Si sus requisitos de cumplimiento exigen la eliminación inmediata del archivo de cookie al revocar el consentimiento, debe eliminarlo manualmente utilizando los métodos nativos de gestión de cookies de su framework. El SDK no eliminará el archivo automáticamente.
Goals and third party analytics
getEngineTrackingCode()
Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call thegetEngineTrackingCode() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.
Consulte experimentación híbrida para más información sobre cómo implementar este método.
- To use this feature, implement both the PHP SDK and Kameleoon Engine.js. Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing
</body>tag. - If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the JavaScript / TypeScript SDK. This option works well for serverless edge compute platforms. The JavaScript / TypeScript SDK automatically tracks variations when you call
getVisitorCode, as long as you add the corresponding experiment assignments towindow.kameleoonQueue.. - You can insert the returned tracking code directly into an HTML
<script>tag.
123456 y 234567 son IDs de experimento, y 7890 y 8901 son IDs de variación. En su implementación, el SDK genera estos valores en el código de seguimiento devuelto.Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. |
Valor de retorno
| Tipo | Descripción |
|---|---|
string | Código JavaScript para insertar en la página. |
trackConversion()
- 📨 Envía datos de seguimiento a Kameleoon
visitorCode and goalId. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitorCode is usually identical to the one that was used when triggering the experiment.
El método trackConversion() no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.
El parámetro
isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.Argumentos
| Nombre | Tipo | Descripción | Default |
|---|---|---|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| goalId (obligatorio) | int | ID del objetivo. | |
| revenue (opcional) | float | Ingreso de la conversión. | 0 |
| negative (opcional) | bool | Define si el ingreso es positivo o negativo. | false |
| metadata (opcional) | ?array<CustomData> | Le permite establecer valores específicos para los datos personalizados que se hayan definido como metadatos del objetivo en la aplicación de Kameleoon. Example: [CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]. In this example, 5 and 9 are the indexes of the custom data (5 = “Payment Type”, 9 = “Delivery Method”). | null |
| isUniqueIdentifier (deprecated) | bool | Parámetro opcional para indicar si el visitorCode es un identificador único. | false |
metadata values are accessible through raw data exports and the results page.Si se proporciona el parámetro
metadata, Kameleoon utilizará estos valores especificados para la conversión actual en lugar de lo recopilado previamente mediante el método addData(). Si se omite el parámetro, Kameleoon utilizará los últimos valores rastreados para esos CustomData antes de la conversión y dentro de la misma visita.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the trackConversion() method.En el siguiente ejemplo, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).Excepciones
| Tipo | Descripción |
|---|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
Tipos de datos
Puede utilizar los siguientes tipos de datos predefinidos deKameleoon\Data.
Browser
El conjunto de datosBrowser almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier valor asociado a él.
| Nombre | Tipo | Descripción |
|---|---|---|
| browserType (obligatorio) | int | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. |
| version (opcional) | float | Version of the browser, floating point number represents major and minor version of the browser |
PageView
| Name | Type | Description | Default |
|---|---|---|---|
| url (obligatorio) | string | URL of the page viewed. Este campo es obligatorio. | |
| title (obligatorio) | ?string | Title of the page viewed. Este campo es obligatorio. | null |
| referrers (opcional) | ?array<int> | Referrers de las páginas vistas. Este campo es opcional. | null |
The index (ID) of the referrer is available in our Back-Office in the Acquisition channel configuration page. Be careful: this index starts at 0, so the first acquisition channel you create for a given site would have the ID 0, not 1.
Conversion
El conjunto de datosConversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
| Nombre | Tipo | Descripción | Default |
|---|---|---|---|
| goalId (obligatorio) | int | ID del objetivo. | |
| revenue (opcional) | float | Revenue of the conversion | 0 |
| negative (opcional) | bool | Define si el ingreso es positivo o negativo. | false |
| metadata (opcional) | ?array<CustomData> | Metadatos de la conversión. | null |
CustomData
CustomData allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in segments or as a filter/breakdown in experiment reports.
To learn more about custom data, please refer to this article.
| Nombre | Tipo | Descripción | Default |
|---|---|---|---|
| indexOrName (obligatorio) | int/string | Índice o nombre del dato personalizado. Either index or name must be provided to identify the data. | |
| values (obligatorio) | string... | Value(s) of the custom data to be stored. | |
| overwrite (opcional) | bool | Flag para controlar explícitamente cómo se almacenan los valores y cómo aparecen en los informes. See more | true |
-
Each visitor is allowed only one
CustomDatafor each uniqueindex. Adding anotherCustomDatawith the sameindexwill replace the existing one. - The custom data ‘index’ can be found in the Custom Data dashboard under the “INDEX” column.
- To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: Use this data only locally for targeting purposes when creating custom data.
-
Adding a
CustomDatainstance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
Device
| Nombre | Tipo | Descripción |
|---|---|---|
| type | int | List of devices: PHONE, TABLET, DESKTOP. Este campo es obligatorio. |
UserAgent
Keep track of visitors’ user-agent information. Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to tackle this issue and recognize known bots and spiders. Kameleoon also uses theUserAgent field to filter out bots and other unwanted traffic that might distort your conversion metrics. Para más detalles, consulte our help article on bot filtering.
Si utiliza bots internos, le sugerimos pasar el valor curl/8.0 del userAgent para excluirlos de nuestra analítica.
| Nombre | Tipo | Descripción |
|---|---|---|
| value | string | The User-Agent value that will be sent with tracking requests. Este campo es obligatorio. |
UniqueIdentifier
Si no añadeUniqueIdentifier para un visitante, se utiliza visitorCode como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando añade UniqueIdentifier para un visitante, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
| Nombre | Tipo | Descripción |
|---|---|---|
| value | bool | Parameter for specifying if the visitorCode is a unique identifier. Este campo es obligatorio. |
OperatingSystem
OperatingSystem contains information about the operating system on the visitor’s device.
| Nombre | Tipo | Descripción |
|---|---|---|
| type | int | List of operating systems: WINDOWS, MAC, IOS, LINUX, ANDROID and WINDOWS_PHONE. Este campo es obligatorio. |
Cookie
Cookie contains information about the cookie stored on the visitor’s device.
| Nombre | Tipo | Descripción |
|---|---|---|
| cookies | array | Map de objetos string que consta de claves y valores de cookies. Este campo es obligatorio. |
Geolocation
Geolocation contains the visitor’s geolocation details.
| Nombre | Tipo | Descripción |
|---|---|---|
| country (obligatorio) | string | The country of the visitor. |
| region (opcional) | ?string | The region of the visitor. |
| city (opcional) | ?string | The city of the visitor. |
| postalCode (opcional) | ?string | The postal code of the visitor. |
| latitude (opcional) | float | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
| longitude (opcional) | float | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
| Nombre | Tipo | Descripción |
|---|---|---|
| version (opcional) | string | The mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, or major.minor.patch. |
Returned Types
DataFile
ElDataFile contiene los detalles de configuración del SDK.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|---|---|
| featureFlags | array<string, FeatureFlag> | A map of FeatureFlag objects, keyed by feature flag keys. |
| dateModified | int | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
FeatureFlag
FeatureFlag representa un conjunto de propiedades que definen un feature flag en sí — por ejemplo, sus Variations, Rules, estado del entorno y otros detalles relacionados.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|---|---|
| isEnvironmentEnabled | bool | Indica si el feature flag está habilitado en el entorno actual. |
| defaultVariationKey | string | The key of the default variation associated with the feature flag. |
| variations | array<string, Variation> | A map of Variation objects, keyed by variation keys. |
| rules | array<Rule> | A list of Rule objects |
Rule
Rule representa un conjunto de propiedades que definen una regla en sí — por ejemplo, sus Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|---|---|
| variations | array<string, Variation> | A map of Variation objects, keyed by variation keys. |
Variation
Variation contains information about the assigned variation to the visitor (or the default variation if no specific assignment exists).
| Nombre | Tipo | Descripción |
|---|---|---|
| name | string | The name of the variation. |
| key | string | The unique key identifying the variation. |
| id | ?int | The ID of the assigned variation (or null if it’s the default variation). |
| experimentId | ?int | The ID of the experiment associated with the variation (or null if default). |
| variables | array<string, Variable> | An array containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated. |
- The
Variationobject provides details about the assigned variation and its associated experiment, while theVariableobject contains specific details about each variable within a variation. - Ensure that your code handles the case where
idorexperimentIdmay benull, indicating a default variation. - The
variablesarray might be empty if no variables are associated with the variation.
Variable
Variable contains information about a variable associated with the assigned variation.
| Nombre | Tipo | Descripción |
|---|---|---|
| key | string | The unique key identifying the variable. |
| type | string | The type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS |
| value | ?mixed | The value of the variable, which can be of the following types: bool, int, float, string, stdClass, array, null. |
Deprecated methods
getFeatureVariationKey()
- 📨 Envía datos de seguimiento a Kameleoon
Use
getVariation() instead.getFeatureVariationKey() method of our SDK.
Este método toma un visitorCode and featureKey as mandatory arguments to get the variation key for a given user.
If a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous variation key value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer’s account.
You have to make sure that proper error handling is set up in your code como se muestra en el ejemplo to the right to catch potential exceptions.
Si especifica un visitorCode, el método getFeatureVariationKey() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro
isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
Valor de retorno
| Tipo | Descripción |
|---|---|
| string | Variation key of the feature flag that is registered for a given visitorCode. |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getActiveFeatureListForVisitor()
Use
getActiveFeatures() instead.Argumentos
| Name | Type | Description |
|---|---|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Type | Description |
|---|---|
| any | List of feature flag keys which are active for a given visitorCode |
Excepciones lanzadas
| Type | Description |
|---|---|
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getActiveFeatures()
Use
getVariations() instead.getActiveFeatures method retrieves information about the active feature flags that are available for the specified visitor code.
Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|---|
| array | An array that contains the assigned variations of the active features using the active feature IDs as keys. |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getFeatureVariable()
- 📨 Envía datos de seguimiento a Kameleoon
- Use
getVariation()instead. - This method was previously called
obtainFeatureVariable, which has been deprecated since SDK version3.0.0and will be removed in a future release.
getFeatureVariable() method.
Este método toma un visitorCode, featureKey, and variableName as mandatory arguments to get a variable of the variation key for a given user.
If the user has never been associated with this feature flag, the SDK returns a variable value of the variation key randomly (according to the feature flag rules). If a user with a given visitorCode is already registered with this feature flag, the method will detect the variable value for the associated variation. If the user does not match any of the rules, the default variable will be returned.
Ensure proper error handling is set up in your code como se muestra en el ejemplo to the right to catch potential exceptions.
Si especifica un visitorCode, el método getFeatureVariable() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro
isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier es útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| variableName | string | Name of the variable you want to get a value. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
Valor de retorno
| Tipo | Descripción |
|---|---|
| Any | Value of variable of variation that is registered for a given visitorCode for this feature flag. Possible types: bool, int, float, string, object, array |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| FeatureVariableNotFound | Exception indicating that the requested variable has not been found. Check that the variable’s ID (or key) matches your code. |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getFeatureVariationVariables()
- Use
getVariation()instead. - This method was previously called
getFeatureAllVariables, which was removed in SDK version4.0.0.
getFeatureVariationVariables() method. A feature variable can be changed easily via our web application.
Este método toma featureKey and variationKey as mandatory arguments. It will return the data with the object type, as defined on the web interface. The method throws an error (FeatureNotFound) if the requested feature flag has not been found in the SDK’s client configuration. If the variation key isn’t found, the method throws the FeatureVariationNotFound error.
Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| featureKey | string | Key of the feature flag you want to obtain. Este campo es obligatorio. |
| variationKey | string | Clave de la variación que desea obtener. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|---|
| Any | Value of the variation variable that is registered for a given visitorCode for this feature flag. Possible types: bool, int, float, string, object, array |
Excepciones lanzadas
| Tipo | Descripción |
|---|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
| FeatureVariationNotFound | Exception indicating that the requested variation ID has not been found in the SDK’s internal configuration. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getFeatureList()
Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.Argumentos
| Nombre | Tipo | Descripción |
|---|---|---|
| timeout (opcional) | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|---|
array<string> | List of feature flag keys |