Guía del desarrollador
Follow this section to install and configure the SDK, and learn about advanced features.Primeros pasos
Instalación del cliente Go
To install the Kameleoon Go SDK, use thego get command and install our package directly from our GitHub repository. Simply run the command below:
Configuración adicional
To provide additional settings for the Go SDK, you can use a configuration file, which lets you customize the SDK’s behavior. You can download a sample configuration file here. We recommend installing this file to the default path/etc/kameleoon/client-go.yaml, which will be read automatically. If you need to customize this path, you can provide an additional argument to the NewClient() method. Either specify a string that indicates an alternative path to the configuration file, or add a JavaScript object (map) containing the configuration.
La versión actual del SDK de Go tiene las siguientes claves disponibles en el archivo de configuración:
To learn more about
client_id and client_secret, and instructions on how to obtain them, please refer to this article. It’s worth noting that our Go SDK utilizes the Automation API and follows the OAuth 2.0 client credentials flow.Initializing the Kameleoon Client
Once you have installed our SDK in your application, you must initialize Kameleoon. All interactions with the SDK, such as triggering an experiment, are accomplished via the object (the Kameleoon client) created using theNewClient() method.
Puede personalizar el comportamiento del SDK (por ejemplo, el entorno o las credenciales) proporcionando un objeto de configuración.
Activación de un feature flag
Asignación de un ID único a un usuario
To assign a unique ID to a user, you can use theGetVisitorCode() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a defaultVisitorCode that you would have generated. The ID is then set in a response headers cookie.
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. To determine the status or variation of a feature flag for a specific user, you should use theGetVariation() or IsFeatureActive() method to retrieve the configuration based on the 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 GetVariationOptParams.Track=true, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s tracking_interval. De forma predeterminada, this interval is set to 1000 milliseconds (1 second).
The GetVariation() method allows you to control whether tracking is done. If GetVariationOptParams.Track=false, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting GetVariationOptParams.Track=false is helpful when using the GetVariations() method, where you might only need the variations for all flags without triggering any tracking events. Si desea saber más sobre how tracking works, view this article
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use theAddData() method to add these data points to the user’s profile.
To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the GetRemoteVisitorData() method. This method asynchronously fetches data from the servers. It is important to call GetRemoteVisitorData() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.
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.Tracking flag exposition and goal conversions
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 por tracking_interval). Si prefiere enviar la solicitud de inmediato, utilice el método FlushVisitorInstantly().
Envío de eventos a soluciones de analítica
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use theGetEngineTrackingCode() method.
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 If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call theGetRemoteVisitorData() method when you want to sync the data collected between multiple devices.
Instancias multi-servidor con IDs consistentes
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with GetRemoteVisitorData()) is sufficient without additional custom mapping sync.
Customers who need additional data can refer to the GetRemoteVisitorData() method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the visitorCode, which can also be referred to as userId) is used consistently between the two devices for accurate data retrieval.
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.
After cross-device reconciliation is enabled, calling GetRemoteVisitorData() with the parameter userId retrieves all known data for a given user.
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()with addedUniqueIdentifier(true)- to retrieve data for all linked visitors.TrackConversion()orFlush*()with addedUniqueIdentifier(true)data - to track some data for specific visitor that is associated with another visitor.
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:- Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the
AddData()method. In this method, you will pass your chosen custom bucketing key as aCustomDataobject. Here,newVisitorCoderefers to the identifier you wish to use for your bucketing (for example, the newuserIdoraccountId).
- Bucketing logic: Once a custom bucketing key is provided through the
AddData()method, all hash calculations for assigning users to variations will use thisnewVisitorCode(your custom key) instead of the defaultvisitorCode. Using thenewVisitorCodemeans that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present. - 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 Go SDK.Inicialización
Create()
Llame a este método antes que a cualquier otro para inicializar el SDK. Este método se encuentra enKameleoonClientFactory. Esto crea una instancia de KameleoonClient para gestionar todas las interacciones entre el SDK y su aplicación.
Argumentos
Valor de retorno
CreateFromFile()
Llame a este método antes que a cualquier otro para inicializar el SDK. Este método se encuentra enKameleoonClientFactory. Esto crea una instancia de KameleoonClient para gestionar todas las interacciones entre el SDK y su aplicación.
Argumentos
Valor de retorno
Forget()
El métodoForget elimina una instancia de KameleoonClient del KameleoonClientFactory con el siteCode especificado y libera los recursos utilizados por la instancia de KameleoonClient. La instancia de KameleoonClient no debe utilizarse después de llamar al método Forget.
Argumentos
WaitInit()
La inicialización del cliente Kameleoon no es inmediata, ya que requiere una solicitud al servidor de nuestra CDN (Content Delivery Network) para recuperar la configuración actual de todos los experimentos activos y feature flags. El métodoWaitInit de kameleoon.KameleoonClient le permite esperar hasta que la instancia de KameleoonClient esté lista para usarse.
Valor de retorno
Feature flags y variaciones
IsFeatureActive() / IsFeatureActiveWithTracking()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
GetVariation.
It takes a visitorCode and featureKey as mandatory arguments to check if the feature flag is active for a given user.
If the user has not been associated with your feature flag before, the SDK returns a random boolean value (true if the user should have this feature or false if not). However, if the user has already been registered with this feature flag, the SDK detects the previous feature flag value.
It is important to set up proper error handling in your code to catch any potential exceptions that may occur, as shown in the code example.
visitorCode, el método IsFeatureActive 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.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 GetVariationOptParams.Track cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro GetVariationOptParams.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 GetVariationsOptParams.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
Valor de retorno
Excepciones lanzadas
GetVariation()
- 📨 Envía datos de seguimiento a Kameleoon (depending on the
GetVariationOptParams.Trackparameter)
Variation asignada a un visitante dado para un feature flag específico.
Este método toma un visitorCode and featureKey as mandatory arguments. The GetVariationOptParams.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
Valor de retorno
Excepciones lanzadas
GetVariations()
- 📨 Envía datos de seguimiento a Kameleoon (depending on the
GetVariationsOptParams.Trackparameter)
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 GetVariationsOptParams.OnlyActive and GetVariationsOptParams.Track are optional.
- If
GetVariationsOptParams.OnlyActiveis set totrue, the methodGetVariations()will return feature flags variations provided the user is not bucketed with theoffvariation. - The
GetVariationsOptParams.Trackparameter controls whether or not the method will track the variation assignments. 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
Valor de retorno
Excepciones lanzadas
Argumentos
Valor de retorno
Excepciones lanzadas
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 SetForcedVariationOptParams.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
Excepciones lanzadas
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
Excepciones lanzadas
GetDataFile()
Devuelve la configuración actual del SDK como un objetoDataFile.
Valor de retorno
Datos del visitante
GetVisitorCode()
This method was previously called
ObtainVisitorCode, which was removed in SDK version 3.0.0.GetVisitorCode() method to obtain the Kameleoon visitorCode for the current visitor. Here’s how it works:
- Kameleoon checks if there is a kameleoonVisitorCode cookie associated with the current Solicitud HTTP. If found, Kameleoon this code as the visitor identifier.
- If no cookie is found, the method will either randomly generate a new identifier, or use the defaultVisitorCode argument if it is passed. Using your identifiers as visitor codes allows you to match Kameleoon visitors with your own users without additional look-ups.
- The server-side kameleoonVisitorCode cookie is then set with the identifier value via HTTP header and the method returns the identifier value.
If you decide to provide your own
User ID instead of using the Kameleoon generated visitorCode, it is your responsibility to ensure that the User ID is unique. The SDK does not check for uniqueness. It’s important to note that the User ID you provide must not exceed 255 characters, as any excess characters will result in an exception being thrown.The
GetVisitorCode() method allows you to set simulated variations for a visitor. 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
Valor de retorno
Excepciones lanzadas
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.
The AddData() method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the Flush*() method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the Flush*().
El método TrackConversion() también envía cualquier dato previamente asociado, al igual que Flush*(). Lo mismo aplica para los métodos GetVariation() y GetVariations() si se desencadena una regla de experimentación.
Argumentos
Excepciones
FlushAll() / FlushVisitor() / FlushVisitorInstantly()
- 📨 Envía datos de seguimiento a Kameleoon
FlushAll()/FlushVisitor()/FlushVisitorInstantly() methods collects the Kameleoon data linked to the visitor. It then sends a tracking request, along with all data added using the AddData method, which has not yet been sent using one of these methods. Flush*() is non-blocking as the server call is made asynchronously.
Flush*() lets you control when the data associated with a given visitorCode is sent to our servers. For instance, if you call AddData() a dozen times, it would be inefficient to send data to the server after each time AddData() is invoked, so all you have to do is call Flush() once at the end.
El método FlushVisitor()/FlushVisitorInstantly() usa visitorCode 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
Excepciones lanzadas
GetRemoteData()
El métodoGetRemoteData() recupera datos externos almacenados en el servidor remoto de Kameleoon para el siteCode especificado (especificado en el constructor de KameleoonClient) según una key pasada como argumento. Esta clave es habitualmente el Visitor Code de Kameleoon o su User ID.
Puede utilizar este método para recuperar preferencias de usuario, datos históricos o cualquier otro dato relevante para la lógica de su aplicación. Al almacenar estos datos en nuestros servidores altamente escalables usando nuestra Data API, puede gestionar eficientemente cantidades masivas de datos y recuperarlos para todos sus visitantes o usuarios.
El valor devuelto por el método es un objeto JSON que puede decodificarse usando la función json.Unmarshal(). Puede usar estos datos para crear segmentos de segmentación avanzados para feature flags y experimentos, o para filtrar los informes de experimentos y personalización basándose en cualquier valor almacenado en los datos recuperados.
Note that, since a server call is required, this mechanism is asynchronous.
Argumentos
Valor de retorno
Excepciones lanzadas
GetRemoteVisitorData()
GetRemoteVisitorData() is an asynchronous method for retrieving Kameleoon Visits Data for the VisitorCode from the Kameleoon Data API. El método añade los datos al almacenamiento para que otros métodos los utilicen al tomar decisiones de segmentación.
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.
The parameter
IsUniqueIdentifier is deprecated. Please use UniqueIdentifier instead.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 of GetRemoteVisitorData
Argumentos of GetRemoteVisitorDataWithFilter
Argumentos of GetRemoteVisitorDataWithOptParams
The
GetRemoteVisitorDataWithOptParams method is deprecated. Please use GetRemoteVisitorDataWithFilter and UniqueIdentifier. instead.Here is the list of
kameleoon.RemoteVisitorDataOptParams fields:El valor predeterminado de
kameleoon.RemoteVisitorDataOptParams, que es types.RemoteVisitorDataFilter{PreviousVisitAmount: 1, CurrentVisit: true, CustomData: true}, puede obtenerse con la función types.DefaultRemoteVisitorDataFilter().Valor de retorno
Using parameters in GetRemoteVisitorData()
El métodoGetRemoteVisitorData() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Ya sea que esté segmentando en función de objetivos, experimentos o variaciones, el mismo enfoque se aplica a todos los tipos de datos.
Por ejemplo, let’s say you want to retrieve data on visitors who completed a goal “Order transaction”. You can specify parameters within the GetRemoteVisitorData() method to refine your targeting. 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
types.RemoteVisitorDataFilter options:GetVisitorWarehouseAudience()
Retrieves 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. El método devuelve a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
Argumentos of GetVisitorWarehouseAudience
Argumentos of GetVisitorWarehouseAudienceWithOptParams
Here is the list of
kameleoon.VisitorWarehouseAudienceOptParams fields:For
GetVisitorWarehouseAudience method parameters are passed into the function as params of struct VisitorWarehouseAudienceParams to make some of them optional (WarehouseKey and Timeout).For GetVisitorWarehouseAudienceWithOptParams method only optional parameters are passed into the function as params of struct VisitorWarehouseAudienceOptParams.Valor de retorno
SetLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use 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
Excepciones lanzadas
Comportamiento al revocar el consentimiento
Cuando llama aSetLegalConsent() con consent=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.
Objetivos y analítica de terceros
TrackConversion()
- 📨 Envía datos de seguimiento a Kameleoon
visitorCode and goalId. In addition, this method also accepts an optional TrackConversionOptParams.Revenue, TrackConversionOptParams.Negative and TrackConversionOptParams.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
TrackConversionOptParams.Metadata values are accessible through raw data exports and the results page.If the
TrackConversionOptParams.Metadata parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the AddData() method. If the parameter is omitted, Kameleoon will use the last tracked values for those CustomData prior to the conversion and within the same visit.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
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 Go 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
Valor de retorno
Events
OnUpdateConfiguration()
OnUpdateConfiguration le permite gestionar el evento cuando la configuración tiene datos actualizados. Toma un parámetro de entrada, handler. El manejador que se llamará cuando la configuración se actualice mediante un evento de configuración en tiempo real.
Argumentos
Tipos de datos
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.
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.
Cookie
Cookie contains information about the cookie stored on the visitor’s device.
Geolocation
Geolocation contains the visitor’s geolocation details.
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.
-
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
Puede utilizar los datos del dispositivo para filtrar los informes de experimentos o personalización por cualquier valor asociado.NewDevice
OperatingSystem
OperatingSystem contains information about the operating system on the visitor’s device.
NewOperatingSystem
PageView
Puede utilizar los datos de pageview para filtrar los informes de experimentos o personalización por cualquier valor asociado.The index or ID of the referrer can be found in your Kameleoon account. It is important to note that this index starts at 0. This menas the first acquisition channel you create for a given site will be assigned 0 as its ID, not 1.
NewPageView
NewPageViewWithTitle
UserAgent
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.
NewUserAgent
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.
NewUniqueIdentifier
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
NewApplicationVersion
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.
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.
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.
Variation
Variation contains information about the visitor’s assigned variation (or the default variation, if no specific assignment exists).
- 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
VariationIDorExperimentIDmay benil, indicating a default variation. - The
Variablesmap might be empty if no variables are associated with the variation.
Variable
Variable contains information about a variable associated with the assigned variation.
Deprecated methods
GetFeatureVariationKey()
- 📨 Envía datos de seguimiento a Kameleoon
Use
GetVariation() instead.Don’t forget to handle potential exceptions with proper error handling in your code. See the example code for guidance.
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 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
Valor de retorno
Excepciones lanzadas
GetActiveFeatureListForVisitor()
Use
GetActiveFeatures() instead.GetActiveFeatureListForVisitor() toma un parámetro visitorCode. Cuando llama a este método con un visitorCode específico, el método devuelve una lista de claves de feature flags disponibles para ese visitorCode.
Don’t forget to handle potential exceptions with proper error handling in your code. Por ejemplo, see the following code:
Argumentos
Valor de retorno
Excepciones lanzadas
GetActiveFeatures()
Use
GetVariations() instead.GetActiveFeatures() recupera información sobre los feature flags activos disponibles para el visitor code especificado.
Don’t forget to handle potential exceptions with proper error handling in your code. Por ejemplo, see the following code:
Argumentos
Valor de retorno
Excepciones lanzadas
GetFeatureVariable()
- 📨 Envía datos de seguimiento a Kameleoon
Use
GetVariation() instead.GetFeatureVariable() method of our SDK.
Este método toma un visitorCode, featureKey and variableKey as mandatory arguments to get a variable of the variation key for a given user.
If the user has never been associated with the feature flag, the SDK returns a variable value of the variation key randomly, following the feature flag rules. If the user is already registered with the feature flag, the SDK detects the previous variation key value and returns the variable value. If the user doesn’t match any of the rules, the default value will be returned.
Don’t forget to handle potential exceptions with proper error handling in your code. See the example code for guidance.
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
Valor de retorno
Excepciones lanzadas
GetFeatureVariationVariables()
Use
GetVariation() instead.GetFeatureVariationVariables method. This method requires two mandatory arguments: featureKey and variationKey. El método devuelve the data with the object type, as defined in the Kameleoon Platform.
Don’t forget to handle potential exceptions with proper error handling in your code. Check out the example code for guidance.