# Piano Analytics Developers Documentation > Everything you need to know to master your data This file contains all documentation content in a single document following the llmstxt.org standard. ## Consent rules by Consent Mode ## opt-in Details | Storage | Events | Properties | | :------ | :----- | :--------- | | All | All | All | ## essential Details | Storage | Events | Properties | | ------- | ---------------- | ---------------------------- | | _pcid | click.action | app_crash | | _pctx | click.download | app_crash_class | | _pprv | click.exit | app_crash_screen | | | click.navigation | app_version | | | page.display | browser | | | | browser_cookie_acceptance | | | | browser_group | | | | browser_version | | | | ch_ua\* | | | | click | | | | click_chapter1 | | | | click_chapter2 | | | | click_chapter3 | | | | click_full_name | | | | connection_monitor | | | | connection_organisation | | | | connection_type | | | | date | | | | date_day | | | | date_daynumber | | | | date_month | | | | date_monthnumber | | | | date_week | | | | date_year | | | | date_yearofweek | | | | device_brand | | | | device_display_height | | | | device_display_width | | | | device_name | | | | device_name_tech | | | | device_screen_diagonal | | | | device_screen_height | | | | device_screen_width | | | | device_timestamp_utc | | | | device_type | | | | event_collection_platform | | | | event_collection_version | | | | event_hour | | | | event_id | | | | event_minute | | | | event_name | | | | event_position | | | | event_second | | | | event_time | | | | event_time_utc | | | | event_url | | | | event_url_domain | | | | event_url_full | | | | exclusion_cause | | | | exclusion_type | | | | geo_city | | | | geo_continent | | | | geo_country | | | | geo_metro | | | | geo_region | | | | hit_time_utc | | | | os | | | | os_group | | | | os_version | | | | os_version_name | | | | page | | | | page_chapter1 | | | | page_chapter2 | | | | page_chapter3 | | | | page_duration | | | | page_full_name | | | | page_position | | | | page_title_html | | | | page_url | | | | pageview_id | | | | privacy_status | | | | site | | | | site_env | | | | site_id | | | | site_platform | | | | src | | | | src_detail | | | | src_direct_access | | | | src_organic | | | | src_organic_detail | | | | src_portal_domain | | | | src_portal_site | | | | src_portal_site_id | | | | src_portal_url | | | | src_referrer_site_domain | | | | src_referrer_site_url | | | | src_referrer_url | | | | src_se | | | | src_se_category | | | | src_se_country | | | | src_type | | | | src_url | | | | src_url_domain | | | | src_webmail | | | | visit_bounce | | | | visit_duration | | | | visit_entrypage | | | | visit_entrypage_chapter1 | | | | visit_entrypage_chapter2 | | | | visit_entrypage_chapter3 | | | | visit_entrypage_full_name | | | | visit_exitpage | | | | visit_exitpage_chapter1 | | | | visit_exitpage_chapter2 | | | | visit_exitpage_chapter3 | | | | visit_exitpage_full_name | | | | visit_hour | | | | visit_id | | | | visit_minute | | | | visit_page_views | | | | visit_second | | | | visit_time | | | | visitor_privacy_consent | | | | visitor_privacy_mode | ## extended-optout Details | Storage | Events | Properties | | -------- | ------ | ---------- | | _pprv | All | All | | _pcid\* | | | | _pctx\* | | | > note: > > \*: If you specify [using Analytics only](/analytics/data-collection/how-to-send-events/consent/#configure-the-default-consent-mode) (`window.pdl.consent.products = ['PA'];`), this cookie won't be deposited ## opt-out Details | Storage | Events | Properties | | -------- | ---------------- | ------------------------- | | _pprv | click.action | ch_ua\* | | _pcid\* | click.download | connection_type | | _pctx\* | click.exit | device_timestamp_utc | | | click.navigation | visitor_privacy_consent | | | page.display | visitor_privacy_mode | > note: > > \*: If you specify [using Analytics only](/analytics/data-collection/how-to-send-events/consent/#configure-the-default-consent-mode) (`window.pdl.consent.products = ['PA'];`), this cookie won't be deposited ## custom By default, the `custom` mode will take the same rules as the `opt-in` mode. --- ## Collection methods Once you have chosen to implement Piano Analytics via our SDKs, our collection API or a TMS, thanks to our [dedicated article](/analytics/data-collection/general/implementation-methods/), you can choose the collection method that suits you best. ## Piano collection endpoint The Piano collection endpoint is the "standard" collection you usually start with. It is simple and works without any configuration on your side. ![Classic Collection](/analytics/assets/images/collection_classic_sdk_2-34dba1384fdabc2da72af566ab39175b.png) To find your collection domain, you can go directly to our [Collection Domains](https://analytics.piano.io/datacollection/#/collection-domains) tool: ![Collection domain](/analytics/assets/images/collection-domains-app-c18ee45dea46dcd5e4c6fde39591ae33.png) You can pick any of the collection domains, they are dedicated to your organization and only your sites can collect data on them. Please note that the example here is based on a SDK implementation. The same applies to a Collection API implementation. Check the [dedicated article](/analytics/data-collection/general/implementation-methods/) to understand the difference. ## Custom Domain Data Collection To guarantee data collection in the best conditions, we provide the ability to send events to our servers with a CNAME from one of your subdomains. By using a custom domain, you keep your events, and collect more while keeping our SLAs. ![CDDC Collection](/analytics/assets/images/collection_cddc_sdk_2-0db8345cd36352c16222bb181526a6f5.png) Please note that the example here is based on a SDK implementation. The same applies to a Collection API implementation. Check the [dedicated article](/analytics/data-collection/general/implementation-methods/) to understand the difference. If you want more information related to our Custom Domain Data Collection method, don't hesitate to consult the [dedicated article](https://analytics-docs.piano.io/en/analytics/v1/custom-domain-data-collection-cddc) in our Help Center. If you want to reach the CDDC configuration interface, please follow this [link](https://analytics.piano.io/datacollection/#/collection-domains). You can find the documentation for [renewing process here](/analytics/data-collection/collection-domains/custom/renew-certificate/). ## Proxify your collection In order to maximize your data collection, you can set up a proxy between your visitors and our collection servers. This is usually done through your CDN, but it can be achieved with any proxy configured accordingly. ![CDN Collection](/analytics/assets/images/collection_cdn_2-773e8df8d987ca93fb349bfd1cc76562.png) To set this up, please follow these requirements: - Headers - Highly recommended: forward full initial request, cleaned from headers you need to (sensitive cookies, …). - If not possible, following headers are required: - `Host`: Origin address and not the Client CDN address (The TLS certificate submitted by the Origin will match the Piano Analytics collection domain) - `X-Forwarded-For`: IP address of the user must be propagated - `User-Agent`, `Client Hints` (`Sec-Ch-Ua*`), `Accept-Language`, `Referer` - Necessary cookies for analytical collection should be transmitted: `atid`, `atidx` and `idrxvr` *(please note that these values are subject to change)* - No forwarding to Custom Domains (CDDC), use your `pa-cd.com` domain. - Whatever path is set on the Client CDN side (e.g. `www.client.com/analy/tics`), it must be returned to a non-empty top-level path on the Piano Analytics API: - `xxx.pa-cd.com/event` is correct - `xxx.pa-cd.com/analy/tics` is **not** correct - `xxx.pa-cd.com/` is **not** correct - The entire querystring must be embedded in the request sent to the Origin, and the HTTP method must be the same as the initial request (`GET` or `POST`) - No caching mechanism configured, all requests received by the CDN/Proxy Client should be forwarded to the Piano Analytics collection domain Most CDNs already handle the constraints described below: - The DNS lifetime (TTL) of the Origin must be followed (60 seconds). The IP addresses of the Origin are dynamic and therefore subject to change over time and geographic location. - The Origin is exposed through multiple IP addresses for a single geographic location. Load balancing should be done across all Origin's IP addresses, not just one for a given period of time. - For example: for a traffic of 1000 requests/s, if the DNS resolution of the Origin domain responds with 4 IPs, we must make sure to send 250 requests/s on each IP. --- ## How Piano Analytics Works Piano Analytics uses a simple yet powerful **event-driven data model** that makes it easy to track user behavior across websites, mobile apps, and server-side applications. ## Core Concepts At the heart of Piano Analytics are two fundamental building blocks: ### Events [**Events**](https://analytics-docs.piano.io/en/analytics/v1/events) represent specific user interactions or system occurrences you want to measure: - **Page views** (`page.display`) - When users visit pages - **Clicks** (`click.navigation`) - When users interact with elements - **Purchases** (`transaction.confirmation`) - When users complete transactions - **Video plays** (`av.play`) - When users engage with media - **Custom events** \- Any business-specific interactions you define ### Properties [**Properties**](https://analytics-docs.piano.io/en/analytics/v1/properties) provide context and details about each event: - **Page information** (`page`, `page_chapter1`) - Where the event happened - **Content details** (`article_title`, `product_name`) - What was involved - **User attributes** (`user_id`, `user_category`) - Who performed the action - **Technical data** (`device_type`, `browser`) - How the event occurred **Example:** A page view event might include properties like page name, category, publication date, and user status. ## Data Model Flexibility ### Standard Properties (450+ available) Piano Analytics provides an extensive library of pre-defined events and properties covering common analytics scenarios: - **Web analytics** \- Page views, navigation, search - **E-commerce** \- Product views, cart actions, purchases - **Media** \- Video/audio playback, engagement metrics - **Mobile apps** \- Screen views, app lifecycle events [→ View standard events documentation](/analytics/data-collection/how-to-send-events/standard-events/) ### Custom Properties For unique business requirements, create custom events and properties to capture specific interactions: ```javascript // Custom event example pa.sendEvent("newsletter.signup", { newsletter_type: "weekly", signup_source: "homepage_banner", user_segment: "premium", }); ``` ### Property Processing Types Piano Analytics handles two types of properties: - **Processed Properties**: Sent directly in your tracking code and immediately available in reports - **Calculated Properties**: Computed during data processing (e.g., session duration, bounce rate) The [data model documentation](https://analytics-docs.piano.io/en/analytics/v1/properties) specifies which properties to include in your tracking implementation. ## Getting Started: Your First Events The best way to understand Piano Analytics is through practical examples. Let's walk through implementing basic tracking for your website or application. ### Quick Start with Instant Tracking ≥ 6.16.0 **For websites:** The fastest way to start collecting data is with [Instant Tracking](/analytics/data-collection/how-to-send-events/instant-tracking/). Add one script to automatically track page views and basic interactions: **Benefits:** - ✅ Immediate data collection with zero configuration - ✅ Automatic page view tracking - ✅ Built-in privacy controls - ✅ Minimal code required ```html My Page ... ``` ### Example 1: Tracking Page Views The foundation of web analytics is measuring when users view pages. Here's how to send a `page.display` event with contextual properties: ### JavaScript ```html My Page ... ``` Before 6.16.0 ```html My Page ... ``` ### Android (3.3.0+) ```java pa.setConfiguration(new Configuration.Builder() .withCollectDomain(".pa-cd.com") .withSite(123456789) .build() ); ... pa.sendEvent(new Event("page.display", new HashMap() {{ // Event name put("page", "page name"); // Event properties put("page_chapter1", "level 1"); put("page_chapter2", "level 2"); put("page_chapter3", "level 3"); }})); ``` ### Android ```kotlin import io.piano.android.analytics.Configuration import io.piano.android.analytics.PianoAnalytics ... val configuration = Configuration.Builder( collectDomain = ".pa-cd.com", site = 123456789 ).build() PianoAnalytics.init(applicationContext, configuration) ... PianoAnalytics.getInstance().sendEvents( Event.Builder("page.display") .properties( Property(PropertyName("page"), "page name"), Property(PropertyName("page_chapter1"), "level 1"), Property(PropertyName("page_chapter2"), "level 2"), Property(PropertyName("page_chapter3"), "level 3"), ) .build() ) ``` ### Apple ```swift pa.setConfiguration(ConfigurationBuilder() .withCollectDomain(".pa-cd.com") .withSite(123456789) .build() ) ... pa.sendEvent(Event("page.display", data: [ // Event name "page": "page name", // Event properties "page_chapter1": "level 1", "page_chapter2": "level 2", "page_chapter3": "level 3" ])) ``` ### HTTP ```javascript const site_id = `123456789`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [ { name: "page.display", data: { page: "page name", page_chapter1: "level 1", page_chapter2: "level 2", page_chapter3: "level 3", }, }, ], }), }); ``` **What this tracking captures:** | Component | Value | Purpose | | -------------- | -------------------------------------- | --------------------------------- | | **Event** | page.display | Identifies this as a page view | | **Properties** | page: Page name | Primary page identifier | | | page_chapter1-3: Navigation hierarchy | Page categorization for reporting | **💡 Key insights from this data:** - Most popular pages and content - Navigation patterns and user flows - Content performance by category - Site structure effectiveness For complete setup instructions, see the [JavaScript SDK guide](/analytics/data-collection/sdks/javascript/). ### Example 2: Tracking User Interactions Beyond page views, you'll want to measure how users interact with your content. Here's how to track clicks with contextual information about where they occurred: ```html My Page ``` ```java pa.sendEvent(new Event("click.navigation", new HashMap() {{ // Event name put("click", "click name"); // Event properties put("click_chapter1", "click level 1"); put("click_chapter2", "click level 2"); put("click_chapter3", "click level 3"); put("page", "page name"); }})); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("click.navigation") .properties( Property(PropertyName("click"), "click name"), Property(PropertyName("click_chapter1"), "click level 1"), Property(PropertyName("click_chapter2"), "click level 2"), Property(PropertyName("click_chapter3"), "click level 3"), Property(PropertyName("page"), "page name"), ) .build() ) ``` ```swift pa.sendEvent(Event("click.navigation", data: [ // Event name "click": "click name", // Event properties "click_chapter1": "click level 1", "click_chapter2": "click level 2", "click_chapter3": "click level 3", "page": "page name" ])) ``` ```javascript const site_id = `123456789`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [ { name: "click.navigation", data: { click: "click name", // Event properties click_chapter1: "click level 1", click_chapter2: "click level 2", click_chapter3: "click level 3", page: "page name", }, }, ], }), }); ``` **What this tracking captures:** | Component | Value | Purpose | | -------------- | --------------------------------------- | ------------------------------------- | | **Event** | click.navigation | Identifies this as a navigation click | | **Properties** | click: Click name | What element was clicked | | | click_chapter1-3: Click categorization | Classification of the click type | | | page: Page context | Where the click occurred | **💡 Key insights from this data:** - Most engaged content and features - User interface effectiveness - Navigation patterns and preferences - Conversion funnel optimization opportunities --- ## Implementation methods Piano Analytics offers multiple integration methods to accommodate various technical environments and project requirements. This section outlines the available options, providing guidance to help you select the most suitable approach for your implementation. ## SDKs Software Development Kits (SDKs) provide streamlined interfaces for integrating Piano Analytics into your applications. By incorporating a lightweight library into your platform, you can leverage predefined methods to dispatch analytics events efficiently. Available SDKs include: | SDK | Platforms | | ----------------------------------------------------------------------------------- | ---------------------------------- | | [JavaScript](/analytics/data-collection/sdks/javascript/) | Websites or Apps through browsers. | | [iOS (Swift)](/analytics/data-collection/sdks/ios-swift/) | iOS native apps. | | [Android (Kotlin)](/analytics/data-collection/sdks/android-kotlin/) | Android native apps. (Kotlin SDK) | | [Flutter](/analytics/data-collection/sdks/flutter/) | Flutter mobile apps. | | [JavaScript (browserless)](/analytics/data-collection/sdks/javascript-browserless/) | Any platform supporting JS. | ### Advantages - Simplifies the tagging process. - Facilitates the management and transmission of platform-specific data. - Officially developed and maintained by Piano.​ ### Considerations - Compatibility is limited to supported platforms.​ If you want to send your first events using our SDKs, please use the [dedicated article](/analytics/data-collection/how-to-send-events/send-events-via-sdks/). ## Collection API The Collection API enables direct transmission of analytics events via HTTPS POST requests, offering a high degree of flexibility for custom implementations. This method is particularly advantageous when SDK integration is not feasible due to technological constraints. > tip: > > Server-side implementations can require implementations without SDKs, directly through the Collection API. This allows you to get rid of browsers and their limitations (client-side collection). ### Advantages - Highly customizable to fit specific requirements. - Operable across diverse platforms and environments.​ ### Considerations - Requires manual construction of event payloads. - Does not automatically capture native platform information. If you want to send your first events using our Collection API, please use the [dedicated article](/analytics/data-collection/how-to-send-events/collection-api/). ## Tag Management Systems Tag Management Systems offer a user-friendly interface for implementing and managing analytics tags across digital properties. They support both client-side and server-side tagging approaches. | | GOOGLE TAG MANAGER | TEALIUM | COMMANDERS ACT | | ----------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | Client-side | ✅[Documentation](https://github.com/at-internet/gtm-pa-tagging) | ✅[Documentation](https://docs.tealium.com/client-side-tags/at-internet-piano-analytics-tag/) | ✅ | | Server-side | ✅[Documentation](https://github.com/optimize-matter/piano-analytics-s2s) | ✅[Documentation](https://docs.tealium.com/server-side-connectors/at-internet-piano-analytics-connector/) | ✅[Documentation](https://community.commandersact.com/platform-x/features/destinations/destinations-catalog/at-internet) | ### Advantages - Centralized management of all tags. - Utilization of a robust common data layer. - Access to advanced features provided by TMS vendors. ### Considerations - Potentially reduced control over individual tagging configurations. ## Selecting the Appropriate Method ### SDKs Ideal for straightforward client-side integrations on supported platforms. Dedicated documentation for [JavaScript](/analytics/data-collection/sdks/javascript/), [iOS](/analytics/data-collection/sdks/ios-swift/), and [Android](/analytics/data-collection/sdks/android-kotlin/) SDKs. ### Collection API Suitable for scenarios requiring extensive customization or when operating in environments where SDKs are unsupported. Can be done with the [js browserless](/analytics/data-collection/sdks/javascript-browserless/) SDK or the [collection API](/analytics/data-collection/how-to-send-events/collection-api/) directly. ### Tag Management Systems Recommended if your organization already utilizes a TMS or seeks to leverage the additional features they offer. Each implementation method is comprehensively documented to assist you throughout the integration process. --- ## Migrate from SmartTag This guide outlines the process of transitioning from legacy SmartTag SDKs to the modern Piano Analytics SDKs, detailing differences in tagging methodologies, SDK lifecycles, and migration strategies. ## SDK and Tagging landscape Since 2015, [SmartTag SDKs](https://developers.atinternet-solutions.com/piano-analytics-tagging-en/getting-started-piano-analytics-en/what-is-piano-analytics-tagging-en/) SDKs have been implemented using two primary tagging approaches: - [AS2 Tagging](https://developers.atinternet-solutions.com/as2-tagging-en/javascript-en/getting-started-javascript-en/tracker-initialisation-javascript-en/) (2015) - Designed for the Analytics Suite 2, utilizing methods like `tag.page.set()` and tag.page.dispatch().​ - [PA Tagging](https://developers.atinternet-solutions.com/piano-analytics-tagging-en/getting-started-piano-analytics-en/what-is-piano-analytics-tagging-en/) (Winter 2020) - Introduced to align with the Piano Analytics event-based model, employing `tag.event.send()` for event tracking.​ As of April 2022, Piano Analytics SDKs are the standard for data collection, offering a streamlined, event-centric architecture. Support for SmartTag SDKs ceased in April 2023, with no further maintenance or feature updates. ## Before I start > attention: > > "xtor" marketing campaigns syntax will not be recognized anymore. Please use ["at_"](/analytics/data-collection/how-to-send-events/marketing-campaigns/) instead. ## Marketing Campaigns Migration ### SmartTag Smarttag previously relied on campaigns that had to be declared before it could be used. This configuration step, in addition to using predefined campaign types, allowed values sent in the URL to be transformed. So for example, the `xtor=AL` was automatically transformed into the Campaign Type `"Affiliation and partners"`. The ID of the campaign was then matched to its declared label in the configuration panel. > tip: > > Learn more on the dedicated [migration page for marketing campaigns](/analytics/data-collection/how-to-send-events/marketing-campaigns/) ### Piano Analytics SDK With the Piano Analytics SDK, the tag first approach is used instead, no matching is done and the data you send is the data you will later find in the different exploratory tools, without any need for prior configuration. > note: > > When sending `#xtor=SEC-2-GOO`, the `GOO` part was automatically translated to `Google Adwords`. When using the Piano Analytics SDK, `src_sl_platform=GOO` will no longer translate the value. If you need consistency when migrating, please use `Google Adwords` as the value instead. This tag first approach makes tracking marketing sources much more flexible, but it remains important to understand its core functioning for a proper migration from the Smarttag SDK. Piano Analytics uses the Data Model to populate data into their respective properties, it also uses the `at_*` marketing campaign format. > info: > > This `at_*` used for your different properties is going to be transformed into `src_*` by the tag directly. 1. When sending `at_type=gold`, you will populate the property Campaign/Organic, if you want to populate the Emailing/Affiliation/Campaign type, then please use the associated property in the data model. 2. When sending `at_medium=affiliate` & `at_aff_type=gold`. Will result in having `src_medium=affiliate` & `src_aff_type=gold` in the tag. Then using the data model you can see which property you'll have to use to find your data. ## Difference between tagging philosophies / SDKs The functionalities of our SDKs have followed the evolution of our audience measurement solution. Perfectly adapted to our legacy system, the SmartTag SDKs had to be adapted to the new Piano Analytics solution to allow you to send events and use your Data Model. This is what was enabled with the PA Tagging philosophy during winter 2020, while still using the old SmartTag SDKs. We then decided to start from scratch and redesign brand new SDKs that are based on our new Piano Analytics solution and event-based data model: | SmartTag (AS2 Tagging) | SmartTag (PA Tagging) | Piano Analytics SDKs | | ---------------------- | --------------------- | -------------------- | | ```javascript tag.page.set({ name: "My_page", level2: "sub_level", }); tag.setprops({ "d:article_date": 1646925124, "b:article_premium": false, }); tag.page.dispatch(); ``` | ```javascript tag.event.send('page.display', { 'page': 'My page' 'site_level2': 'sub level' , 'article_date': 1646925124, 'article_premium': false }); ``` | ```javascript pa.sendEvent('page.display', { 'page': 'My page' 'site_level2': 'sub level' , 'article_date': 1646925124, 'article_premium': false }); ``` | As you can see here, if you already tagged your perimeters with the SmartTag (PA Tagging) approach, migrating to Piano Analytics SDKs will not be heavy. It is the same event-based approach, with easier tagging methods and configurations. Piano Analytics SDKs come with: - A redesigned and easier tagging - A JS Browserless SDK to collect data in new environments - A new "Privacy by design" approach, the most advanced on the market - Dozens of improvements and new features ## Can I use both SDKs? You can. But both SDKs don't communicate, so Privacy configuration and users' ID are not shared. More information in the [dedicated article](/analytics/data-collection/general/cookie-storage/#legacy-cookie-management). ## Complete tagging example ### SmartTag - AS2 Tagging (2015) [documentation](https://developers.atinternet-solutions.com/as2-tagging-en/javascript-en/getting-started-javascript-en/tracker-initialisation-javascript-en/) ```html My Page ... ``` ### SmartTag - PA Tagging (Winter 2020) [documentation](https://developers.atinternet-solutions.com/piano-analytics-tagging-en/getting-started-piano-analytics-en/what-is-piano-analytics-tagging-en/) ```html My Page ... ``` ### Piano Analytics SDKs (April 2022) ```html My Page ... ``` --- ## Cookies & storage ## Client Side Cookies (JS SDK) | Name | Lifetime | Description | Is flag secure | Is flag SameSite | If deleted | | -------- | --------------------------------------- | ------------------------ | -------------- | ---------------- | ------------------------------------------------------------------------------------------ | | _pcid | 13 months by default, can be configured | Visitor ID | ✅ | SameSite=lax | New cookie set, new visitor ID assigned | | _pctx | 13 months by default, can be configured | Piano context storage | ✅ | SameSite=lax | No persistence of contextual information between Piano SDKs | | _pprv | 13 months by default, can be configured | Consent Mode persistence | ✅ | SameSite=lax | No persistence of Consent Mode, window.pdl.consent.defaultPreset.PA configuration assigned | | pa_user | 13 months by default, can be configured | Stored user information | ✅ | SameSite=lax | No persistence of user information information in events | Before 6.8.0 | Name | Lifetime | Description | Is flag secure | Is flag SameSite | If deleted | | ----------- | --------------------------------------- | ------------------------ | -------------- | ---------------- | ------------------------------------------------------------------------- | | pa_vid | 13 months by default, can be configured | Visitor ID | ✅ | SameSite=lax | New cookie set, new visitor ID assigned | | pa_user | 13 months by default, can be configured | Stored user information | ✅ | SameSite=lax | No persistence of user information information in events | | pa_privacy | 13 months by default, can be configured | Privacy Mode persistence | ✅ | SameSite=lax | No persistence of Privacy Mode, privacyDefaultMode configuration assigned | ### `_pcid` format The `_pcid` cookie may trigger OWASP security rules due to its structure: it contains a JSON object with special characters (quotes, colons, pipes) that are URL-encoded, which can be flagged by security scanners. The cookie value is URL-encoded and follows this pattern: `%7B%22browserId%22%3A%22mg0j6i6ct4vxgjb9%22%2C%22_t%22%3A%22mwj35h8y%7Cmgum2u4y%22%7D` When URL-decoded and formatted, the cookie contains a JSON object: ```json { "browserId": "mg0j6i6ct4vxgjb9", // Unique visitor identifier (random alphanumeric value) "_t": "mwj35h8y|mgum2u4y" // Encoded timestamp for cookie duration manipulation } ``` This cookie uses a JSON structure to allow end-users to easily retrieve their identifier for GDPR compliance purposes. Storing this data in a cookie allows it to naturally expire after the configured lifetime (13 months by default). ## Server Side Cookies | Name | Lifetime | Description | Secure flag | SameSite flag | HTTPOnly flag | If deleted | | ------ | --------- | ----------------------------- | ----------- | ------------- | ------------- | --------------------------------------- | | idrxvr | 13 months | Legacy Server Side Visitor ID | ❌ | ❌ | ✅ | New cookie set, new visitor ID assigned | | atidx | 13 months | Server Side Visitor ID | ✅ | ❌ | ✅ | New cookie set, new visitor ID assigned | | atid | 13 months | Main Server Side Visitor ID | ✅ | SameSite=none | ✅ | New cookie set, new visitor ID assigned | ## Piano Analytics Mobile SDKs ### Android | Storage key | Lifetime | Description | | ------------- | --------------------------------------- | ------------------------ | | pa_vid | 13 months by default, can be configured | Visitor ID | | pa_uid | 13 months by default, can be configured | Stored user information | | pa_privacy | 13 months by default, can be configured | Privacy Mode persistence | | pa_crash | Until app relaunch | Crash information | | pa_lifecycle | No expiration | Application lifecycle | ### Apple | Storage key | Lifetime | Description | | ------------- | --------------------------------------- | ------------------------ | | pa_vid | 13 months by default, can be configured | Visitor ID | | pa_uid | 13 months by default, can be configured | Stored user information | | pa_privacy | 13 months by default, can be configured | Privacy Mode persistence | | pa_crash | Until app relaunch | Crash information | | pa_lifecycle | No expiration | Application lifecycle | ## Piano Cookies This page covers the Piano Analytics cookies, you can also find the cookies used for the other Piano products [here](https://docs.piano.io/track/piano-cookie-descriptions/#menu40630) ## Legacy cookie management If you're migrating from SmartTag SDKs to Piano Analytics SDKs, we still use the `atuserid` cookie (visitor identification) so as not to cause a break in the detection of the visitor. As soon as this `atuserid` cookie is deleted, we replace it with `_pcid` cookie. Same applies to `pa_vid` (legacy value of PA SDK visitor cookie ID). The `atauthority` cookie (Privacy) is not used anymore. Please implement [Consent methods](/analytics/data-collection/how-to-send-events/consent/) to deposit the new `_pprv` cookie instead (or [Privacy methods](/analytics/data-collection/how-to-send-events/privacy/) if your use mobile SDKs). Same applies for legacy `atidvisitor` cookie ("identified visitor" detection, now "user"). Please implement [Users methods](/analytics/data-collection/how-to-send-events/users/) to deposit the new `pa_user` cookie instead. --- ## Activation Insights Activation Insights offers analysis dedicated to your Activation performance. This article will present you how it works and how to get the best out of your implementation. ## How it works Activation Insights merge data from various Piano products into Piano Analytics data model. To provide a comprehensive understanding of how Activation Insights work, let's break down the process step-by-step: 1. Piano SDKs implemented on the application (web, mobile, ...) send events to Piano backends. These events include user interactions and other relevant data points that help track the activation journey. All those events share 2 key IDs allowing us to correlate them across different systems: 1. Browser ID: also called Visitor ID, represents a unique ID linked to a specific browser. (`idclient` querystring property) 2. Pageview ID: this unique ID is generated for each pageview or screen view within an application and links all events that occur on the same page or screen. (`pageview_id` event property) 2. Activation backends process these events, enrich them and send them to Piano Analytics. 3. These events are then processed by Piano Analytics, which uses advanced algorithms to analyze patterns, user journeys, and interactions. ## Implementation ### JavaScript JavaScript SDKs automatically share Pageview ID (`pageview_id`) and Browser ID (`idclient`) since version 6.7.0. ### Android (3.3.0+) - Browser ID: you need to set the same browser ID for both Composer SDK and Analytics SDK: - Set: - `Composer.getInstance().browserIdProvider { "" }` - `PianoAnalytics.getInstance().customVisitorId = ""` ([documentation](/analytics/data-collection/how-to-send-events/visitor-identification/#visitor-identification-management)) - Get: - `val visitorId = PianoAnalytics.getInstance().visitorId` ([documentation](/analytics/data-collection/how-to-send-events/visitor-identification/#visitor-identification-management)) - Pageview ID: you need to retrieve the pageview ID generated by Composer SDK to push it in every events: ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder(...) .properties( ... Property(PropertyName("pageview_id"), Composer.getInstance().pageViewId.orEmpty()), ) .build() ) ``` ### Apple - Browser ID: you need to set the same browser ID and pageview ID for both Composer SDK and Analytics SDK: - Composer: ```swift PianoComposer(...) ... .browserId("") .pageViewId("") .execute() ``` ```text - Analytics: - Browser ID: - Set: `pa.setVisitorId("")` ([documentation](/analytics/data-collection/how-to-send-events/visitor-identification.md#visitor-identification-management)) - Get: `pa.getVisitorId { visitorId in print(visitorId) }` ([documentation](/analytics/data-collection/how-to-send-events/visitor-identification.md#visitor-identification-management)) - Pageview ID: ```swift PianoAnalytics.shared.sendEvent( Event( "...", properties: [ Property("pageview_id", "") ] ) ) ``` --- ## AV Insights (audio video) AV Insights allows the collection of events related to media consumption. You will be able to follow the different interactions on your players and measure the performance of your content. The AV Insight tracker is designed to give you options on the level of information you want to measure. ## Media management ### Media instantiation In order to be able to manipulate a media and measure its events, it is necessary to declare an object: ### JavaScript ```js var myMedia = new pa.avInsights.Media([ heartbeatDuration, bufferingHeartbeatDuration, sessionId, ]); ``` | Parameter | Type | Description | Example | | ------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------- | | heartbeatDuration (optional) | int, object | Delay between two heartbeat during playback (minimum delay is 5sec).If the value is a int, this will be the delay for the whole playback.If the value is an object such as { 0:5, 1:10, 5:60 }, meaning the first minute will be 5sec delay, starting from minute 1, 10sec, and after the 5th minute, the delay will be 60sec.A value of 0 means no heartbeat. If set in an object format, heartbeats will stop for the rest of the video. | 5 or { 0:5, 1:10, 5:60, 120:0 } | | bufferingHeartbeatDuration (optional) | int, object | Delay between two heartbeat during buffering (minimum delay is 1sec).If the value is a int, this will be the delay for the whole buffering.If the value is an object such as { 0:5, 1:10, 5:60 }, meaning the first minute will be 5sec delay, starting from minute 1, 10sec, and after the 5th minute, the delay will be 60sec.A value of 0 means no heartbeat. If set in an object format, heartbeats will stop for the rest of the buffering. | 5 or { 0:5, 1:10, 5:60, 10:0 } | | sessionId (optional) | string | Session ID of the playback. This ID is automatically managed by the SDK, but you can override it if you know what you are doing. More details in the next section. | "97fb0ee6-7b86-4ffa-a69f-e32a04d40bbf" | ```js var myMedia = new pa.avInsights.Media(5, 5); // or var myMedia = new pa.avInsights.Media({ 0: 5, 1: 10, 5: 60, 120: 0 }, 5); ``` > note: > > Two parameters are available, in order to activate the heartbeats. The first one enables playback tracking heartbeats and the second one enables buffering tracking heartbeats. ### Android (3.3.0+) Declare your heartbeat delays and content ID thanks to `MediaHelper` class: ```kotlin val heartbeat = SparseLongArray() // first minute will be 5sec delay heartbeat.put(0, 5) // starting from minute 1, 10sec heartbeat.put(1, 10) // and after the 5th minute, the delay will be 60sec heartbeat.put(5, 60) val bufferHeartbeat = SparseLongArray() bufferHeartbeat.put(0, 5) val myMedia = PianoAnalytics.getInstance() .mediaHelper("fg456") // Content ID .setHeartbeat(heartbeat) .setBufferHeartbeat(bufferHeartbeat) ``` ### Android ```swift var myMedia = AVMedia(pa: PianoAnalytics, sessionId: String? = nil) ``` | Parameter | Type | Description | Example | | -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | pa | PianoAnalytics | Tracker instance | pa | | sessionId (optional) | String? | Session ID of the playback. This ID is automatically managed by the SDK, but you can override it if you know what you are doing. More details in the next section. | \- | ```swift var myMedia = AVMedia(pa: pa) ``` To set up automatic heartbeat management, call the dedicated methods: `myMedia.setHeartbeat(heartbeat: [Int: Int]?)` | Parameter | Type | Description | Example | | --------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | | heartbeat | \[Int: Int\]? | Delay between two heartbeat during playback (minimum delay is 5sec). You can set a map such as \[0:5, 1:10, 5:60\], meaning the first minute will be 5sec delay, starting from minute 1, 10sec, and after the 5th minute, the delay will be 60sec | \[0:5, 1:10, 5:60\] | ```swift myMedia.setHeartbeat(heartbeat: [ 0: 5, 1: 10, 5: 60 ]) ``` `myMedia.setBufferHeartbeat(bufferHeartbeat: [Int: Int]?)` | Parameter | Type | Description | Example | | --------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | | bufferHeartbeat | \[Int: Int\]? | Delay between two heartbeat during buffering (minimum delay is 1sec). You can set a map such as \[0:5, 1:10, 5:60\], meaning the first minute will be 5sec delay, starting from minute 1, 10sec, and after the 5th minute, the delay will be 60sec | \[0:5, 1:10, 5:60\] | ```swift myMedia.setBufferHeartbeat(bufferHeartbeat: [ 0: 5, 1: 10, 5: 60 ]) ``` ### Apple Begin by importing `io.piano.analytics.avinsights.Media` into your file: ```java import io.piano.analytics.avinsights.Media; ``` In order to be able to manipulate a media and measure its events, it is necessary to declare an object of type `Media` : ```java Media myMedia = new Media(pa); // or Media myMedia = new Media(pa, sessionId); ``` | Parameter | Type | Description | Example | | -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | pa | PianoAnalytics | Tracker instance | pa | | sessionId (optional) | String | Session ID of the playback. This ID is automatically managed by the SDK, but you can override it if you know what you are doing. More details in the next section. | \- | To set up automatic heartbeat management, call the dedicated methods: `myMedia.setHeartbeat(heartbeat)` | Parameter | Type | Description | Example | | --------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | | heartbeat | SparseIntArray | Delay between two heartbeat during playback (minimum delay is 5sec). You can set a map such as \[0:5, 1:10, 5:60\], meaning the first minute will be 5sec delay, starting from minute 1, 10sec, and after the 5th minute, the delay will be 60sec | \[0:5, 1:10, 5:60\] | ```java myMedia.setHeartbeat(new SparseIntArray() .append(0, 5) .append(1, 10) .append(5, 60) ); ``` `myMedia.setBufferHeartbeat(bufferHeartbeat)` | Parameter | Type | Description | Example | | --------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | | bufferHeartbeat | SparseIntArray | Delay between two heartbeat during buffering (minimum delay is 1sec). You can set a map such as \[0:5, 1:10, 5:60\], meaning the first minute will be 5sec delay, starting from minute 1, 10sec, and after the 5th minute, the delay will be 60sec | \[0:5, 1:10, 5:60\] | ```java myMedia.setBufferHeartbeat(new SparseIntArray() .append(0, 5) .append(1, 10) .append(5, 60) ); ``` #### Session ID management > warning: > > Please note that this setup should be used only in special cases, when you need to transfer sessions between different devices, for example. An optional third parameter `sessionId` is available to override the common standard property `av_session_id` present in each event generated by AV Insights tags. The parameter is automatically managed by the SDK for all standard cases. ```js var myMedia = new pa.avInsights.Media(5, 5, "custom_session_id"); ``` A function `getSessionID` can be used to retrieve the value of the parameter: `getSessionID() ⇒ string | number` *Retrieve the session ID.* Example ```js var sessionID = myMedia.getSessionID(); // 'custom_session_id' or 'xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxx' ``` An optional second parameter `mediaSessionId` is available to override the common standard property `av_session_id` present in each event generated by AV Insights tags. The parameter is automatically managed by the SDK for all standard cases. ```kotlin val myMedia = PianoAnalytics.getInstance().mediaHelper("contentId", "custom-session-id") ``` An optional second parameter `sessionId` is available to override the common standard property `av_session_id` present in each event generated by AV Insights tags. The parameter is automatically managed by the SDK for all standard cases. ```java Media myMedia = new Media(pa, "custom-session-id"); ``` An optional second parameter `sessionId` is available to override the common standard property `av_session_id` present in each event generated by AV Insights tags. The parameter is automatically managed by the SDK for all standard cases. ```swift var myMedia = new AVMedia(pa: pa, sessionId: "custom-session-id") ``` ### Media properties Some rules must be observed regarding the format of the properties used for the configuration of a media : - The `av_content_id` is a mandatory property that must be used for all media instances ([see complete tagging example section](#complete-tagging-example)). - The duration of the media or the positions of the playback head must be expressed in *milliseconds*. The SDK provides useful functions for the management of Media properties: `set(propKey, propValue)` *Declare a media property.* | Parameter | Type | Description | | --------- | -------------- | -------------------- | | propKey | string | Media property key | | propValue | string, number | Media property value | Example ```js myMedia.set("av_content_id", "fg456"); // mandatory myMedia.set("av_content", "my_video"); ``` `get(propKey) ⇒ string | number` *Retrieve a media property.* | Parameter | Type | Description | | --------- | ------ | ------------------ | | propKey | string | Media property key | Example ```js var content_id = myMedia.get("av_content_id"); // fg456 ``` `del(propKey)` *Delete a media property.* | Parameter | Type | Description | | --------- | ------ | ------------------ | | propKey | string | Media property key | Example ```js myMedia.del("av_content_id"); ``` `setProps(properties)` *Declare multiple media properties.* | Parameter | Type | Description | | ---------- | ------ | ---------------- | | properties | Object | Media properties | Example ```js myMedia.setProps({ av_content_id: "fg456", av_content: "My Content" }); ``` `getProps() ⇒ Object` *Retrieve all media properties.* Example ```js var props = myMedia.getProps(); // {'av_content_id': 'fg456', 'av_content': 'My Content'} ``` `delProps()` *Delete all media properties.* Example ```js myMedia.delProps(); ``` ```kotlin myMedia.setExtraProps( Property(PropertyName("av_content"), "my_video") Property(PropertyName("av_content_duration"), 2760000) ) ``` You need to manage your [media properties](#media-properties-list) to send them on every events, through the `extraProps` parameter of dedicated methods. You need to manage your [media properties](#media-properties-list) to send them on every events, through the `extraProps` parameter of dedicated methods. For automatic events (e.g. heartbeats), use the `setExtraProperties` method to set media properties: ```swift myMedia.setExtraProperties([ "av_content": "my_video", "av_content_duration": 2760000 ]) ``` ## Events tracking The SDK offers useful functions for measuring events related to your users’ interactions with your content: ### Media events #### play Event name : `av.play` *Generate a play event (playback attempt).* `play(cursorPosition[, callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | cursorPosition | number | Current cursor position (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.play( 0, function () { console.log("Event av.play generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.play( 0, Property(...), Property(...) ) ``` `func Media.play(cursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.play( 0, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.play(cursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.play( cursorPosition: 0, extraProps: [ "av_content": "Content title", ... ] ) ``` #### bufferStart Event name : `av.buffer.start` or `av.rebuffer.start` *Generate an event of buffering at the launch of a media or during the playing. The `buffering.heartbeat` is sent before the `av.start` while the `rebuffering.heartbeat` is sent after an `av.start` is recorded on the `av_session_id`.* `bufferStart(cursorPosition[, callback, extraProps])` A buffering flag will automatically generate `buffering.heartbeat` or `rebuffering.heartbeat` events depending on the context. | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | cursorPosition | number | Current cursor position (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.bufferStart( 0, function () { console.log( "Event av.buffer.start or av.rebuffer.start generated depending on the playback launch" ); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.bufferStart( 0, Property(...), Property(...) ) ``` `func Media.bufferStart(cursorPosition, extraProps)` A buffering flag will automatically generate `buffering.heartbeat` or `rebuffering.heartbeat` events depending on the context. | Parameter | Type | Description | | --------------------- | -------------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.bufferStart( 0, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.bufferStart(cursorPosition: Int, extraProps: [String: Any]?)` A buffering flag will automatically generate `buffering.heartbeat` or `rebuffering.heartbeat` events depending on the context. | Parameter | Type | Description | | --------------------- | ---------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.bufferStart( cursorPosition: 0, extraProps: [ "av_content": "Content title", ... ] ) ``` #### playbackStart Event name : `av.start` *Generate a playback start event (first media frame). This allows the automatic `av.heartbeat` events (designed to accurately track the playback time) to be sent. These `av.heartbeat` events follow the media instance configuration.* `playbackStart(cursorPosition[, callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | cursorPosition | number | Current cursor position (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.playbackStart( 0, function () { console.log("Event av.start generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.playbackStart( 0, Property(...), Property(...) ) ``` `func Media.playbackStart(cursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.playbackStart( 0, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.playbackStart(cursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.playbackStart( cursorPosition: 0, extraProps: [ "av_content": "Content title", ... ] ) ``` #### playbackPaused Event name : `av.pause` *Generate a pause event.* `playbackPaused(cursorPosition[, callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | cursorPosition | number | Current cursor position (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.playbackPaused( 1000, function () { console.log("Event av.pause generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.playbackPaused( 1000, Property(...), Property(...) ) ``` `func Media.playbackPaused(cursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.playbackPaused( 1000, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.playbackPaused(cursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.playbackPaused( cursorPosition: 1000, extraProps: [ "av_content": "Content title", ... ] ) ``` #### playbackResumed Event name : `av.resume` *Generate a resume event, following a pause event.* `playbackResumed(cursorPosition[, callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | cursorPosition | number | Current cursor position (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.playbackResumed( 1000, function () { console.log("Event av.resume generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.playbackResumed( 1000, Property(...), Property(...) ) ``` `func Media.playbackResumed(cursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.playbackResumed( 1000, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.playbackResumed(cursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.playbackResumed( cursorPosition: 1000, extraProps: [ "av_content": "Content title", ... ] ) ``` #### playbackStopped Event name : `av.stop` *Generate a stop event. Automatically changes the `av_session_id`.* `playbackStopped(cursorPosition[, callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | cursorPosition | number | Current cursor position (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.playbackStopped( 1000, function () { console.log("Event av.stop generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.playbackStopped( 1000, Property(...), Property(...) ) ``` `func Media.playbackStopped(cursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.playbackStopped( 1000, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.playbackStopped(cursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ---------------------------- | | cursorPosition | Int | Current cursor position (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.playbackStopped( cursorPosition: 1000, extraProps: [ "av_content": "Content title", ... ] ) ``` #### seek Event name : `av.forward` or `av.backward` *Generate a seek event. `av.backward` is sent whenever the user goes back to an already seen cursorPosition. `av.forward` whenever the user goes past the current cursorPosition.* `seek(oldCursorPosition, newCursorPosition[, callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | oldCursorPosition | number | Cursor position before seeking (ms) | | newCursorPosition | number | Cursor position after seeking (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.seek( 1000, 2000, function () { console.log("Event av.forward generated"); }, { customProp: "customValue" } ); myMedia.seek( 2000, 1000, function () { console.log("Event av.backward generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.seek( 1000, 2000, Property(...), Property(...) ) myMedia.seek( 2000, 1000, Property(...), Property(...) ) ``` `func Media.seek(oldCursorPosition, newCursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.seek( 1000, 2000, new HashMap() {{ put("av_content", "Content title"); ... }} ); myMedia.seek( 2000, 1000, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.seek(oldCursorPosition: Int, newCursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.seek( oldCursorPosition: 1000, newCursorPosition: 2000, extraProps: [ "av_content": "Content title", ... ] ) myMedia.seek( oldCursorPosition: 2000, newCursorPosition: 1000, extraProps: [ "av_content": "Content title", ... ] ) ``` #### playbackKill This method doesn't generate any events. *It is intended to be used for very specific use cases. This method will kill the current playback session, including all timers for heartbeats, without generating any events. It should only be called when absolutely necessary: we highly recommend using `playbackStopped()` instead.* `playbackKill()` Example ```js myMedia.playbackKill(); ``` ### Contextual events The following list of events is not taken into account in the calculation of media consumption times. They are one-time contextual events. #### Playback speed When changing the playback speed you have to use the dedicated method specifying the new speed factor as a decimal number. Method: `setPlaybackSpeed(playbackSpeed)` *Declare a change in playback speed.* | Parameter | Type | Description | | ------------- | ------ | --------------------- | | playbackSpeed | number | Playback speed factor | Example ```js myMedia.setPlaybackSpeed(2); // Media playback speed increased by a factor of two ``` | Parameter | Type | Description | | ------------- | ------ | --------------------- | | playbackSpeed | Double | Playback speed factor | ```kotlin myMedia.playbackSpeed = 2.0 ``` `func Media.setPlaybackSpeed(playbackSpeed)` *Declare a change in playback speed.* | Parameter | Type | Description | | ------------- | ------ | --------------------- | | playbackSpeed | Double | Playback speed factor | Example ```java myMedia.setPlaybackSpeed(2.0); // Media playback speed increased by a factor of two ``` `myMedia.playbackSpeed: Double = playbackSpeed` *Declare a change in playback speed.* | Parameter | Type | Description | | ------------- | ------ | --------------------- | | playbackSpeed | Double | Playback speed factor | Example ```swift myMedia.playbackSpeed = 2.0 // Media playback speed increased by a factor of two ``` The new playback speed factor will be taken into account when calculating the cursor positions of automated `heartbeats` events during playback. If necessary, you can tag the event associated with this speed change by using the `speed()` method. #### adClick Event name : `av.ad.click` *Generate an ad click event.* `adClick([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.adClick( function () { console.log("Event av.ad.click generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.adClick( Property(...), Property(...) ) ``` `func Media.adClick(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.adClick( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.adClick(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.adClick( extraProps: [ "av_content": "Content title", ... ] ) ``` #### adSkip Event name : `av.ad.skip` *Generate an ad skip event.* `adSkip([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.adSkip( function () { console.log("Event av.ad.skip generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.adSkip( Property(...), Property(...) ) ``` `func Media.adSkip(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.adSkip( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.adSkip(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.adSkip( extraProps: [ "av_content": "Content title", ... ] ) ``` #### close Event name : `av.close` *Measure a closing.* `close([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.close( function () { console.log("Event av.close generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.close( Property(...), Property(...) ) ``` `func Media.close(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.close( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.close(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.close( extraProps: [ "av_content": "Content title", ... ] ) ``` #### display Event name : `av.display` *Measure a display.* `display([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.display( function () { console.log("Event av.display generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.display( 1000, Property(...), Property(...) ) ``` `func Media.display(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.display( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.display(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.display( extraProps: [ "av_content": "Content title", ... ] ) ``` #### error Event name : `av.error` *Measure an error preventing playback.* `error(message[, callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | message | string | Error message | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.error( "Error loading video", function () { console.log("Event av.error generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | message | String | Error message | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.error( "Error loading video", Property(...), Property(...) ) ``` `func Media.error(message, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | message | String | Error message | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.error( "Error loading video", new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.error(message: String, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | message | String | Error message | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.error( "Error loading video", extraProps: [ "av_content": "Content title", ... ] ) ``` #### fullscreenOff Event name : `av.fullscreen.off` *Measure full screen deactivation.* `fullscreenOff([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.fullscreenOff( function () { console.log("Event av.fullscreen.off generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.fullscreenOff( Property(...), Property(...) ) ``` `func Media.fullscreenOff(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.fullscreenOff( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.fullscreenOff(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.fullscreenOff( extraProps: [ "av_content": "Content title", ... ] ) ``` #### fullscreenOn Event name : `av.fullscreen.on` *Measure full screen activation.* `fullscreenOn([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.fullscreenOn( function () { console.log("Event av.fullscreen.on generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.fullscreenOn( 1000, Property(...), Property(...) ) ``` `func Media.fullscreenOn(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.fullscreenOn( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.fullscreenOn(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.fullscreenOn( extraProps: [ "av_content": "Content title", ... ] ) ``` #### quality Event name : `av.quality` *Measure a quality change.* `quality([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.quality( function () { console.log("Event av.quality generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.quality( Property(...), Property(...) ) ``` `func Media.quality(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.quality( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.quality(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.quality( extraProps: [ "av_content": "Content title", ... ] ) ``` #### share Event name : `av.share` *Measure a sharing.* `share([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.share( function () { console.log("Event av.share generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.share( Property(...), Property(...) ) ``` `func Media.share(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.share( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.share(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.share( extraProps: [ "av_content": "Content title", ... ] ) ``` #### speed Event name : `av.speed` *Measure a speed change.* `speed([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.speed( function () { console.log("Event av.speed generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.speed( Property(...), Property(...) ) ``` `func Media.speed(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.speed( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.speed(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.speed( extraProps: [ "av_content": "Content title", ... ] ) ``` #### subtitleOff Event name : `av.subtitle.off` *Measure subtitles deactivation* `subtitleOff([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.subtitleOff( function () { console.log("Event av.subtitle.off generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.subtitleOff( Property(...), Property(...) ) ``` `func Media.subtitleOff(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.subtitleOff( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.subtitleOff(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.subtitleOff( extraProps: [ "av_content": "Content title", ... ] ) ``` #### subtitleOn Event name : `av.subtitle.on` *Measure subtitles activation.* `subtitleOn([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.subtitleOn( function () { console.log("Event av.subtitle.on generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.subtitleOn( Property(...), Property(...) ) ``` `func Media.subtitleOn(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.subtitleOn( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.subtitleOn(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.subtitleOn( extraProps: [ "av_content": "Content title", ... ] ) ``` #### volume Event name : `av.volume` *Measure sound volume change.* `volume([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.volume( function () { console.log("Event av.volume generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.volume( Property(...), Property(...) ) ``` `func Media.volume(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.volume( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.volume(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.volume( extraProps: [ "av_content": "Content title", ... ] ) ``` ### Technical events The following events are automatically generated by the Tracker. You can, however, call up the associated public marking methods if you need spot marking. Should the implementation be done without the SDK *(server-side)*, you would have to generate the following events manually. #### bufferHeartbeat Event name : `av.buffer.heartbeat` *Generate a buffering heartbeat before the playback starts event.* `bufferHeartbeat([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.bufferHeartbeat( function () { console.log("Event av.buffer.heartbeat generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.bufferHeartbeat( Property(...), Property(...) ) ``` `func Media.bufferHeartbeat(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.bufferHeartbeat( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.bufferHeartbeat(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.bufferHeartbeat( extraProps: [ "av_content": "Content title", ... ] ) ``` #### heartbeat Event name: `av.heartbeat` *Generate an heartbeat event. Event used to accurately track the playback time preferably sent at regular intervals when the content is actively playing.* `heartbeat([cursorPosition, callback, extraProps])` | Parameter | Type | Description | | ------------------------- | -------- | ------------------------------------------- | | cursorPosition (optional) | number | Current cursor position (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.heartbeat( 45, function () { console.log("Event av.heartbeat generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.heartbeat( Property(...), Property(...) ) ``` `func Media.heartbeat(cursorPosition, extraProps)` | Parameter | Type | Description | | ------------------------- | -------------------- | ---------------------------- | | cursorPosition (optional) | number | Current cursor position (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.heartbeat( 45, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.heartbeat(cursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | ------------------------- | ---------------- | ---------------------------- | | cursorPosition (optional) | number | Current cursor position (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.heartbeat( cursorPosition: 45, extraProps: [ "av_content": "Content title", ... ] ) ``` > note: > > The cursor position is not mandatory for tagging a `heartbeat` event. Without any value, it will be automatically calculated according to the context (playback speed factor, cursor position of the previous event). #### rebufferHeartbeat Event name : `av.rebuffer.heartbeat` *Generate a buffering heartbeat after the playback starts event.* `rebufferHeartbeat([callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.rebufferHeartbeat( function () { console.log("Event av.rebuffer.heartbeat generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------- | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.rebufferHeartbeat( Property(...), Property(...) ) ``` `func Media.rebufferHeartbeat(extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------- | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.rebufferHeartbeat( new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.rebufferHeartbeat(extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------- | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.rebufferHeartbeat( extraProps: [ "av_content": "Content title", ... ] ) ``` #### seekStart Event name : `av.seek.start` *Generate a beginning of seeking event.* `seekStart(oldCursorPosition, [callback, extraProps])` > note: > > This event is automatically raised when calling the `seek()`, `seekBackward()` or `seekForward()` methods. | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | oldCursorPosition | number | Cursor position before seeking (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.seekStart( 1000, function () { console.log("Event av.seek.start generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ---------------------------- | | oldCursorPosition | Int | Current cursor position (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.seekStart( 1000, Property(...), Property(...) ) ``` `func Media.seekStart(oldCursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.seekStart( 1000, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.seekStart(oldCursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.seekStart( oldCursorPosition: 1000, extraProps: [ "av_content": "Content title", ... ] ) ``` #### seekBackward Event name : `av.backward` *Generate a backward seeking event.* `seekBackward(oldCursorPosition, newCursorPosition, [callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | oldCursorPosition | number | Cursor position before seeking (ms) | | newCursorPosition | number | Cursor position after seeking (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.seekBackward( 2000, 1000, function () { console.log("Event av.backward generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.seekBackward( 2000, 1000, Property(...), Property(...) ) ``` `func Media.seekBackward(oldCursorPosition, newCursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.seekBackward( 2000, 1000, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.seekBackward(oldCursorPosition: Int, newCursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.seekBackward( oldCursorPosition: 2000, newCursorPosition: 1000, extraProps: [ "av_content": "Content title", ... ] ) ``` #### seekForward Event name : `av.forward` *Generate a forward seeking event.* `seekForward(oldCursorPosition, newCursorPosition, [callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ------------------------------------------- | | oldCursorPosition | number | Cursor position before seeking (ms) | | newCursorPosition | number | Cursor position after seeking (ms) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js myMedia.seekForward( 1000, 2000, function () { console.log("Event av.forward generated"); }, { customProp: "customValue" } ); ``` | Parameter | Type | Description | | ---------------------------- | -------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | properties vararg (optional) | Property | Custom properties | ```kotlin myMedia.seekForward( 1000, 2000, Property(...), Property(...) ) ``` `func Media.seekForward(oldCursorPosition, newCursorPosition, extraProps)` | Parameter | Type | Description | | --------------------- | -------------------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | extraProps (optional) | Map? | Custom properties | Example ```java myMedia.seekForward( 1000, 2000, new HashMap() {{ put("av_content", "Content title"); ... }} ); ``` `myMedia.seekForward(oldCursorPosition: Int, newCursorPosition: Int, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ----------------------------------- | | oldCursorPosition | Int | Cursor position before seeking (ms) | | newCursorPosition | Int | Cursor position after seeking (ms) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.seekForward( oldCursorPosition: 1000, newCursorPosition: 2000, extraProps: [ "av_content": "Content title", ... ] ) ``` ## Complete tagging example ```js var myMedia = new pa.avInsights.Media({ 0: 5, 1: 10, 5: 60, 120: 0 }, 5); // Set heartbeats value var properties = { av_content_id: "fge234", //mandatory av_content: "myContent", av_content_type: "Video", av_content_duration: 10000, av_content_genre: ["entertainment"], av_content_version: "short", av_player: "HTML5_V123", av_player_version: "1b", av_player_position: "top", av_broadcasting_type: "On Demand", av_publication_date: 1562055880, av_show: "The gist of the game", av_show_season: "Season 1", av_episode_id: "3134", av_channel: "INFO", av_author: "Piano", av_broadcaster: "Direction 123", av_language: "EN", av_subtitles: "FR", av_launch_reason: "Auto", }; // Set media properties myMedia.setProps(properties); // Play attempt (cursor position 0 second) myMedia.play(0); // Buffering before playback start (cursor position 0 second) myMedia.bufferStart(0); // Playback start (cursor position 0 second) myMedia.playbackStart(0); // Buffering after 5 seconds of playback myMedia.bufferStart(5000); // Seek action (backward from cursor position 5 seconds to cursor position 3 seconds) myMedia.seek(5000, 3000); // Playback resume (cursor position 3 seconds) myMedia.playbackResumed(3000); // Playback pause (cursor position 9 seconds) myMedia.playbackPaused(9000); // Playback resume (cursor position 9 seconds) myMedia.playbackResumed(9000); // Playback stop (cursor position 15 seconds) myMedia.playbackStopped(15000); ``` ```kotlin val heartbeat = SparseLongArray() // first minute will be 5sec delay heartbeat.put(0, 5) // starting from minute 1, 10sec heartbeat.put(1, 10) // and after the 5th minute, the delay will be 60sec heartbeat.put(5, 60) val bufferHeartbeat = SparseLongArray() bufferHeartbeat.put(0, 5) val myMedia = PianoAnalytics.getInstance() .mediaHelper("fge234") .setHeartbeat(heartbeat) .setBufferHeartbeat(bufferHeartbeat) val properties = arrayOf( Property(PropertyName("av_content"), "myContent"), Property(PropertyName("av_content_type"), "Video"), Property(PropertyName("av_content_duration"), 10000), Property(PropertyName("av_content_genre"), arrayOf("entertainment")), Property(PropertyName("av_content_version"), "short"), Property(PropertyName("av_player"), "HTML5_V123"), Property(PropertyName("av_player_version"), "1b"), Property(PropertyName("av_player_position"), "top"), Property(PropertyName("av_broadcasting_type"), "On Demand"), Property(PropertyName("av_publication_date"), 1562055880), Property(PropertyName("av_show"), "The gist of the game"), Property(PropertyName("av_show_season"), "Season 1"), Property(PropertyName("av_episode_id"), "3134"), Property(PropertyName("av_channel"), "INFO"), Property(PropertyName("av_author"), "Piano"), Property(PropertyName("av_broadcaster"), "Direction 123"), Property(PropertyName("av_language"), "EN"), Property(PropertyName("av_subtitles"), "FR"), Property(PropertyName("av_launch_reason"), "Auto"), ) myMedia.setExtraProps(*properties) // Play attempt (cursor position 0 second) myMedia.play(0, *properties) // Buffering before playback start (cursor position 0 second) myMedia.bufferStart(0, *properties) // Playback start (cursor position 0 second) myMedia.playbackStart(0, *properties) // Buffering after 5 seconds of playback myMedia.bufferStart(5000, *properties) // Seek action (backward from cursor position 5 seconds to cursor position 3 seconds) myMedia.seek(5000, 3000, *properties) // Playback resume (cursor position 3 seconds) myMedia.playbackResumed(3000, *properties) // Playback pause (cursor position 9 seconds) myMedia.playbackPaused(9000, *properties) // Playback resume (cursor position 9 seconds) myMedia.playbackResumed(9000, *properties) // Playback stop (cursor position 15 seconds) myMedia.playbackStopped(15000, *properties) ``` ```java Media myMedia = new Media(pa); HashMap properties = new HashMap() {{ put("av_content_id", "fge234"); //mandatory put("av_content", "myContent"); put("av_content_type", "Video"); put("av_content_duration", 10000); put("av_content_genre", new String[]{"entertainment"}); put("av_content_version", "short"); put("av_player", "HTML5_V123"); put("av_player_version", "1b"); put("av_player_position", "top"); put("av_broadcasting_type", "On Demand"); put("av_publication_date", 1562055880); put("av_show", "The gist of the game"); put("av_show_season", "Season 1"); put("av_episode_id", "3134"); put("av_channel", "INFO"); put("av_author", "Piano"); put("av_broadcaster", "Direction 123"); put("av_language", "EN"); put("av_subtitles", "FR"); put("av_launch_reason", "Auto"); }}; // Play attempt (cursor position 0 second) myMedia.play(0, properties); // Buffering before playback start (cursor position 0 second) myMedia.bufferStart(0, properties); // Playback start (cursor position 0 second) myMedia.playbackStart(0, properties); // Buffering after 5 seconds of playback myMedia.bufferStart(5000, properties); // Seek action (backward from cursor position 5 seconds to cursor position 3 seconds) myMedia.seek(5000, 3000, properties); // Playback resume (cursor position 3 seconds) myMedia.playbackResumed(3000, properties); // Playback pause (cursor position 9 seconds) myMedia.playbackPaused(9000, properties); // Playback resume (cursor position 9 seconds) myMedia.playbackResumed(9000, properties); // Playback stop (cursor position 15 seconds) myMedia.playbackStopped(15000, properties); ``` ```swift var myMedia = AVMedia(pa: pa) myMedia.setHeartbeat(heartbeat: [ 0: 5, 1: 10, 5: 60 ]) myMedia.setBufferHeartbeat(bufferingHeartbeat: [ 0: 5, 1: 10, 5: 60 ]) var properties = [ "av_content_id": "fge234", //mandatory "av_content": "myContent", "av_content_type": "Video", "av_content_duration": 10000, "av_content_genre": ["entertainment"], "av_content_version": "short", "av_player": "HTML5_V123", "av_player_version": "1b", "av_player_position": "top", "av_broadcasting_type": "On Demand", "av_publication_date": 1562055880, "av_show": "The gist of the game", "av_show_season": "Season 1", "av_episode_id": "3134", "av_channel": "INFO", "av_author": "Piano", "av_broadcaster": "Direction 123", "av_language": "EN", "av_subtitles": "FR", "av_launch_reason": "Auto" ] myMedia.setExtraProperties(properties) // Play attempt (cursor position 0 second) myMedia.play(cursorPosition: 0, extraProps: properties) // Buffering before playback start (cursor position 0 second) myMedia.bufferStart(cursorPosition: 0, extraProps: properties) // Playback start (cursor position 0 second) myMedia.playbackStart(cursorPosition: 0, extraProps: properties) // Buffering after 5 seconds of playback myMedia.bufferStart(cursorPosition: 5000, extraProps: properties) // Seek action (backward from cursor position 5 seconds to cursor position 3 seconds) myMedia.seek(oldCursorPosition: 5000, newCursorPosition: 3000, extraProps: properties) // Playback resume (cursor position 3 seconds) myMedia.playbackResumed(cursorPosition: 3000, extraProps: properties) // Playback pause (cursor position 9 seconds) myMedia.playbackPaused(cursorPosition: 9000, extraProps: properties) // Playback resume (cursor position 9 seconds) myMedia.playbackResumed(cursorPosition: 9000, extraProps: properties) // Playback stop (cursor position 15 seconds) myMedia.playbackStopped(cursorPosition: 15000, extraProps: properties) ``` ## Custom events tracking method ### track The AV Insights `track()` method allows standard or custom events to be tracked. Event name : `event` value *Track standard or custom actions.* `track(event, [options, callback, extraProps])` | Parameter | Type | Description | | --------------------- | -------- | ----------------------------------------------------------------------------- | | event | string | Event to be generated (see list of standard events at the bottom of the page) | | options (optional) | Object | Options depending on the event (see list of available options) | | callback (optional) | function | Callback function to execute after hit sent | | extraProps (optional) | Object | Custom properties | Example ```js var myMedia = new pa.avInsights.Media(5, 5); // Buffer tagging myMedia.track( "av.buffer.start", { av_position: 0 }, function () { console.log('Event "av.buffer.start" generated'); }, null ); // Re-buffer tagging myMedia.track( "av.rebuffer.start", { av_position: 10 }, function () { console.log('Event "av.rebuffer.start" generated'); }, null ); // Play tagging myMedia.track( "av.play", { av_position: 0 }, function () { console.log('Event "av.play" generated'); }, null ); // Playback start tagging myMedia.track( "av.start", { av_position: 0 }, function () { console.log('Event "av.start" generated'); }, null ); // Playback pause tagging myMedia.track( "av.pause", { av_position: 10 }, function () { console.log('Event "av.pause" generated'); }, null ); // Playback resume tagging myMedia.track( "av.resume", { av_position: 10 }, function () { console.log('Event "av.resume" generated'); }, null ); // Playback stop tagging myMedia.track( "av.stop", { av_position: 20 }, function () { console.log('Event "av.stop" generated'); }, null ); // Seek forward tagging myMedia.track( "av.forward", { av_previous_position: 10, av_position: 20 }, function () { console.log('Event "av.forward" generated'); }, null ); // Seek backward tagging myMedia.track( "av.backward", { av_previous_position: 20, av_position: 10 }, function () { console.log('Event "av.backward" generated'); }, null ); // Ad click tagging myMedia.track( "av.ad.click", null, function () { console.log('Event "av.ad.click" generated'); }, null ); // Ad skip tagging myMedia.track( "av.ad.skip", null, function () { console.log('Event "av.ad.skip" generated'); }, null ); // Error tagging myMedia.track( "av.error", { av_player_error: "Player error" }, function () { console.log('Event "av.error" generated'); }, null ); // Display tagging myMedia.track( "av.display", null, function () { console.log('Event "av.display" generated'); }, null ); // Close tagging myMedia.track( "av.close", null, function () { console.log('Event "av.close" generated'); }, null ); // Volume tagging myMedia.track( "av.volume", null, function () { console.log('Event "av.volume" generated'); }, null ); // Subtitle on tagging myMedia.track( "av.subtitle.on", null, function () { console.log('Event "av.subtitle.on" generated'); }, null ); // Subtitle off tagging myMedia.track( "av.subtitle.off", null, function () { console.log('Event "av.subtitle.off" generated'); }, null ); // Full screen on tagging myMedia.track( "av.fullscreen.on", null, function () { console.log('Event "av.fullscreen.on" generated'); }, null ); // Full screen off tagging myMedia.track( "av.fullscreen.off", null, function () { console.log('Event "av.fullscreen.off" generated'); }, null ); // Quality tagging myMedia.track( "av.quality", null, function () { console.log('Event "av.quality" generated'); }, null ); // Speed tagging myMedia.track( "av.speed", null, function () { console.log('Event "av.speed" generated'); }, null ); // Share tagging myMedia.track( "av.share", null, function () { console.log('Event "av.share" generated'); }, null ); // Custom tagging myMedia.track("custom", null, null, { customParam: "customValue" }); ``` `func Media.track(event, options, extraProps)` | Parameter | Type | Description | | ---------- | -------------------- | ---------------------------------------------------------------------------------------- | | event | String | Event to be generated (see list of standard events at the bottom of the page) | | options | Map? | Options depending on the event (see list of available options at the bottom of the page) | | extraProps | Map? | Custom properties | Example ```java myMedia.setHeartbeat(new SparseIntArray() .append(0, 5) .append(1, 10) .append(5, 60) ); myMedia.setBufferHeartbeat(new SparseIntArray() .append(0, 5) .append(1, 10) .append(5, 60) ); // Buffer tagging myMedia.track( "av.buffer.start", new HashMap() {{ put("av_position", 0); }}, new HashMap() {{ put("av_content", "Content title"); ... }} ); // Re-buffer tagging myMedia.track( "av.rebuffer.start", new HashMap() {{ put("av_position", 10); }}, new HashMap() {{ put("av_content", "Content title"); ... }} ); // Play tagging myMedia.track( "av.play", new HashMap() {{ put("av_position", 0); }}, new HashMap() {{ put("av_content", "Content title"); ... }} ); ... // Custom tagging myMedia.track(event: "av.custom", options: nil, extraProps: ["av_content": "Content title", ...]); ``` `myMedia.track(event: String, options: [String: Any]?, extraProps: [String: Any]?)` | Parameter | Type | Description | | --------------------- | ---------------- | ---------------------------------------------------------------------------------------- | | event | String | Event to be generated (see list of standard events at the bottom of the page) | | options (optional) | \[String: Any\]? | Options depending on the event (see list of available options at the bottom of the page) | | extraProps (optional) | \[String: Any\]? | Custom properties | Example ```swift myMedia.setHeartbeat(heartbeat: [ 0: 5, 1: 10, 5: 60 ]) myMedia.setBufferHeartbeat(bufferHeartbeat: [ 0: 5, 1: 10, 5: 60 ]) // Buffer tagging myMedia.track(event: "av.buffer.start", options: ["av_position": 0], extraProps: ["av_content": "Content title", ...]) // Re-buffer tagging myMedia.track(event: "av.rebuffer.start", options: ["av_position": 10], extraProps: ["av_content": "Content title", ...]) // Play tagging myMedia.track(event: "av.play", options: ["av_position": 0], extraProps: ["av_content": "Content title", ...]) ... // Custom tagging myMedia.track(event: "av.custom", options: nil, extraProps: ["av_content": "Content title", ...]) ``` ### List of available options | Option | Description | | ---------------------- | ------------------------------------------ | | av_position | Current cursor position (in milliseconds) | | av_previous_position | Previous cursor position (in milliseconds) | | av_player_error | Error preventing playback | ## Annexes ### Media sequence example *This represents the ideal sequence for a media playback. As this does not include ads, there will be adjustments needed to cover this scenario.* ![data model](/analytics/assets/images/av_insight_tagging_example-de32b0c743116f55aff175331a18de94.png) ### Seek sequence example ![data model](/analytics/assets/images/av_insight_seek_example-ca37ba70916debd0e37a76a31cff0c79.png) ### Media properties list > note: > > Please note that the Piano Analytics SDK automatically adds properties to your AV events. You will need to exempt these properties too for proper AV tracking. | Property | Description | Type | Mandatory | Example | | ---------------------------- | ----------------------------------------------------------------------- | --------------- | --------- | -------------------------------------- | | av_content_id | Content ID | string | Yes | 'bc35' | | av_session_id | Session ID (generated by the SDK) | uuid\* | Yes | '799d9f3b-7307-5113-a260-2e1371e35fe6' | | av_duration | Inter-event duration (in milliseconds) (generated by the SDK) | int | | 5000 | | av_position | Cursor position (in milliseconds) (generated by the SDK for heartbeats) | int | | 5000 | | av_previous_event | Previous event (generated by the SDK) | string | | 'av.start' | | av_previous_position | Previous cursor position (in milliseconds) (generated by the SDK) | int | | 2000 | | av_content | Content Label | string | | 'Broadchurch 3.5' | | av_content_type | Content Type | string | | 'TV Show' | | av_content_duration | Content Duration (in milliseconds) | int | | 2760000 | | av_content_linked | Linked Content Label | string | | 'myLinkedContent' | | av_publication_date | Publication Date (timestamp) | date | | 1501065673 | | av_content_genre | Content genre(s) | array of string | | \["Crime","Drama","Mystery"\] | | av_show | Show Label | string | | 'Broadchurch' | | av_show_season | Show Season Label | string | | '3' | | av_episode_id | Episode ID | string | | '5' | | av_episode | Episode Label | string | | 'Episode #3.5' | | av_channel | Channel Label | string | | 'ITV' | | av_author | Author Name | string | | 'Chris Chibnall' | | av_content_version | Content Version (full length, …) | string | | 'Full length' | | av_content_duration_range | Duration range | string | | '0-10' | | av_broadcasting_type | Broadcasting Type | string | | 'Live' | | av_broadcaster | Broadcaster Name | string | | 'ITV' | | av_ad_type | Ad Type | string | | 'Mid-roll' | | av_player | Player Label | string | | 'Main' | | av_player_version | Player Version | string | | '1.55' | | av_player_position | Player Position | string | | 'Homepage' | | av_auto_mode | Auto play mode | boolean | | true | | av_language | Media language | string | | 'fr' | | av_subtitles | Subtitles | string | | 'en' | | av_launch_reason | Launch reason | string | | 'auto' | ### List of standard events | Event | Type | | --------------------- | --------- | | av.play | Manual | | av.buffer.start | Manual | | av.buffer.heartbeat | Automatic | | av.start | Manual | | av.heartbeat | Automatic | | av.pause | Manual | | av.rebuffer.start | Manual | | av.rebuffer.heartbeat | Automatic | | av.resume | Manual | | av.stop | Manual | | av.seek.start | Manual | | av.forward | Manual | | av.backward | Manual | | av.ad.click | Manual | | av.ad.skip | Manual | | av.error | Manual | | av.display | Manual | | av.close | Manual | | av.volume | Manual | | av.subtitle.on | Manual | | av.subtitle.off | Manual | | av.fullscreen.on | Manual | | av.fullscreen.off | Manual | | av.quality | Manual | | av.speed | Manual | | av.share | Manual | --- ## Collection API The Piano Analytics Collection API enables direct transmission of analytics events via HTTP requests, offering a flexible solution for environments where SDK integration is not feasible.​ ## Pattern ### Event object The event object is composed of two properties, while `name` represents the event, `data` is another object containing different the properties and values attached to the event. ```json { "name": "event.name", "data": { "property": "value", "property2": "value" } } ``` > note: > > Please note that in HTTP requests, an array of events is required. ### POST > important: > > Please note that we highly recommend using POST requests. #### Endpoint ```http https:///?s=&idclient= ``` | Header | Value | | ------------ | ---------- | | Content-Type | text/plain | #### Body ```json { "events": } ``` | Variable | Description | Example | | ----------------- | ----------------------------------------- | --------------------------------------------------------------------------------- | | collection-domain | Collection endpoint for your organization | your.collection.domain | | path | Collection path | event | | site-id | ID of the site the data belongs | 123456789 | | visitor-id | Unique identifier of the visitor | 9e8d6d5f-143a-4a21-a7d5-7348b56e130d | | events-array | Array of events objects | \[{"name": "event.name", "data": { "property": "value", "property2": "value" }}\] | > note: > > Don't hesitate to read our [collection methods article](/analytics/data-collection/general/collection-methods/) to find the collection domain that has been assigned to you. > > You can also use a custom domain thanks to our [CDDC](/analytics/data-collection/general/collection-methods/#custom-domain-data-collection). #### Example Endpoint: ```http https://your.collection.domain/event?s=123456789&idclient=9e8d6d5f-143a-4a21-a7d5-7348b56e130d ``` Body: ```json { "events": [ { "name": "event.name", "data": { "property": "value", "property2": "value" } } ] } ``` #### Programming Examples ### JavaScript ```javascript async function sendPianoAnalyticsEvent(events, siteId, visitorId, collectionDomain) { const endpoint = `https://${collectionDomain}/event`; const params = new URLSearchParams({ s: siteId, idclient: visitorId, }); try { const response = await fetch(`${endpoint}?${params}`, { method: "POST", headers: { "Content-Type": "text/plain", }, body: JSON.stringify({ events }), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } console.log("Events sent successfully"); return await response.text(); } catch (error) { console.error("Failed to send events:", error); // Implement retry logic or fallback here throw error; } } // Usage sendPianoAnalyticsEvent( [ { name: "page.display", data: { page: "Homepage", page_chapter1: "Main", }, }, ], "123456789", "9e8d6d5f-143a-4a21-a7d5-7348b56e130d", "your.collection.domain" ); ``` ### Python ```python import requests import json import logging def send_piano_analytics_event(events, site_id, visitor_id, collection_domain): endpoint = f"https://{collection_domain}/event" params = { 's': site_id, 'idclient': visitor_id } payload = {'events': events} try: response = requests.post( endpoint, params=params, headers={'Content-Type': 'text/plain'}, data=json.dumps(payload), timeout=30 ) response.raise_for_status() logging.info("Events sent successfully") return response.text except requests.exceptions.RequestException as e: logging.error(f"Failed to send events: {e}") # Implement retry logic or fallback here raise # Usage send_piano_analytics_event( events=[{ "name": "page.display", "data": { "page": "Homepage", "page_chapter1": "Main" } }], site_id="123456789", visitor_id="9e8d6d5f-143a-4a21-a7d5-7348b56e130d", collection_domain="your.collection.domain" ) ``` ### Go ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" "net/url" ) func sendPianoAnalyticsEvent(events []map[string]interface{}, siteID, visitorID, collectionDomain string) error { endpoint := fmt.Sprintf("https://%s/event", collectionDomain) params := url.Values{} params.Set("s", siteID) params.Set("idclient", visitorID) payload := map[string]interface{}{ "events": events, } jsonData, err := json.Marshal(payload) if err != nil { return fmt.Errorf("failed to marshal payload: %w", err) } req, err := http.NewRequest("POST", endpoint+"?"+params.Encode(), bytes.NewBuffer(jsonData)) if err != nil { return fmt.Errorf("failed to create request: %w", err) } req.Header.Set("Content-Type", "text/plain") client := &http.Client{} resp, err := client.Do(req) if err != nil { return fmt.Errorf("failed to send request: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("HTTP error! status: %d", resp.StatusCode) } fmt.Println("Events sent successfully") return nil } // Usage func main() { events := []map[string]interface{}{ { "name": "page.display", "data": map[string]interface{}{ "page": "Homepage", "page_chapter1": "Main", }, }, } err := sendPianoAnalyticsEvent( events, "123456789", "9e8d6d5f-143a-4a21-a7d5-7348b56e130d", "your.collection.domain", ) if err != nil { fmt.Printf("Failed to send events: %v\n", err) // Implement retry logic or fallback here } } ``` ### Java ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; public class PianoAnalytics { public static void sendPianoAnalyticsEvent( List> events, String siteId, String visitorId, String collectionDomain ) throws Exception { String endpoint = String.format( "https://%s/event?s=%s&idclient=%s", collectionDomain, URLEncoder.encode(siteId, StandardCharsets.UTF_8), URLEncoder.encode(visitorId, StandardCharsets.UTF_8) ); Map payload = new HashMap<>(); payload.put("events", events); ObjectMapper mapper = new ObjectMapper(); String jsonData = mapper.writeValueAsString(payload); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(endpoint)) .header("Content-Type", "text/plain") .POST(HttpRequest.BodyPublishers.ofString(jsonData)) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new Exception("HTTP error! status: " + response.statusCode()); } System.out.println("Events sent successfully"); } // Usage public static void main(String[] args) { try { List> events = new ArrayList<>(); Map event = new HashMap<>(); event.put("name", "page.display"); Map data = new HashMap<>(); data.put("page", "Homepage"); data.put("page_chapter1", "Main"); event.put("data", data); events.add(event); sendPianoAnalyticsEvent( events, "123456789", "9e8d6d5f-143a-4a21-a7d5-7348b56e130d", "your.collection.domain" ); } catch (Exception e) { System.err.println("Failed to send events: " + e.getMessage()); // Implement retry logic or fallback here } } } ``` ### PHP ```php $siteId, 'idclient' => $visitorId ]); $payload = ['events' => $events]; $jsonData = json_encode($payload); $ch = curl_init($endpoint . '?' . $params); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: text/plain'], CURLOPT_POSTFIELDS => $jsonData, CURLOPT_TIMEOUT => 30 ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = curl_error($ch); curl_close($ch); if ($error) { throw new Exception("Failed to send request: {$error}"); } if ($httpCode !== 200) { throw new Exception("HTTP error! status: {$httpCode}"); } echo "Events sent successfully\n"; } // Usage try { sendPianoAnalyticsEvent( [ [ 'name' => 'page.display', 'data' => [ 'page' => 'Homepage', 'page_chapter1' => 'Main' ] ] ], '123456789', '9e8d6d5f-143a-4a21-a7d5-7348b56e130d', 'your.collection.domain' ); } catch (Exception $e) { echo "Failed to send events: " . $e->getMessage() . "\n"; // Implement retry logic or fallback here } ``` ### Ruby ```ruby require 'net/http' require 'uri' require 'json' def send_piano_analytics_event(events, site_id, visitor_id, collection_domain) endpoint = "https://#{collection_domain}/event" params = URI.encode_www_form({ 's' => site_id, 'idclient' => visitor_id }) payload = { 'events' => events } json_data = payload.to_json uri = URI("#{endpoint}?#{params}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri) request['Content-Type'] = 'text/plain' request.body = json_data response = http.request(request) unless response.code == '200' raise "HTTP error! status: #{response.code}" end puts 'Events sent successfully' rescue => e puts "Failed to send events: #{e.message}" # Implement retry logic or fallback here raise end # Usage begin send_piano_analytics_event( [ { 'name' => 'page.display', 'data' => { 'page' => 'Homepage', 'page_chapter1' => 'Main' } } ], '123456789', '9e8d6d5f-143a-4a21-a7d5-7348b56e130d', 'your.collection.domain' ) rescue => e puts "Failed to send events: #{e.message}" # Implement retry logic or fallback here end ``` ### cURL ```bash #!/bin/bash # Function to send events with error handling send_event() { local endpoint="https://your.collection.domain/event" local site_id="123456789" local visitor_id="9e8d6d5f-143a-4a21-a7d5-7348b56e130d" local payload='{ "events": [{ "name": "page.display", "data": { "page": "Homepage", "page_chapter1": "Main" } }] }' # Send request with error handling if response=$(curl -s -w "\n%{http_code}" \ -X POST \ -H "Content-Type: text/plain" \ -d "$payload" \ "${endpoint}?s=${site_id}&idclient=${visitor_id}"); then http_code=$(echo "$response" | tail -n1) response_body=$(echo "$response" | head -n -1) if [ "$http_code" -eq 200 ]; then echo "Events sent successfully" else echo "Error: HTTP $http_code - $response_body" >&2 exit 1 fi else echo "Error: Failed to send request" >&2 exit 1 fi } # Usage send_event ``` ### GET #### Endpoint ```http https:///?s=&idclient=&events=[] ``` | Variable | Description | Example | | ----------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | collection-domain | Collection endpoint for your organization | your.collection.domain | | path | Collection path | event | | site-id | ID of the site the data belongs | 123456789 | | visitor-id | Unique identifier of the visitor | 9e8d6d5f-143a-4a21-a7d5-7348b56e130d | | events-array | Array of events objects. URL encoded | %5B%7B%22name%22%3A%22event.name%22%2C%22data%22%3A%7B%22property%22%3A%22value%22%2C%22property2%22%3A%22value%22%7D%7D%5D | > note: > > Don't hesitate to read our [collection methods article](/analytics/data-collection/general/collection-methods/) to find the collection domain that has been assigned to you. > > You can also use a custom domain thanks to our [CDDC](/analytics/data-collection/general/collection-methods/#custom-domain-data-collection). #### Example ```http https://your.collection.domain/event?s=123456789&idclient=9e8d6d5f-143a-4a21-a7d5-7348b56e130d&events=%5B%7B%22name%22%3A%22event.name%22%2C%22data%22%3A%7B%22property%22%3A%22value%22%2C%22property2%22%3A%22value%22%7D%7D%5D ``` ## Property key rules The property key must follow some rules: - lowercase (our processing will automatically lowercase it) - authorized characters: `a→z` `0→9` `_` - no space - begin with `a→z` - can't begin with: `m_` or `visit_` - 40 characters max ## Property type > info: > > In your Data Model, a property is tied to a specific type. When you tag your properties, this type must be the same. The JSON type is automatically assigned to the property. You can however force a type, by prefixing the property key with: - `s:` (string) - `n:` (integer) - `f:` (float) - `d:` (date) - `b:` (boolean) - `a:s:` (array of strings) Our processing will then try to cast it if the value complies. Example: ```text "data": { ... "f:product_price": "12.50", ... } --> Even if the JSON type is string, we will process it as a float. ``` ### Date Properties ending with `_date`, `_utc`, `_timestamp` and `_ts` are automatically casted as dates if the value whether: - is a date following this pattern: `YYYYMMDD` or `YYYY-MM-DD` - is a Timestamp in seconds `1660027175` (if you need milliseconds, use decimals: `1660027175.475`) - complies with the RFC 3339 standard `YYYY-MM-DDTHH:mm:ssZ` ### Limits Our data model imposes limits: - string: 255 characters - array of strings: 20 strings of 255 characters - integer: int64 - decimal: between `-1.0e15` and `1.0e15` ## Headers A few headers are taken into account, in order to enhance analysis. | Header | Description | Example | | --------------- | ------------------------------------ | --------------------------------------------------------------------------------- | | User-Agent | User agent of the client | User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0 | | Referer | Address of the page sending the data | Referer: https://www.piano.io | | X-Forwarded-For | IP address of the client | X-Forwarded-For: 129.78.138.66 | ## Standard properties ### Contextual properties Some properties give insights on the context | Property | Description | Type | Example | | --------------------------- | ---------------------------------- | ------ | ----------------------- | | previous_url | Previous page url | string | "https://www.piano.io/" | | device_timestamp_utc | Device timestamp UTC in seconds | int | 1648753357 | | event_collection_platform | Collection platform used | string | "api" | | event_collection_version | Version of the collection platform | string | "2" | | device_manufacturer | Manufacturer of the device | string | "Apple" | | device_model | Model of the device | string | "iPhone 13" | | device_display_height | Height of the viewport | int | 1057 | | device_display_width | Width of the viewport | int | 1148 | | device_screen_height | Height of the device screen | int | 1200 | | device_screen_width | Width of the device screen | int | 1920 | ### Marketing campaigns In order to track marketing campaigns, you can use the following properties | Property | Description | Type | Example | | ------------------------- | ----------------- | ------ | ------------ | | src_medium (mandatory) | Campaign medium | string | "sea" | | src_campaign (mandatory) | Campaign name | string | "winter2022" | | src_creation | Campaign creation | string | "main" | | src_variant | Campaign variant | string | "blue" | | src_format | Campaign format | string | "440x300" | | src_type | Campaign type | string | "direct" | You can also check your data model to see other properties linked to marketing campaigns. ### Users If you want to track your authentified users, we offer specific properties | Property | Description | Type | Example | | -------------- | --------------- | ------ | -------------- | | user_id | User identifier | string | "WEB-192203AJ" | | user_category | User category | string | "premium" | ### Application Lifecycle In order to measure your application lifecycle (mobile oriented), here are the dedicated properties | Property | Description | Type | Example | | -------------- | ------------------------------------------ | ------- | -------------------------------------- | | app_sc | Session count | integer | 12 | | app_dsls | Days since last session | integer | 2 | | app_dsfs | Days since first session | integer | 48 | | app_sessionid | Session ID | string | "a6de0f1c-667b-4219-b747-3fe39a0facc9" | | app_fsd | First session date (YYYYMMDD) | string | "20220401" | | app_fsdau | First session date after update (YYYYMMDD) | string | "20230125" | | app_scsu | Session count since update | integer | 3 | | app_dsu | Days since update | integer | 10 | ## Technical specifications Our collection API has some technical specifications: - HSTS header is automatically set on HTTPS requests, forcing a secure collection even from an unencrypted (HTTP) request - use of dynamic IPs, do not rely on IP filtering - collection IPs lifetime vary. Implementation must refresh DNS cache to respect TTL value (60 seconds) and spread the traffic across all IPs - bot detection can be ignored by adding the boolean property `bot_detection` with the value `false` in your events - max body size is set to `500 kB` ### TLS policy If you use a custom domain for your collection (CDDC), you can request one of the following specific TLS configuration. Available policies: | | SSLv3 | TLSv1 | TLSv1_2016 | TLSv1.1_2016 | TLSv1.2_2018 | TLSv1.2_2019 | TLSv1.2_2021 | | ------------------------------- | ----- | ----- | ----------- | ------------- | ------------- | ------------- | ------------- | | **Supported SSL/TLS protocols** | | | | | | | | | TLSv1.3 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | TLSv1.2 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | TLSv1.1 | ♦ | ♦ | ♦ | ♦ | | | | | TLSv1 | ♦ | ♦ | ♦ | | | | | | SSLv3 | ♦ | | | | | | | | **Supported TLSv1.3 ciphers** | | | | | | | | | TLS_AES_128_GCM_SHA256 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | TLS_AES_256_GCM_SHA384 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | TLS_CHACHA20_POLY1305_SHA256 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | **Supported RSA ciphers** | | | | | | | | | ECDHE-RSA-AES128-GCM-SHA256 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | ECDHE-RSA-AES128-SHA256 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | | ECDHE-RSA-AES128-SHA | ♦ | ♦ | ♦ | ♦ | | | | | ECDHE-RSA-AES256-GCM-SHA384 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | ECDHE-RSA-CHACHA20-POLY1305 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | ECDHE-RSA-AES256-SHA384 | ♦ | ♦ | ♦ | ♦ | ♦ | ♦ | | | ECDHE-RSA-AES256-SHA | ♦ | ♦ | ♦ | ♦ | | | | | AES128-GCM-SHA256 | ♦ | ♦ | ♦ | ♦ | ♦ | | | | AES256-GCM-SHA384 | ♦ | ♦ | ♦ | ♦ | ♦ | | | | AES128-SHA256 | ♦ | ♦ | ♦ | ♦ | ♦ | | | | AES256-SHA | ♦ | ♦ | ♦ | ♦ | | | | | AES128-SHA | ♦ | ♦ | ♦ | ♦ | | | | | DES-CBC3-SHA | ♦ | ♦ | | | | | | | RC4-MD5 | ♦ | | | | | | | ### Server-side Cookies management > info: > > Please refer to [storage documentation](/analytics/data-collection/general/cookie-storage/#server-side-cookies) to view our server-side cookies specifications. If the incoming request does not include an `idclient` querystring parameter or an already existing server-side cookie, we will automatically redirect (`302 Found` on `GET` requests, `307 Temporary Redirect` on `POST` requests) to set the server-side cookies. This redirection will upgrade to HTTPS for incoming HTTP requests, causing the HSTS header to be set. --- ## Consent management ## Prerequisite Consent Management is only available on JS ≥ 6.8.0, Android ≥ 3.4.0 and iOS ≥ 3.1.0. If you use PA JS < 6.8.0 / Android < 3.4.0 / iOS < 3.1.0, please use legacy [Privacy management](/analytics/data-collection/how-to-send-events/privacy/) methods. > note: > > If you want to use the ePrivacy exemption, please read this [documentation](https://analytics-docs.piano.io/en/analytics/v1/consent-exemption-configuration) first. Contact our support centre to request an activation process for the ePrivacy exemption. ## What is "Consent Management" "Consent Management" is the first building block of unified tagging methods across all Piano products. You will be able to control the data collected, according to the different regulations you refer to. All in one place for all your Piano products. In other words, it allows you to customize your tagging thanks to a precise management of the different measurement parameters (events and properties sent, trackers used, ...), in compliance with the regulations in force. All the logic is explained in our [Privacy center](https://analytics-docs.piano.io/en/analytics/v1/consent-management). > Read first: > > As a unified way to manage Privacy, “Consent Management” can be triggered from several Piano SDKs. > > You have two options: > > - **You use several Piano Products** > > - You can manage consent for all products using the Piano Analytics SDK and this documentation. > - Or you can use the Composer SDK with this [configuration](https://docs.piano.io/consent-management-for-client-storage-cookies/). > > *Make sure that only one SDK triggers Privacy instructions.* > - **You only use Piano Analytics** > > - Use this page to set up your Privacy instructions. ## Key notion A "Consent Mode" is a state in which you can have control over various items: - The events / properties you want to send - The value your `visitor_privacy_mode` and `visitor_privacy_consent` properties will take Basically, we can say that a Consent Mode refers to a specific purpose (under GDPR). Thanks to the `visitor_privacy_mode` and `visitor_privacy_consent`, you will be able to respect a perfect data governance by applying dedicated treatments depending on the mode the data has been collected. ## Consent Modes ### JavaScript | Consent Mode | setMode value | "_pcid" cookie | Visitor ID | visitor_privacy_mode | visitor_privacy_consent | Properties / events | Exclusion / Anonymization | Comment | | ------------------------- | ------------- | --------------- | ---------- | ---------------------- | ------------------------- | ------------------------------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Opt-in | opt-in | ✅ | ✅ | optin | true | all | ❌ | | | Exempt | essential | ✅ | ✅ | exempt | false | [some](/analytics/data-collection/consent/modes-rules/) | ❌ | Requires a specific configuration as explained in our [Privacy center](https://analytics-docs.piano.io/en/analytics/v1/consent-exemption-configuration) | | Opt-out | opt-out | ❌ | ❌ | optout | false | [some](/analytics/data-collection/consent/modes-rules/) | ✅ | All events will be excluded and anonymized. More information in our [Privacy Center](https://analytics-docs.piano.io/en/analytics/v1/pseudonymization-and-anonymization) | | Extended Opt-out ≥ 6.13.0 | opt-out | ❌ | ❌ | extended-optout | false | all | ✅ | enableExtendedOptout SDK configuration [needed](/analytics/data-collection/sdks/javascript/#sdk-configuration). All events will be anonymized thanks to the "Contains personal data" flags. More information in our [Privacy Center](https://analytics-docs.piano.io/en/analytics/v1/contains-personal-data-flag) | Deprecated mode | Consent Mode | setMode value | "_pcid" cookie | Visitor ID | visitor_privacy_mode | visitor_privacy_consent | Properties / events | Exclusion / Anonymization | Comment | | ----------------- | ------------- | --------------- | ---------- | ---------------------- | ------------------------- | ---------------------------------------- | ------------------------- | ---------------------------------------------------------------------------- | | Custom Deprecated | custom | you decide | you decide | you decide | you decide | you decide (same base as essential mode) | ❌ | Some cookies, properties and events are included by default to a custom mode | ### Android (3.4.0+) | Consent Mode | pianoConsents.set() value | Visitor ID | visitor_privacy_mode | visitor_privacy_consent | Properties / events | Exclusion / Anonymization | Comment | | ------------ | ------------------------- | ---------- | ---------------------- | ------------------------- | ------------------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Opt-in | ConsentMode.OPT_IN | ✅ | optin | true | all | ❌ | | | Exempt | ConsentMode.ESSENTIAL | ✅ | exempt | false | [some](/analytics/data-collection/privacy/modes-rules/) | ❌ | Requires a specific configuration as explained in our [Privacy center](https://analytics-docs.piano.io/en/analytics/v1/consent-exemption-configuration) | | Opt-out | ConsentMode.OPT_OUT | ❌ | optout | false | [some](/analytics/data-collection/privacy/modes-rules/) | ✅ | All events will be excluded and anonymized. More information in our [Privacy Center](https://analytics-docs.piano.io/en/analytics/v1/pseudonymization-and-anonymization) | Deprecated mode | Consent Mode | pianoConsents.set() value | Visitor ID | visitor_privacy_mode | visitor_privacy_consent | Properties / events | Exclusion / Anonymization | Comment | | ----------------- | ------------------------- | ---------- | ---------------------- | ------------------------- | ------------------- | ------------------------- | ---------------------------------------------------------------------------- | | Custom Deprecated | ConsentMode.CUSTOM | you decide | custom | you decide | you decide | ❌ | Some cookies, properties and events are included by default to a custom mode | > tip: > > Each mode has by default its own rules. > > For JS SDK, you can check which storage keys (cookies), properties and events are included by default in [the dedicated article](/analytics/data-collection/consent/modes-rules/). > > For Android SDK, the default configuration is the [same as the Privacy modes](/analytics/data-collection/privacy/modes-rules/). Please note that only Optin, Exempt and Optout are available for Consent feature. You can also find the list of our cookies and storage keys in the [Cookies & storage](/analytics/data-collection/general/cookie-storage/) article. ### Extended opt-out Since PA JS 6.13.0, you can turn on "Extended opt-out". This feature anonymously collects exhaustive data for opted-out visitors. See how it works in our [Privacy center](https://analytics-docs.piano.io/en/analytics/v1/consent-management). To enable it, you should [set the SDK configuration](/analytics/data-collection/sdks/javascript/#sdk-configuration) `enableExtendedOptout` to `true`. This will change the behavior of opted-out visitors, who will now send every events and properties, with an anonymized visitor ID (`idclient`). ## Pre-requisite The configuration of the Consents feature uses the global object `window.pdl`, that must be defined and populated **before the loading of the SDK**. ```html ... ``` The configuration of the Consents feature requires the dependency available [here](https://github.com/tinypass/piano-consents-android). The Piano Consents SDK is available as an AAR via MavenCentral. To add dependencies, open your project's `build.gradle`/`build.gradle.kts` and update `dependencies` block: ```text dependencies { ... implementation("io.piano.android:consents:VERSION") } ``` The configuration of the Consents feature requires the dependency available [here](https://pub.dev/packages/piano_consents). Add the `piano_consents` package to your `pubspec.yaml` file: ```yaml dependencies: piano_consents: ^1.0.1 ``` The configuration of the Consents feature requires the dependency available [here](https://gitlab.com/piano-public/sdk/ios/packages/consents). **CocoaPods** Add the following lines to your Podfile. ```text use_frameworks! pod 'PianoConsents', '~>1.0.9' ``` **Swift Package Manager** Add the component PianoConsents from the repository: URL: `https://gitlab.com/piano-public/sdk/ios/packages/consents` Version: `1.0.9` You can then import the dependency: ```swift import PianoConsents ``` ### Activating the Consents feature In order to activate the Consents feature, you need to set the `requireConsent` variable to `'v2'`: ```js window.pdl = window.pdl || {}; window.pdl.requireConsent = "v2"; window.pdl.consent = {}; // If you use Analytics only window.pdl.consent.products = ["PA"]; ``` In order to activate the Consents feature, you need to give the `PianoConsents` instance to your `PianoAnalytics` instance: ```kotlin val pianoConsents = PianoConsents.init( context, ConsentConfiguration( requireConsent = true // `false` means "disable the feature" ) ) PianoAnalytics.init(applicationContext, configuration, pianoConsents) ``` In order to activate the Consents feature, you need to `PianoConsents` instance before `PianoAnalytics` instance: ```dart import 'package:piano_consents/piano_consents.dart'; import 'package:piano_analytics/piano_analytics.dart'; ... class _MyAppState extends State { final _pianoConsents = PianoConsents( requireConsents: true, defaultPurposes: { PianoConsentProduct.pa: PianoConsentPurpose.audienceMeasurement } ); final _pianoAnalytics = PianoAnalytics(...); @override void initState() { super.initState(); initPlugins(); } Future initPlugins() async { ... await _pianoConsents.init(); await _pianoAnalytics.init(); ... } ... } ``` In order to activate the Consents feature, you need to init `PianoConsents` instance: ```swift let configuration = PianoConsentsConfiguration( requireConsents: true, // `false` means "disable the feature" defaultPurposes: nil // specify custom purposes for Piano products, `nil` means "use default mapping" ) PianoConsents.initialize(configuration: configuration) ``` ## Purposes and products Since consent v2 (PA JS 6.14.0), the consent is set by purpose instead of Piano products. Each product belongs to one purpose by default, but you can alter our default setup. Default distribution: | Purpose | Products | | -------------------------------------------- | ------------------------------- | | Audience measurement (AM) | Analytics (PA) | | Content personalization and Performance (CP) | Composer (COMPOSER) | | Advertising (AD) | DMP, Social Flow (SOCIAL_FLOW) | | Personal Relationship (PR) | ID, VX, ESP | | Data Layer (DL) (*JS only*) | DL | > note: > > "Data Layer" purpose and the assigned DL product are reserved by Piano. Only the DL product can be assigned to the DL purpose. ### Altering the Default Purposes You can specify your own purposes if the ones provided by Piano don't match your consent banner. For example: ```js window.pdl = window.pdl || {}; window.pdl.requireConsent = "v2"; window.pdl.consent = {}; window.pdl.consent.defaultPurposes = { DMP: "Custom purpose 1", COMPOSER: "Custom purpose 2", }; ``` ```kotlin val pianoConsents = PianoConsents.init( context, ConsentConfiguration( requireConsent = true, defaultPurposes = mapOf( // specify custom purposes for Piano products, `null` means "use default mapping" Product.DMP to Purpose("Custom purpose 1"), Product.COMPOSER to Purpose("Custom purpose 2"), ) ) ) PianoAnalytics.init(applicationContext, configuration, pianoConsents) ``` ```swift let configuration = PianoConsentsConfiguration( requireConsents: true, // `false` means "disable the feature" defaultPurposes: [ // specify custom purposes for Piano products, `nil` means "use default mapping" PianoConsentProduct.DMP: PianoConsentPurpose.init(custom: "Custom purpose 1"), PianoConsentProduct.COMPOSER: PianoConsentPurpose.init(custom: "Custom purpose 2"), ] ) PianoConsents.initialize(configuration: configuration) ``` In this example since Composer is moved to a different purpose the CP purpose doesn’t contain any product and doesn’t exist anymore. Based on the above code, here is how the purposes and products would look like after if it's applied: | Purpose | Products | | -------------------------- | -------------------------- | | Audience measurement (AM) | Analytics (PA) | | **Custom purpose 2** | Composer (COMPOSER) | | **Custom purpose 1** | DMP | | Advertising (AD) | Social Flow (SOCIAL_FLOW) | | Personal Relationship (PR) | ID, VX, ESP | | Data Layer (DL) | DL | ## Set consent mode by purpose The Consent Mode will be in charge of sending the right information, depending on what you have configured. It will be stored in a `_pprv` cookie along with other Piano products consent, and will be used on all events until it is modified, or until the cookie is deleted. Method: `pa.consent.setByPurpose(purpose, mode, product?)` | Parameters | Type | Description | | ---------- | -------------- | ------------------------------------------------------------------- | | purpose | string | Purpose to set. AM, CP, AD, PR or DL | | mode | string | Consent mode. opt-in, essential or opt-out | | product | string / array | Product(s) to assign to the purpose. PA, COMPOSER, DMP, VX, ID, ESP | ```js pa.consent.setByPurpose("AM", "essential"); // edit AM products pa.consent.setByPurpose("AM", "essential", ["PA", "COMPOSER"]); ``` You can also set a Consent mode for all purposes. `pa.consent.setAllPurposes(mode)` | Parameters | Type | Description | | ---------- | ------ | ------------------------------------------ | | mode | string | Consent mode. opt-in, essential or opt-out | ```js pa.consent.setAllPurposes("essential"); ``` ```kotlin val pianoConsents = PianoConsents.getInstance() // or can be retrieved via PianoAnalytics.getInstance().pianoConsents (null if consents are not used) pianoConsents.set(Purpose.AUDIENCE_MEASUREMENT, ConsentMode.ESSENTIAL) // edit AM products pianoConsents.set(Purpose.AUDIENCE_MEASUREMENT, ConsentMode.ESSENTIAL, Product.PA, Product.COMPOSER) ``` You can also set a Consent mode for all purposes. ```kotlin PianoConsents.getInstance().setAll(ConsentMode.ESSENTIAL) ``` ```dart await _pianoConsents.set( purpose: PianoConsentPurpose.audienceMeasurement, mode: PianoConsentMode.essential, products: [PianoConsentProduct.pa]); ``` You can also set a Consent mode for all purposes. ```dart await _pianoConsents.setAll(mode: PianoConsentMode.essential); ``` ```swift PianoConsents.shared.set( purpose: PianoConsentPurpose.AUDIENCE_MEASUREMENT, mode: PianoConsentMode.ESSENTIAL, ) // edit AM products PianoConsents.shared.set( purpose: PianoConsentPurpose.AUDIENCE_MEASUREMENT, mode: PianoConsentMode.ESSENTIAL, products: PianoConsentProduct.PA, PianoConsentProduct.COMPOSER ) ``` You can also set a Consent mode for all purposes. ```swift PianoConsents.shared.setAll(mode: PianoConsentMode.ESSENTIAL) ``` ## Retrieve consent mode by purpose If you want to know the current consent mode for each purpose, you can use the following method: Method: `pa.consent.getByPurpose()` ```js pa.consent.getByPurpose(); // { // AM: {mode: 'opt-in', products: ["PA"]}, // CP: {mode: 'opt-in', products: ["COMPOSER"]}, // AD: {mode: 'opt-in', products: ["DMP", "SOCIAL_FLOW"]}, // PR: {mode: 'opt-out', products: ["ID", "VX", "ESP"]}, // DL: {mode: 'opt-in', products: ["DL"]}, // } ``` ```kotlin PianoConsents.getInstance().consents // returns Map, where // - Purpose is one of [AUDIENCE_MEASUREMENT, CONTENT_PERSONALISATION, ADVERTISING, PERSONAL_RELATIONSHIP], // - Consent is class Consent(val mode: ConsentMode, val products: List), // - ConsentMode is one of [OPT_IN, ESSENTIAL, OPT_OUT, CUSTOM, NOT_ACQUIRED], // - Product is one of [PA, DMP, COMPOSER, ID, VX, ESP, SOCIAL_FLOW] ``` ```swift PianoConsents.shared.consents // returns Map, where // - Purpose is one of [AUDIENCE_MEASUREMENT, CONTENT_PERSONALISATION, ADVERTISING, PERSONAL_RELATIONSHIP], // - Consent is class Consent(val mode: ConsentMode, val products: List), // - ConsentMode is one of [OPT_IN, ESSENTIAL, OPT_OUT, CUSTOM, NOT_ACQUIRED], // - Product is one of [PA, DMP, COMPOSER, ID, VX, ESP, SOCIAL_FLOW] ``` ## Configure the default consent mode In order to define the default consent mode for Piano Analytics (`PA`), you need to set the `consent.defaultPreset.PA` variable to the desired value (`optin` by default): ```js window.pdl = window.pdl || {}; window.pdl.requireConsent = "v2"; window.pdl.consent = { defaultPreset: { PA: "essential", }, }; // If you use Analytics only window.pdl.consent.products = ["PA"]; ``` With Kotlin SDK, you need to set the consent mode after the consents init: ```kotlin // call after PianoConsents.init(...) PianoConsents.set(...) ``` ```dart final _pianoConsents = PianoConsents( requireConsents: true, defaultPurposes: { PianoConsentProduct.pa: PianoConsentPurpose.audienceMeasurement } ); ``` With iOS SDK, you need to set the consent mode after the consents init: ```swift // call after PianoConsents.initialize(...) PianoConsents.set(...) ``` ## Manage default Consent modes As explained in the [Key notion](#key-notion) section, you can manage your default Consent Modes by controlling several items: - properties / events - the value your `visitor_privacy_mode` and `visitor_privacy_consent` properties will take For JS SDK, this is achieved by declaring mode items before loading the SDK, thanks to `window.pdl.consent_items.PA` object. You need to define the type of items you need to edit: `properties` or `events`. You'll then need to define the priority level of each property/event you need to modify. Three levels exist: `mandatory` (higher priority) > `essential` > `optional` (lower priority). Priority level refers to the consent level required for the data to be sent/stored. You can imagine it as follow: ![Consent priorities](/analytics/assets/images/consent-priorities-mode-907a23494284f2b7692355db41e18d82.png) Any item with a higher priority will also be sent with lower priority modes. For example, an item with a "mandatory" priority will be included de facto in "essential" and "opt-in" modes. On the other hand, if we try to avoid sending `event_collection_platform` in "opt-out" and "essential" modes: ```js window.pdl.consent_items = { PA: { properties: { event_collection_platform: "optional", }, }, }; ``` As `event_collection_platform` has the lowest priority level ("optional"), it won't be included into "essential" and "opt-out" modes. The `window.pdl.consent_items.PA` object specifications: | Property | Description | Type | Value | | ---------- | --------------------------------- | --------------------- | --------------- | | properties | Properties priority configuration | object of consentItem | { consentItem } | | events | Events priority configuration | object of consentItem | { consentItem } | The `window.pdl.consent_items.PA.properties`,`window.pdl.consent_items.PA.events` (`consentItem`) objects specifications: | Property | Description | Type | Value | | -------- | ------------------------------------------------ | ------ | --------------------------- | | | Key to configure, with the priority as the value | string | event_collection_platform | Complete example: ```js window.pdl.consent_items = { PA: { properties: { event_collection_platform: "essential", event_collection_version: "optional", }, events: { "ad.view": "optional", "ad.click": "essential", }, }, }; ``` With Kotlin SDK, can use the same methods as the [Privacy implementation](/analytics/data-collection/how-to-send-events/privacy/#manage-a-privacy-mode): ```kotlin // allow Visitor storage for Exempt mode PrivacyMode.EXEMPT.allowedStorageFeatures += PrivacyStorageFeature.VISITOR // forbid Visitor storage for Exempt mode PrivacyMode.EXEMPT.forbiddenStorageFeatures += PrivacyStorageFeature.VISITOR // allow property `prop_name` for any event for Exempt mode PrivacyMode.EXEMPT.allowedPropertyKeys[Event.ANY]?.add(PropertyName("prop_name")) // forbid property `prop_name` for any event for Exempt mode PrivacyMode.EXEMPT.forbiddenPropertyKeys[Event.ANY]?.add(PropertyName("prop_name")) // allow event `selfpromotion.impression` for Exempt mode PrivacyMode.EXEMPT.allowedEventNames.add("selfpromotion.impression") // forbid event `selfpromotion.impression` for Exempt mode PrivacyMode.EXEMPT.forbiddenEventNames.add("selfpromotion.impression") ``` With Kotlin SDK, can use the same methods as the [Privacy implementation](/analytics/data-collection/how-to-send-events/privacy/#manage-a-privacy-mode): ```dart // allow Visitor storage for Exempt mode await _pianoAnalytics.privacyIncludeStorageFeatures( features: [PrivacyStorageFeature.visitor], modes: [PrivacyMode.exempt] ); // forbid Visitor storage for Exempt mode await _pianoAnalytics.privacyExcludeStorageFeatures( features: [PrivacyStorageFeature.visitor], modes: [PrivacyMode.exempt] ); // allow property `prop_name` for event "page.display" for Exempt mode await _pianoAnalytics.privacyIncludeProperties( propertyNames: ["prop_name"], modes: [PrivacyMode.exempt], eventNames: ["page.display"] ); // forbid property `prop_name` for event "page.display" for Exempt mode await _pianoAnalytics.privacyExcludeProperties( propertyNames: ["prop_name"], modes: [PrivacyMode.exempt], eventNames: ["page.display"] ); // allow event `selfpromotion.impression` for Exempt mode await _pianoAnalytics.privacyIncludeEvents( eventNames: ["selfpromotion.impression"], modes: [PrivacyMode.exempt] ); // forbid event `selfpromotion.impression` for Exempt mode await _pianoAnalytics.privacyExcludeEvents( eventNames: ["selfpromotion.impression"], modes: [PrivacyMode.exempt] ); ``` With iOS SDK, can use the same methods as the [Privacy implementation](/analytics/data-collection/how-to-send-events/privacy/#manage-a-privacy-mode): ```kotlin // allow Visitor storage for Exempt mode pa.privacyIncludeStorageKey(PA.Privacy.Storge.Visitor, privacyModes: ["exempt"]); // forbid Visitor storage for Exempt mode pa.privacyExcludeStorageKey(PA.Privacy.Storge.Visitor, privacyModes: ["exempt"]); // allow property `prop_name` for any event for Exempt mode pa.privacyIncludeProperty("prop_name", privacyModes: ["exempt"]); // forbid property `prop_name` for any event for Exempt mode pa.privacyExcludeProperty("prop_name", privacyModes: ["exempt"]); // allow event `selfpromotion.impression` for Exempt mode pa.privacyIncludeEvent("selfpromotion.impression", privacyModes: ["exempt"]); // forbid event `selfpromotion.impression` for Exempt mode pa.privacyExcludeEvent("selfpromotion.impression", privacyModes: ["exempt"]); ``` ## Use product consent (deprecated) ### Set a Consent Mode The Consent Mode will be in charge of sending the right information, depending on what you have configured. It will be stored in a `_pprv` cookie along with other Piano products consent, and will be used on all events until it is modified, or until the cookie is deleted. Method: `pa.consent.setMode(mode)` | Parameters | Type | Description | | ---------- | ------ | ------------------------------------------ | | mode | string | Privacy Mode. opt-in, essential or opt-out | ```js pa.consent.setMode("essential"); ``` > note: > > If you don't set any Consent Mode (and none stored), the value set for configuration `window.pdl.consent.defaultPreset.PA` will be applied by default. > > `opt-in` by default. ### Retrieve the Consent Mode If you want to know the current mode used by the SDK, you can use the following method: Method: `pa.consent.getMode()` ```js pa.consent.getMode(); // Return a string with the Consent Mode value ``` ## Deprecated Manage a custom Consent mode By default, the `custom` mode uses the same rules as the `opt-in` mode. As explained in the [Key notion](#key-notion) section, you can manage your custom Consent Mode by controlling several items: - properties / events - the value your `visitor_privacy_mode` and `visitor_privacy_consent` properties will take You first need to declare the "source mode" of your custom mode with `window.pdl.consent_modifiers.PA.source`, with one of the default modes: - `opt-in` - `essential` - `opt-out` Each rule is then a new entry in the `window.pdl.consent_modifiers.PA.patches` array, with an `action` and an `item`. Example trying to avoid sending `event_collection_platform` in "opt-out" and "essential" modes: ```js window.pdl.consent_modifiers = { PA: { source: "essential", patches: [ { action: "exclude", item: { key: "event_collection_platform", type: "property", }, }, ], }, }; ``` The `property` named `event_collection_platform` has been excluded from the custom mode. The `window.pdl.consent_modifiers.PA` object specifications: | Property | Description | Type | Value | | -------- | ------------------------------------------------ | ------------------ | ---------------------------- | | source | Base mode for configuration of the custom mode | string | opt-in, essential or opt-out | | patches | Patches to edit configuration of the custom mode | array of modePatch | \[ modePatches \] | The `window.pdl.consent_modifiers.PA.patches` (`modePatch`) array specifications: | Property | Description | Type | Value | | -------- | ------------------------- | --------- | ------------------ | | action | Action to perform | string | exclude or include | | item | Item to perform action on | patchItem | patchItem | The `window.pdl.consent_modifiers.PA.patches[].item` (`patchItem`) object specifications: | Property | Description | Type | Value | | -------- | ---------------- | ------ | ----------------- | | key | Key of the item | string | page | | type | Type of the item | string | event or property | Complete example: ```js window.pdl.consent_modifiers = { PA: { source: "optout", patches: [ { action: "exclude", item: { key: "event_collection_platform", type: "property", }, }, { action: "exclude", item: { key: "ad.view", type: "event", }, }, ], }, }; ``` You can also manage the custom mode name (sent in `visitor_privacy_mode`) and consent type (sent in `visitor_privacy_consent`) with: Method: `pa.consent.setCustomModeMetadata(modeConsent, modeName)` | Parameters | Type | Description | | ----------- | ------- | ---------------------------------- | | modeConsent | boolean | Custom Consent mode consent status | | modeName | string | Custom Consent mode name | ```js pa.consent.setMode("custom"); pa.consent.setCustomModeMetadata(false, "myCustomMode"); ``` > tip: > > Don't forget to set the mode to `custom` to apply the changes In order to set a Custom mode (will be named `Custom`), you can proceed as for default modes: ```kotlin PianoConsents.getInstance().set(Purpose.ESSENTIAL, ConsentMode.CUSTOM) ``` In order to set a Custom mode (will be named `Custom`), you can proceed as for default modes: ```swift PianoConsents.shared.set( purpose: PianoConsentPurpose.ESSENTIAL, mode: PianoConsentMode.Custom ) ``` ## How to migrate In order to migrate from Privacy implementation, here are some steps to follow or check: - Add initialization for consents ```kotlin val pianoConsents = PianoConsents.init( applicationContext, ConsentConfiguration( requireConsent = true, defaultPurposes = mapOf(...) // if needed ) ) ``` - Add consents to Piano Analytics initialization ```kotlin PianoAnalytics.init(applicationContext, configuration, pianoConsents) ``` - Set default preset (if needed) ```kotlin pianoConsents.set(...) ``` - Configure privacy modes (if needed) ```kotlin PrivacyMode.EXEMPT.allowedEventNames.add("event-name-here") ``` - Configure custom privacy mode (if needed) ```kotlin PrivacyMode.CUSTOM.apply { ... } ``` - Remove all usages of `PianoAnalytics.getInstance().privacyModesStorage.allModes` - Replace setting `PianoAnalytics.getInstance().privacyModesStorage.currentMode` via `pianoConsents.set(...)`, use this mapping: ```text PrivacyMode.OPTIN -> ConsentMode.OPT_IN PrivacyMode.EXEMPT -> ConsentMode.ESSENTIAL PrivacyMode.OPTOUT -> ConsentMode.OPT_OUT PrivacyMode.CUSTOM -> ConsentMode.CUSTOM ``` Note: default value "consent not acquired" will be used if you haven't set any other value - Purpose values are (JS name in brackets): ```text Purpose.AUDIENCE_MEASUREMENT (AM) Purpose.CONTENT_PERSONALISATION (CP) Purpose.ADVERTISING (AD) Purpose.PERSONAL_RELATIONSHIP (PR) ``` --- ## Conversion ## Tag an event as a conversion In order to track a conversion, you need to set the property `goal_type` on the event leading to conversion. | Property | Type | | ---------- | ------ | | goal_type | string | ### JavaScript ```js pa.sendEvent('account.signup', { ..., 'goal_type': 'signup', ... }); ``` ### Android (3.3.0+) ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("account.signup") .properties( Property(...), Property(PropertyName("goal_type"), "signup"), Property(...), // you can add properties here ) .build() // you can add other events here ) ``` ### Android ```java pa.sendEvent(new Event("account.signup", new HashMap() {{ put(...); put("goal_type", "signup"); put(...); }})); ``` ### Apple ```swift pa.sendEvent(Event("account.signup", data: [ ... "goal_type": "signup", ... ])) ``` --- ## Instant tracking Instant tracking is a built-in module of the JavaScript SDK ≥ 6.16.0 that makes it easier to tag core analytics features. This set of events are automatically tracked without any need for manual implementation aside from the SDK loading and configuration (site id and collect domain). > tip: > > This feature also comes with an **out-of-the-box board** based on the data collected, which can be deployed for your organization upon request. > > Please reach out to the Support centre or your preferential contact to request a demo or have it activated. ## Tracking available Instant tracking can automatically measure the following events - `page.display` - `click.download` - **pdf**, **xls**, **xlsx**, **doc**, **docx**, **txt**, **rtf**, **csv**, **exe**, **key**, **pps**, **ppt**, **pptx**, **7z**, **pkg**, **rar**, **gz**, **zip**, **avi**, **mov**, **mp4**, **mpg**, **mpeg**, **wmv**, **mid**, **midi**, **mp3**, **wav**, **wma** - `internal_search_result.display` - **q**, **s**, **search**, **query**, **keyword** On top of these events, it also collects contextual properties built-in the SDK and our processing such as - Organic and marketing traffic sources - Geolocation - Browsers and devices ## Configuration This code sample loads the Piano Analytics SDK, and enables all the instant tracking features. The `site` and `collectDomain` values must match your organization's Data Collection Portal. The `consentDefaultMode` can also be changed, please refer to the Consent documentation for more information. For a lightweight implementation: ```js (function (_config) { var script = document.createElement("script"); script.src = "https://tag.aticdn.net/piano-analytics.js"; script.async = true; script.dataset.config = JSON.stringify(_config); document.head.appendChild(script); })({ site: 123456789, collectDomain: "https://xxxxxxx.pa-cd.com", instantTracking: true, consentDefaultMode: "opt-in", }); ``` The Instant Tracking features can also be individually deactivated: ```js (function (_config) { var script = document.createElement("script"); script.src = "https://tag.aticdn.net/piano-analytics.js"; script.async = true; script.dataset.config = JSON.stringify(_config); document.head.appendChild(script); })({ site: 123456789, collectDomain: "https://xxxxxxx.pa-cd.com", instantTracking: { pages: true, searches: false, downloads: true, }, consentDefaultMode: "opt-in", }); ``` > tip: > > Each element of the `instantTracking` object can be turned on-off at will, allowing you to track what you need but also build on top of the Instant tracking module. --- ## Marketing campaigns ## Link tagging > note: > > Automatic campaign links tracking only works with JS SDK. > > If you need to track marketing campaign on mobile, you will need to push yourself dedicated properties (beginning with `src_`). ([see mobile marketing campaigns section](#mobile-marketing-campaigns)). The content of the campaign parameters must be communicated in the destination URL according to the format `at_medium=email&at_campaign=new_offer` where `at_medium` is the source label and `at_campaign` is the campaign label. These parameters are both mandatory for the campaign to be taken into account in your analyses. > attention: > > The legacy "xtor" format is not recognized by Piano Analytics SDKs. Please use flexible and powerful `at_` instead. Add campaign parameters to the links pointing to your site: If the link points to the root of the site or a directory: `https://www.site.com/?at_medium=email&at_campaign=new_offer...` If the link points to a file with no variable transmitted: `https://www.site.com/index.php?at_medium=email&at_campaign=new_offer...` If the link leads to a file with a transmitted variable: `https://www.site.com/index.php?other_variable=2&at_medium=email&at_campaign=new_offer...` > note: > > The character `?` (or `&`, depending on the position of the variable) can be replaced by the character `#`. ### Campaign format | URL Parameter | Description | Detail | Format / Example | | ------------------------ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | | at_medium (mandatory) | Campaign medium | | at_medium=mymediumvalue | | at_campaign (mandatory) | Name of the campaign | | at_campaign=mycampaign | | at_\* | Customized properties of your campaign | Any querystring parameter starting with at_ will be considered a campaign parameter, and will be translated into a src_ property. You may need to create this src_\* in your data model. | at_creation=myvalue | #### Full example `https://www.site.com/?at_medium=mymedium&at_campaign=mycampaign&at_myproperty=myvalue&at_myotherproperty=myothervalue` This will result in the following properties: - `src_medium` : `mymedium` - `src_campaign` : `mycampaign` - `src_myproperty` : `myvalue` - `src_myotherproperty` : `myothervalue` You can also associate standard data model properties to your campaigns: | Property | Type | Example | | ------------------- | ------ | ------------------------- | | at_creation | string | at_creation=Main | | at_variant | string | at_variant=Red | | at_format | string | at_format=440x300 | | at_type | string | at_type=Direct | | at_campaign_group | string | at_campaign_group=Carlo | ## Email opening measurement In order to track email opening with Piano Analytics tagging, it is mandatory to build raw event, embedded in emails inside an `` tag. Event name: `email.display.offsite` Example: ```text // Raw event https:///event?s=&events=[{"name":"email.display.offsite","data":{"src_medium":"email","src_campaign":"email campaign"}}] // Embedded ``` ## Force visit marketing source It is possible to force the marketing source of a visit even if we’ve already retrieved another one on past events. For this, you have to set the `src_force` property (`boolean`) to `true`: ```js pa.sendEvent("page.display", { page: "page name", page_chapter1: "level 1", page_chapter2: "level 2", page_chapter3: "level 3", src_medium: "email", src_campaign: "launching", src_force: true, }); ``` > note: > > If several sources are forced during a visit, the last one filled in will be the one kept. > > The forced source is taken into account from the next day. The real-time functionalities (Data Query granular exports, or Data Flow) are still based on the classic source detection. ## UTM management > note: > > Automatic UTM links tracking only works with JS SDK. If you already use Google UTMs and you want to collect them into Piano Analytics, we offer you two options: ### Collect UTM as properties You can collect UTM parameters as Piano analytics properties. To do so, please use the `enableUTMTracking` configuration (`true` by default). ### Collect UTM as sources You can collect UTM parameters as marketing campaigns (sources). To do so, set the `campaignPrefix` configuration. For example, if you want to collect both `at_` and `utm_`, giving the priority to the first one, you can use: ```js pa.setConfiguration("campaignPrefix", ["at_", "utm_"]); ``` In that case, if no `at_` parameters are present, we will process the `utm_` ones. If you want to use custom UTM, you need to declare corresponding `src_` properties: | UTM | Piano Analytics native properties | Need to be declared? | | --------------------- | --------------------------------- | -------------------- | | utm_source | src_source | ❌ | | utm_medium | src_medium | ❌ | | utm_campaign | src_campaign | ❌ | | utm_term | src_term | ❌ | | utm_content | src_content | ❌ | | utm_custom (example) | \- | ✅ (src_custom) | To do so, you can consult the [dedicated documentation](https://analytics-docs.piano.io/en/analytics/v1/properties) or directly create properties in your [data management interface](https://analytics.piano.io/datamanagement/#/data-model/properties/list/). ## Mobile marketing campaigns On mobile, the marketing campaign properties need to be pushed in the tag. Example *Measure a marketing campaign source on a page.display.* ### Android ```java pa.sendEvent(new Event("page.display", new HashMap() {{ put("page", "Page name"); put("src_medium", "email"); put("src_campaign", "launching"); put("src_creation", "promotion"); put("src_myCustomProperty", "myCustomValue"); }})); ``` ### Apple ```swift pa.sendEvent(Event("page.display", data: [ "page": "Page name", "src_medium": "email", "src_campaign": "launching", "src_creation": "promotion", "src_myCustomProperty": "myCustomValue", ])) ``` > note: > > For XTOR migration please use the `xtor` to `at_` translation available in the [AS2 documentation](https://developers.atinternet-solutions.com/as2-tagging-en/javascript-en/campaigns-javascript-en/marketing-campaigns-v2/#translate-xtor-at__12). You can then use the translated campaign and change the `at_` parameters to `src_` as showcased above. --- ## Privacy > caution: > > Privacy Management is a legacy module to manage Privacy and consent within Piano Analytics. > > Started from PA SDK javascript 6.8, we've released a brand new ["Consent Management" module](/analytics/data-collection/how-to-send-events/consent/) to unify Privacy management and tagging methods across all Piano products. > > If you already have a legacy Privacy Management implementation or a mobile implementation, it will still be compatible and continue to work. Our Privacy methods allow you to control the data collected within the audience measurement solution, according to the different legislations to which you refer. It offers you the possibility to adapt your tagging thanks to a precise management of the different measurement parameters (events and properties sent, trackers used, …), in the respect of the regulation in force. We encourage you to first consult our [Privacy Center](https://analytics-docs.piano.io/en/analytics/v1/privacy-center) in order to set up the appropriate tagging. Don't hesitate to involve your legal team and/or you DPO in the process. ## Key notions A Privacy Mode is a Privacy state where you can manage different options : - The cookies (or storage for mobile) you want to set - The events / properties you want to send - The value your "visitor_privacy_mode" and "visitor_privacy_consent" properties will take Basically, we can say that a Privacy Mode refers to a specific purpose. ![Privacy](/analytics/assets/images/privacy-schema-2-90c9009e696fb54a7797d022ed1c5c11.png) Let's take another example: We start in the same way as the schema above. When a visitor lands to your page, you have not yet collected its consent. So you do not want to set cookies, and only collect anonymized data. So you will use a specific Privacy Mode to achieve this behavior: `no-consent`. Then, when the visitor consents, you will want to start dropping a visitor cookie, and send all the information contained in your tagging. To do this you will use another specific Privacy Mode: `optin`. Finally, the visitor could also have consented to a purpose other than opt-in. In that case, you can create a Privacy Mode that fits to your Privacy needs. I can create an `advertising` mode I will use to set Users cookies, and send some advertising information. Thanks to the "visitor_privacy_mode" and "visitor_privacy_consent", you will be able to respect a perfect data governance by applying dedicated treatments depending on the mode the data has been collected. ## Default Privacy Modes | Privacy Mode | "pa_vid" cookie | Visitor ID | visitor_privacy_mode | visitor_privacy_consent | Properties / events | Exclusion / Anonymization | Comment | | ------------ | ---------------- | --------------- | ---------------------- | ------------------------- | ------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | optin | ✅ | GUID | optin | true | all | ❌ | | | exempt | ✅ | GUID | exempt | false | some | ❌ | Requires a specific configuration as explained in our [Privacy center](https://analytics-docs.piano.io/en/analytics/v1/consent-exemption-configuration) | | no-storage | ❌ | Finger Printing | no-storage | false | all | ❌ | | | no-consent | ❌ | ❌ | no-consent | false | some | ✅ | Based on a specic processing option you must request from our support center. All events will be excluded and anonymized. More information in our [Privacy Center](https://analytics-docs.piano.io/en/analytics/v1/pseudonymization-and-anonymization) | | optout | ✅ | ❌ | optout | false | some | ✅ | All events will be excluded and anonymized. More information in our [Privacy Center](https://analytics-docs.piano.io/en/analytics/v1/pseudonymization-and-anonymization) | | custom | you decide | you decide | you decide | you decide | you decide (same base as exempt mode) | ❌ | Some cookies, properties and events are included by default to a custom mode | > tip: > > Each mode has by default its own rules. > > You can check which storage keys (cookies), properties and events are included by default in [the dedicated article](/analytics/data-collection/privacy/modes-rules/). You can also find the list of our cookies and storage keys in the [Cookies & storage](/analytics/data-collection/general/cookie-storage/) article. > caution: > > If you want to use the ePrivacy exemption collection (or Hybrid measurement), please refer to our [documentation](https://analytics-docs.piano.io/en/analytics/v1/consent-exemption-configuration). > > Some legal steps are mandatory. ## Set a Privacy Mode You don't have to modify your event tagging depending on a specific consent. The Privacy Mode will be in charge of sending the right information, depending on what you have configured. It will be stored in a `pa_privacy` cookie, and will be used on all events until it is modified, or until the cookie is deleted. ### JavaScript Method: `pa.privacy.setMode(mode)` | Parameters | Type | Description | | ---------- | ------ | ------------ | | mode | string | Privacy Mode | ```js pa.privacy.setMode("optin"); ``` > note: > > If you don't set any Privacy Mode (and none stored), the value set for configuration `privacyDefaultMode` will be applied by default. ### Android (3.3.0+) ```kotlin val privacyModesStorage = PianoAnalytics.getInstance().privacyModesStorage privacyModesStorage.currentMode = PrivacyMode.OPTIN ``` Available values: - `PrivacyMode.OPTIN` - `PrivacyMode.OPTOUT` - `PrivacyMode.EXEMPT` - `PrivacyMode.NO_CONSENT` - `PrivacyMode.NO_STORAGE` > note: > > If you don't set any Privacy Mode (and none stored), the value set for configuration `defaultPrivacyMode` will be applied by default. ### Android Method: `func PianoAnalytics.privacySetMode(mode) -> void` | Parameters | Type | Description | | ---------- | ------ | ------------ | | mode | String | Privacy Mode | ```java pa.privacySetMode("optin"); ``` > note: > > If you don't set any Privacy Mode (and none stored), the value set for configuration `privacyDefaultMode` will be applied by default. ### Apple Method: `pa.privacySetMode(_ mode: String)` | Parameters | Type | Description | | ---------- | ------ | ------------ | | mode | String | Privacy Mode | ```swift pa.privacySetMode("optin"); ``` > note: > > If you don't set any Privacy Mode (and none stored), the value set for configuration `privacyDefaultMode` will be applied by default. ## Get a Privacy Mode If you want to know the current mode used by the SDK, you can use the following method: Method: `pa.privacy.getMode()` ```js pa.privacy.getMode(); // Return a string with the Privacy Mode value ``` ```kotlin val privacyModesStorage = PianoAnalytics.getInstance().privacyModesStorage val currentPrivacyMode = privacyModesStorage.currentMode ``` Method: `func PianoAnalytics.privacyGetMode(PianoAnalytics.OnGetPrivacyModeListener) -> void` ```java pa.privacyGetMode(privacyMode -> { // do something with user }); ``` Method: `pa.privacyGetMode(completionHandler: ((_ privacyMode: String) -> Void)?)` ```swift pa.privacyGetMode { privacyMode in print(privacyMode) } ``` ## Manage a Privacy Mode You can manage your Privacy Modes by controlling the storage, properties and events. ### Storage You can include one or more storage keys to your current Privacy Mode (in addition to those already included). Method: `pa.privacy.include.storageKey(key[, modes])` | Parameters | Type | Description | | ---------- | ------ | ------------------------------------------------------------------ | | key | string | Privacy Mode | | modes | array | Privacy modes where you want to include the storage key (optional) | ```js pa.privacy.include.storageKey("pa_vid"); // Will be included in all modes pa.privacy.include.storageKey("pa_uid", ["exempt", "customMode"]); // Will be included in selected modes ``` Method: `pa.privacy.include.storageKeys(keysArray[, modes])` | Parameters | Type | Description | | ---------- | ----- | ------------------------------------------------------------------ | | keysArray | array | Privacy Modes | | modes | array | Privacy modes where you want to include the storage key (optional) | ```js pa.privacy.include.storageKeys(["pa_vid", "pa_uid"]); // Will be included in all modes pa.privacy.include.storageKeys(["pa_vid", "pa_uid"], ["exempt", "customMode"]); // Will be included in selected modes ``` ```kotlin PrivacyMode.EXEMPT.allowedStorageFeatures += PrivacyStorageFeature.VISITOR ``` Available values: - `PrivacyStorageFeature.ALL` - `PrivacyStorageFeature.VISITOR` - `PrivacyStorageFeature.USER` - `PrivacyStorageFeature.PRIVACY` - `PrivacyStorageFeature.CRASH` - `PrivacyStorageFeature.LIFECYCLE` Method: `func PianoAnalytics.privacyIncludeStorageKey(storageKey) -> void` `func PianoAnalytics.privacyIncludeStorageKey(storageKey, privacyModes) -> void` | Parameters | Type | Description | | ------------ | ------------------------------------ | ------------------------------------------------------------------ | | storageKey | PianoAnalytics.PrivacyStorageFeature | Privacy Mode | | privacyModes | String\[\] | Privacy modes where you want to include the storage key (optional) | ```java pa.privacyIncludeStorageKey(PianoAnalytics.PrivacyStorageFeature.USER); // Will be included in all modes pa.privacyIncludeStorageKey(PianoAnalytics.PrivacyStorageFeature.USER, new String[]{"exempt"}); // Will be included in selected modes ``` Method: `func PianoAnalytics.privacyIncludeStorageKeys(storageKeys) -> void` `func PianoAnalytics.privacyIncludeStorageKeys(storageKeys, privacyModes) -> void` | Parameters | Type | Description | | ------------ | ---------------------------------------- | ------------------------------------------------------------------ | | storageKeys | PianoAnalytics.PrivacyStorageFeature\[\] | Privacy Modes | | privacyModes | String\[\] | Privacy modes where you want to include the storage key (optional) | ```java pa.privacyIncludeStorageKeys(new PianoAnalytics.PrivacyStorageFeature[]{PianoAnalytics.PrivacyStorageFeature.USER, PianoAnalytics.PrivacyStorageFeature.LIFECYCLE}); // Will be included in all modes pa.privacyIncludeStorageKeys(new PianoAnalytics.PrivacyStorageFeature[]{PianoAnalytics.PrivacyStorageFeature.USER, PianoAnalytics.PrivacyStorageFeature.LIFECYCLE}, new String[]{"exempt"}); // Will be included in selected modes ``` Method: `pa.privacyIncludeStorageKey(_ storageKey: String, privacyModes: [String]? = ["*"])` | Parameters | Type | Description | | ------------ | ----------- | ------------------------------------------------------------------ | | storageKey | String | Privacy Mode | | privacyModes | \[String\]? | Privacy modes where you want to include the storage key (optional) | ```swift pa.privacyIncludeStorageKey(PA.Privacy.Storage.User); // Will be included in all modes pa.privacyIncludeStorageKey(PA.Privacy.Storage.User, privacyModes: ["exempt"]); // Will be included in selected modes ``` Method: `pa.privacyIncludeStorageKeys(_ storageKeys: [String], privacyModes: [String]? = ["*"])` | Parameters | Type | Description | | ------------ | ----------- | ------------------------------------------------------------------ | | storageKeys | \[String\] | Privacy Modes | | privacyModes | \[String\]? | Privacy modes where you want to include the storage key (optional) | ```swift pa.privacyIncludeStorageKeys([PA.Privacy.Storage.User, PA.Privacy.Storage.Lifecycle]); // Will be included in all modes pa.privacyIncludeStorageKeys([PA.Privacy.Storage.User, PA.Privacy.Storage.Lifecycle], privacyModes: ["exempt"]); // Will be included in selected modes ``` You can exclude one or more storage keys to your current Privacy Mode (in addition to those already excluded). Method: `pa.privacy.exclude.storageKey(key[, modes])` | Parameters | Type | Description | | ---------- | ------ | ------------------------------------------------------------------ | | key | string | Privacy Mode | | modes | array | Privacy modes where you want to exclude the storage key (optional) | ```js pa.privacy.exclude.storageKey("pa_uid"); // Will be excluded in all modes pa.privacy.exclude.storageKey("pa_uid", ["exempt", "customMode"]); // Will be excluded in selected modes ``` Method: `pa.privacy.exclude.storageKeys(keysArray[, modes])` | Parameters | Type | Description | | ---------- | ----- | ------------------------------------------------------------------ | | keysArray | array | Privacy Modes | | modes | array | Privacy modes where you want to exclude the storage key (optional) | ```js pa.privacy.exclude.storageKeys(["pa_vid", "pa_uid"]); // Will be excluded in all modes pa.privacy.exclude.storageKeys(["pa_vid", "pa_uid"], ["exempt", "customMode"]); // Will be excluded in selected modes ``` ```kotlin PrivacyMode.EXEMPT.forbiddenStorageFeatures += PrivacyStorageFeature.VISITOR ``` Available values: - `PrivacyStorageFeature.ALL` - `PrivacyStorageFeature.VISITOR` - `PrivacyStorageFeature.USER` - `PrivacyStorageFeature.PRIVACY` - `PrivacyStorageFeature.CRASH` - `PrivacyStorageFeature.LIFECYCLE` Method: `func PianoAnalytics.privacyExcludeStorageKey(storageKey) -> void` `func PianoAnalytics.privacyExcludeStorageKey(storageKey, privacyModes) -> void` | Parameters | Type | Description | | ------------ | ------------------------------------ | ------------------------------------------------------------------ | | storageKey | PianoAnalytics.PrivacyStorageFeature | Privacy Mode | | privacyModes | String\[\] | Privacy modes where you want to exclude the storage key (optional) | ```java pa.privacyExcludeStorageKey(PianoAnalytics.PrivacyStorageFeature.USER); // Will be excluded in all modes pa.privacyExcludeStorageKey(PianoAnalytics.PrivacyStorageFeature.USER, new String[]{"exempt"}); // Will be excluded in selected modes ``` Method: `func PianoAnalytics.privacyExcludeStorageKeys(storageKeys) -> void` `func PianoAnalytics.privacyExcludeStorageKeys(storageKeys, privacyModes) -> void` | Parameters | Type | Description | | ------------ | ---------------------------------------- | ------------------------------------------------------------------ | | storageKeys | PianoAnalytics.PrivacyStorageFeature\[\] | Privacy Modes | | privacyModes | String\[\] | Privacy modes where you want to exclude the storage key (optional) | ```java pa.privacyExcludeStorageKeys(new PianoAnalytics.PrivacyStorageFeature[]{PianoAnalytics.PrivacyStorageFeature.USER, PianoAnalytics.PrivacyStorageFeature.LIFECYCLE}); // Will be excluded in all modes pa.privacyExcludeStorageKeys(new PianoAnalytics.PrivacyStorageFeature[]{PianoAnalytics.PrivacyStorageFeature.USER, PianoAnalytics.PrivacyStorageFeature.LIFECYCLE}, new String[]{"exempt"}); // Will be excluded in selected modes ``` Method: `pa.privacyExcludeStorageKey(_ storageKey: String, privacyModes: [String]? = ["*"])` | Parameters | Type | Description | | ------------ | ----------- | ------------------------------------------------------------------ | | storageKey | String | Privacy Mode | | privacyModes | \[String\]? | Privacy modes where you want to exclude the storage key (optional) | ```swift pa.privacyExcludeStorageKey(PA.Privacy.Storage.User); // Will be excluded in all modes pa.privacyExcludeStorageKey(PA.Privacy.Storage.User, privacyModes: ["exempt"]); // Will be excluded in selected modes ``` Method: `pa.privacyExcludeStorageKeys(_ storageKeys: [String], privacyModes: [String]? = ["*"])` | Parameters | Type | Description | | ------------ | ----------- | ------------------------------------------------------------------ | | storageKeys | \[String\] | Privacy Modes | | privacyModes | \[String\]? | Privacy modes where you want to exclude the storage key (optional) | ```swift pa.privacyExcludeStorageKeys([PA.Privacy.Storage.User, PA.Privacy.Storage.Lifecycle]); // Will be excluded in all modes pa.privacyExcludeStorageKeys([PA.Privacy.Storage.User, PA.Privacy.Storage.Lifecycle], privacyModes: ["exempt"]); // Will be excluded in selected modes ``` ### Properties You can include one or more properties to the following events you will send for your current Privacy Mode (in addition to those already included). Method: `pa.privacy.include.property(prop[, modes, events])` | Parameters | Type | Description | | ---------- | ------ | ---------------------------------------------------------- | | prop | string | Property you want to include | | modes | array | Privacy Modes (optional) | | events | array | Events on which the properties will be included (optional) | ```js pa.privacy.include.property("article_category"); // Will be included in all modes pa.privacy.include.property("article_category", ["exempt", "customMode"]); // Will be included in selected modes pa.privacy.include.property("article_category", null, [ "page.display", "click.*", ]); // Will be included for all modes, but only selected events ``` Method: `pa.privacy.include.properties(propsArray[, modes, events])` | Parameters | Type | Description | | ---------- | ----- | ---------------------------------------------------------- | | propsArray | array | Properties you want to include | | modes | array | Privacy Modes (optional) | | events | array | Events on which the properties will be included (optional) | ```js pa.privacy.include.properties(["article_category", "article_date"]); // Will be included in all modes pa.privacy.include.properties( ["article_category", "article_date"], ["exempt", "customMode"] ); // Will be included in selected modes pa.privacy.include.properties(["article_category", "article_date"], null, [ "page.display", "click.*", ]); // Will be included for all modes, but only selected events ``` ```kotlin PrivacyMode.EXEMPT.allowedPropertyKeys[Event.ANY]?.add(PropertyName("prop_name")) ``` Method: `func PianoAnalytics.privacyIncludeProperty(property) -> void` `func PianoAnalytics.privacyIncludeProperty(property, privacyModes) -> void` `func PianoAnalytics.privacyIncludeProperty(property, privacyModes, eventNames) -> void` | Parameters | Type | Description | | ------------ | ---------- | ---------------------------------------------------------- | | property | String | Property you want to include | | privacyModes | String\[\] | Privacy Modes (optional) | | eventNames | String\[\] | Events on which the properties will be included (optional) | ```java pa.privacyIncludeProperty("article_category"); // Will be included in all modes pa.privacyIncludeProperty("article_category", new String[]{"exempt", "customMode"}); // Will be included in selected modes pa.privacyIncludeProperty("article_category", null, new String[]{"page.display", "click.*"}); // Will be included for all modes, but only selected events ``` Method: `func PianoAnalytics.privacyIncludeProperties(properties) -> void` `func PianoAnalytics.privacyIncludeProperties(properties, privacyModes) -> void` `func PianoAnalytics.privacyIncludeProperties(properties, privacyModes, eventNames) -> void` | Parameters | Type | Description | | ------------ | ---------- | ---------------------------------------------------------- | | properties | String\[\] | Properties you want to include | | privacyModes | String\[\] | Privacy Modes (optional) | | eventNames | String\[\] | Events on which the properties will be included (optional) | ```java pa.privacyIncludeProperties(new String[]{"article_category", "article_date"}); // Will be included in all modes pa.privacyIncludeProperties(new String[]{"article_category", "article_date"}, new String[]{"exempt", "customMode"}); // Will be included in selected modes pa.privacyIncludeProperties(new String[]{"article_category", "article_date"}, null, new String[]{"page.display", "click.*"}); // Will be included for all modes, but only selected events ``` Method: `pa.privacyIncludeProperty(_ property: String, privacyModes: [String]? = ["*"], eventNames: [String]? = ["*"])` | Parameters | Type | Description | | ------------ | ----------- | ---------------------------------------------------------- | | property | String | Property you want to include | | privacyModes | \[String\]? | Privacy Modes (optional) | | eventNames | \[String\]? | Events on which the properties will be included (optional) | ```swift pa.privacyIncludeProperty("article_category"); // Will be included in all modes pa.privacyIncludeProperty("article_category", privacyModes: ["exempt", "customMode"]); // Will be included in selected modes pa.privacyIncludeProperty("article_category", privacyModes: nil, eventNames: ["page.display", "click.*"]); // Will be included for all modes, but only selected events ``` Method: `pa.privacyIncludeProperties(_ properties: [String], privacyModes: [String]? = ["*"], eventNames: [String]? = ["*"])` | Parameters | Type | Description | | ------------ | ----------- | ---------------------------------------------------------- | | properties | \[String\] | Properties you want to include | | privacyModes | \[String\]? | Privacy Modes (optional) | | eventNames | \[String\]? | Events on which the properties will be included (optional) | ```swift pa.privacyIncludeProperties(["article_category", "article_date"]); // Will be included in all modes pa.privacyIncludeProperties(["article_category", "article_date"], privacyModes: ["exempt", "customMode"]); // Will be included in selected modes pa.privacyIncludeProperties(["article_category", "article_date"], privacyModes: nil, eventNames: ["page.display", "click.*"]); // Will be included for all modes, but only selected events ``` You can exclude one or more properties to the following events you will send for your current Privacy Mode (in addition to those already excluded). Method: `pa.privacy.exclude.property(prop[, modes, events])` | Parameters | Type | Description | | ---------- | ------ | ---------------------------------------------------------- | | prop | string | Property you want to include | | modes | array | Privacy Modes (optional) | | events | array | Events on which the properties will be excluded (optional) | ```js pa.privacy.exclude.property("article_category"); // Will be excluded in all modes pa.privacy.exclude.property("article_category", ["exempt", "customMode"]); // Will be excluded in selected modes pa.privacy.exclude.property("article_category", null, [ "page.display", "click.*", ]); // Will be excluded for all modes, but only selected events ``` Method: `pa.privacy.exclude.properties(propsArray[, modes, events])` | Parameters | Type | Description | | ---------- | ----- | ---------------------------------------------------------- | | propsArray | array | Properties you want to exclude | | modes | array | Privacy Modes (optional) | | events | array | Events on which the properties will be excluded (optional) | ```js pa.privacy.exclude.properties(["article_category", "article_date"]); // Will be excluded in all modes pa.privacy.exclude.properties( ["article_category", "article_date"], ["exempt", "customMode"] ); // Will be excluded in selected modes pa.privacy.exclude.properties(["article_category", "article_date"], null, [ "page.display", "click.*", ]); // Will be excluded for all modes, but only selected events ``` ```kotlin PrivacyMode.EXEMPT.forbiddenPropertyKeys[Event.ANY]?.add(PropertyName("prop_name")) ``` Method: `func PianoAnalytics.privacyExcludeProperty(property) -> void` `func PianoAnalytics.privacyExcludeProperty(property, privacyModes) -> void` `func PianoAnalytics.privacyExcludeProperty(property, privacyModes, eventNames) -> void` | Parameters | Type | Description | | ------------ | ---------- | ---------------------------------------------------------- | | property | String | Property you want to exclude | | privacyModes | String\[\] | Privacy Modes (optional) | | eventNames | String\[\] | Events on which the properties will be excluded (optional) | ```java pa.privacyExcludeProperty("article_category"); // Will be excluded in all modes pa.privacyExcludeProperty("article_category", new String[]{"exempt", "customMode"}); // Will be excluded in selected modes pa.privacyExcludeProperty("article_category", null, new String[]{"page.display", "click.*"}); // Will be excluded for all modes, but only selected events ``` Method: `func PianoAnalytics.privacyExcludeProperties(properties) -> void` `func PianoAnalytics.privacyExcludeProperties(properties, privacyModes) -> void` `func PianoAnalytics.privacyExcludeProperties(properties, privacyModes, eventNames) -> void` | Parameters | Type | Description | | ------------ | ---------- | ---------------------------------------------------------- | | properties | String\[\] | Properties you want to exclude | | privacyModes | String\[\] | Privacy Modes (optional) | | eventNames | String\[\] | Events on which the properties will be excluded (optional) | ```java pa.privacyExcludeProperties(new String[]{"article_category", "article_date"}); // Will be excluded in all modes pa.privacyExcludeProperties(new String[]{"article_category", "article_date"}, new String[]{"exempt", "customMode"}); // Will be excluded in selected modes pa.privacyExcludeProperties(new String[]{"article_category", "article_date"}, null, new String[]{"page.display", "click.*"}); // Will be excluded for all modes, but only selected events ``` Method: `pa.privacyExcludeProperty(_ property: String, privacyModes: [String]? = ["*"], eventNames: [String]? = ["*"])` | Parameters | Type | Description | | ------------ | ----------- | ---------------------------------------------------------- | | property | String | Property you want to exclude | | privacyModes | \[String\]? | Privacy Modes (optional) | | eventNames | \[String\]? | Events on which the properties will be excluded (optional) | ```swift pa.privacyExcludeProperty("article_category", privacyModes: ["exempt", "customMode"]); // Will be excluded in selected modes pa.privacyExcludeProperty("article_category", privacyModes: nil, eventNames: ["page.display", "click.*"]); // Will be excluded for all modes, but only selected events ``` Method: `pa.privacyExcludeProperties(_ properties: [String], privacyModes: [String]? = ["*"], eventNames: [String]? = ["*"])` | Parameters | Type | Description | | ------------ | ----------- | ---------------------------------------------------------- | | properties | \[String\] | Properties you want to exclude | | privacyModes | \[String\]? | Privacy Modes (optional) | | eventNames | \[String\]? | Events on which the properties will be excluded (optional) | ```swift pa.privacyExcludeProperties(["article_category", "article_date"]); // Will be excluded in all modes pa.privacyExcludeProperties(["article_category", "article_date"], privacyModes: ["exempt", "customMode"]); // Will be excluded in selected modes pa.privacyExcludeProperties(["article_category", "article_date"], privacyModes: nil, eventNames: ["page.display", "click.*"]); // Will be excluded for all modes, but only selected events ``` ### Events You can include one or more events that can be sent for your current Privacy Mode (in addition to those already included). Method: `pa.privacy.include.event(event[, modes])` | Parameters | Type | Description | | ---------- | ------ | ------------------------- | | event | string | Event you want to include | | modes | array | Privacy Modes (optional) | ```js pa.privacy.include.event("selfpromotion.impression"); // Will be included in all modes pa.privacy.include.event("selfpromotion.impression", ["exempt", "customMode"]); // Will be included in selected modes ``` Method: `pa.privacy.include.events(eventsArray[, modes])` | Parameters | Type | Description | | ----------- | ----- | -------------------------- | | eventsArray | array | Events you want to include | | modes | array | Privacy Modes (optional) | ```js pa.privacy.include.events(["selfpromotion.display", "selfpromotion.click"]); // Will be included in all modes pa.privacy.include.events( ["selfpromotion.display", "selfpromotion.click"], ["exempt", "customMode"] ); // Will be included in selected modes ``` ```kotlin PrivacyMode.EXEMPT.allowedEventNames += "selfpromotion.impression" ``` Method: `func PianoAnalytics.privacyIncludeEvent(eventName) -> void` `func PianoAnalytics.privacyIncludeEvent(eventName, privacyModes) -> void` | Parameters | Type | Description | | ------------ | ---------- | ------------------------- | | eventName | String | Event you want to include | | privacyModes | String\[\] | Privacy Modes (optional) | ```java pa.privacyIncludeEvent("selfpromotion.impression"); // Will be included in all modes pa.privacyIncludeEvent("selfpromotion.impression", new String[]{"exempt", "customMode"}); // Will be included in selected modes ``` Method: `func PianoAnalytics.privacyIncludeEvents(eventNames) -> void` `func PianoAnalytics.privacyIncludeEvents(eventNames, privacyModes) -> void` | Parameters | Type | Description | | ------------ | ---------- | -------------------------- | | eventNames | String\[\] | Events you want to include | | privacyModes | String\[\] | Privacy Modes (optional) | ```java pa.privacyIncludeEvents(new String[]{"selfpromotion.impression", "selfpromotion.click"}); // Will be included in all modes pa.privacyIncludeEvents(new String[]{"selfpromotion.impression", "selfpromotion.click"}, new String[]{"exempt", "customMode"}); // Will be included in selected modes ``` Method: `pa.privacyIncludeEvent(_ eventName: String, privacyModes: [String] = ["*"])` | Parameters | Type | Description | | ------------ | ---------- | ------------------------- | | eventName | String | Event you want to include | | privacyModes | \[String\] | Privacy Modes (optional) | ```swift pa.privacyIncludeEvent("selfpromotion.impression"); // Will be included in all modes pa.privacyIncludeEvent("selfpromotion.impression", privacyModes: ["exempt", "customMode"]); // Will be included in selected modes ``` Method: `pa.privacyIncludeEvents(_ eventNames: [String], privacyModes: [String] = ["*"])` | Parameters | Type | Description | | ------------ | ---------- | -------------------------- | | eventNames | \[String\] | Events you want to include | | privacyModes | \[String\] | Privacy Modes (optional) | ```swift pa.privacyIncludeEvents(["selfpromotion.display","selfpromotion.click"]); // Will be included in all modes pa.privacyIncludeEvents(["selfpromotion.display","selfpromotion.click"], privacyModes: ["exempt","customMode"]); // Will be included in selected modes ``` You can exclude one or more events that can be sent for your current Privacy Mode (in addition to those already excluded). Method: `pa.privacy.exclude.event(event[, modes])` | Parameters | Type | Description | | ---------- | ------ | ------------------------- | | event | string | Event you want to include | | modes | array | Privacy Modes (optional) | ```js pa.privacy.exclude.event("selfpromotion.display"); // Will be excluded in all modes pa.privacy.exclude.event("selfpromotion.display", ["exempt", "customMode"]); // Will be excluded in selected modes ``` Method: `pa.privacy.exclude.events(eventsArray[, modes, events])` | Parameters | Type | Description | | ----------- | ----- | ------------------------- | | eventsArray | array | Event you want to exclude | | modes | array | Privacy Modes (optional) | ```js pa.privacy.exclude.events(["selfpromotion.display", "selfpromotion.click"]); // Will be excluded in all modes pa.privacy.exclude.events( ["selfpromotion.display", "selfpromotion.click"], ["exempt", "customMode"] ); // Will be excluded in selected modes ``` ```kotlin PrivacyMode.EXEMPT.forbiddenEventNames += "selfpromotion.impression" ``` Method: `func PianoAnalytics.privacyExcludeEvent(eventName) -> void` `func PianoAnalytics.privacyExcludeEvent(eventName, privacyModes) -> void` | Parameters | Type | Description | | ------------ | ---------- | ------------------------- | | eventName | String | Event you want to exclude | | privacyModes | String\[\] | Privacy Modes (optional) | ```java pa.privacyExcludeEvent("selfpromotion.impression"); // Will be excluded in all modes pa.privacyExcludeEvent("selfpromotion.impression", new String[]{"exempt", "customMode"}); // Will be excluded in selected modes ``` Method: `func PianoAnalytics.privacyExcludeEvents(eventNames) -> void` `func PianoAnalytics.privacyExcludeEvents(eventNames, privacyModes) -> void` | Parameters | Type | Description | | ------------ | ---------- | -------------------------- | | eventNames | String\[\] | Events you want to exclude | | privacyModes | String\[\] | Privacy Modes (optional) | ```java pa.privacyExcludeEvents(new String[]{"selfpromotion.impression", "selfpromotion.click"}); // Will be excluded in all modes pa.privacyExcludeEvents(new String[]{"selfpromotion.impression", "selfpromotion.click"}, new String[]{"exempt", "customMode"}); // Will be excluded in selected modes ``` Method: `pa.privacyExcludeEvent(_ eventName: String, privacyModes: [String] = ["*"])` | Parameters | Type | Description | | ------------ | ---------- | ------------------------- | | eventName | String | Event you want to exclude | | privacyModes | \[String\] | Privacy Modes (optional) | ```swift pa.privacyExcludeEvent("selfpromotion.impression"); // Will be excluded in all modes pa.privacyExcludeEvent("selfpromotion.impression", privacyModes: ["exempt", "customMode"]); // Will be excluded in selected modes ``` Method: `pa.privacyExcludeEvents(_ eventNames: [String], privacyModes: [String] = ["*"])` | Parameters | Type | Description | | ------------ | ---------- | -------------------------- | | eventNames | \[String\] | Events you want to exclude | | privacyModes | \[String\] | Privacy Modes (optional) | ```swift pa.privacyExcludeEvents(["selfpromotion.display","selfpromotion.click"]); // Will be excluded in all modes pa.privacyExcludeEvents(["selfpromotion.display","selfpromotion.click"], privacyModes: ["exempt","customMode"]); // Will be excluded in selected modes ``` ## Custom Privacy Modes If our default Privacy Modes do not meet your expectations, you can create your own modes. Method: `pa.privacy.createMode(modeName, consentValue)` | Parameters | Type | Description | | ------------ | ------- | -------------------------------------------------------------------------------------------------------- | | modeName | string | Privacy Mode you will use in your tagging and that will be sent in the "visitor_privacy_mode" property | | consentValue | boolean | Privacy consent that will be sent in the "visitor_privacy_consent" property | ```js pa.privacy.createMode("customMode", true); // Create my mode pa.privacy.include.properties( ["my_property", "my_second_property"], "customMode" ); // Properties will be included in the mode I've created // or pa.privacy.include.property("*", "customMode"); // All properties will be included in the mode I've created pa.privacy.setMode("customMode"); // Set my mode ``` ```kotlin // create new privacy mode val myCustomPrivacyMode = PrivacyMode( visitorMode = "name", visitorConsent = true ) // forbid all storage features for new mode myCustomPrivacyMode.forbiddenStorageFeatures += PrivacyStorageFeature.ALL // register the new privacy mode privacyModesStorage.allModes += myCustomPrivacyMode // set current privacy mode (should be registered before, if custom) privacyModesStorage.currentMode = myCustomPrivacyMode ``` Method: `func PianoAnalytics.privacyCreateMode(mode, visitorConsent)` | Parameters | Type | Description | | -------------- | ------- | ------------------------------------------------------------------------------------------------------ | | mode | String | Privacy Mode you will use in your tagging and that will be sent in the visitor_privacy_mode property | | visitorConsent | Boolean | Privacy consent that will be sent in the visitor_privacy_consent property | ```java pa.privacyCreateMode("customMode", true); // Create my mode pa.privacyIncludeProperties(new String[]{"my_property", "my_second_property"}, new String[]{"customMode"}); // Properties will be included in the mode I've created // or pa.privacyIncludeProperty("*", new String[]{"customMode"}); // All properties will be included in the mode I've created pa.privacySetMode("customMode"); // Set my mode ``` Method: `pa.privacyCreateMode(_ mode: String, visitorConsent: Bool)` | Parameters | Type | Description | | -------------- | ------ | ------------------------------------------------------------------------------------------------------ | | mode | String | Privacy Mode you will use in your tagging and that will be sent in the visitor_privacy_mode property | | visitorConsent | Bool | Privacy consent that will be sent in the visitor_privacy_consent property | ```swift pa.privacyCreateMode("customMode", visitorConsent: true) // Create my mode pa.privacyIncludeProperties(["my_property", "my_second_property"], privacyModes: ["customMode"]) // Properties will be included in the mode I've created // or pa.privacyIncludeProperty("*", privacyModes: ["customMode"]) // All properties will be included in the mode I've created pa.privacySetMode("customMode") // Set my mode ``` > note: > > `visitor_privacy_consent` can be used in Explorer or Data Query if you want to filter on users that have given consent or not. > > We also use it in Data Flow to filter your stream, and Stream Inspector to filter your sessions. --- ## Sales Insights (ECommerce) Sales Insight has multiple premade analyses that are based on native events but also on the properties that are currently tracked. It allows you to send events at different steps of the purchase funnel to give you a detailed view from start to finish. You'll first have the products impressions, the creation and evolution of the cart and its content to finally have a transaction. > note: > > These are examples, the property list can be changed to fit your needs. You can very well remove properties and add custom properties on top. Please note that the implementation in those examples represents best practices whenever you want to fill the premade analyses available in the Piano Analytics interfaces. ## Product events ### `product.display` Mandatory property: `product_id` Impression of a product on a given page. Aside from the `product_id` that is mandatory, this implementation is recommended at least to allow you to fill all of the premade analyses in the interface. ### Javascript ```js pa.sendEvent('product.display', { 'product_id' : 'LPTAX174', // mandatory 'product' : 'Laptop AX174', 'product_variant' : '8Go RAM', 'product_brand' : 'Laptop', 'product_discount' : false, 'product_placement' : 'banner', 'product_pricetaxincluded' : 1399.9, 'product_pricetaxfree' : 1120.9, 'product_stock' : true, 'product_category1' : 'Hardware', 'product_category2' : 'Computer', 'product_category3' : 'Gaming', 'product_category4' : 'Laptop', }); ``` ### Android (3.3.0+) ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("product.display") .properties( Property(PropertyName("product_id"), "LPTAX174"), // mandatory Property(PropertyName("product"), "Laptop AX174"), Property(PropertyName("product_variant"), "8Go RAM"), Property(PropertyName("product_brand"), "Laptop"), Property(PropertyName("product_discount"), false), Property(PropertyName("product_placement"), "banner"), Property(PropertyName("product_pricetaxincluded"), 1399.9), Property(PropertyName("product_pricetaxfree"), 1120.9), Property(PropertyName("product_stock"), true), Property(PropertyName("product_category1"), "Hardware"), Property(PropertyName("product_category2"), "Computer"), Property(PropertyName("product_category3"), "Gaming"), Property(PropertyName("product_category4"), "Laptop"), ) .build() ) ``` ### Android ```java pa.sendEvent(new Event("product.display", new HashMap() {{ put("product_id", "LPTAX174"); // mandatory put("product", "Laptop AX174"); put("product_variant", "8Go RAM"); put("product_brand", "Laptop"); put("product_discount", false); put("product_placement", "banner"); put("product_pricetaxincluded", 1399.9); put("product_pricetaxfree", 1120.9); put("product_stock", true); put("product_category1", "Hardware"); put("product_category2", "Computer"); put("product_category3", "Gaming"); put("product_category4", "Laptop"); }})); ``` ### Apple ```swift pa.sendEvent(Event("product.display", data: [ "product_id" : "LPTAX174", // mandatory "product" : "Laptop AX174", "product_variant" : "8Go RAM", "product_brand" : "Laptop", "product_discount" : false, "product_placement" : "banner", "product_pricetaxincluded" : 1399.9, "product_pricetaxfree" : 1120.9, "product_stock" : true, "product_category1" : "Hardware", "product_category2" : "Computer", "product_category3" : "Gaming", "product_category4" : "Laptop" ])) ``` ### Flutter ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "product.display", properties: [ Property.string(name: "product_id", value: "LPTAX174"), // mandatory Property.string(name: "product", value: "Laptop AX174"), Property.string(name: "product_variant", value: "8Go RAM"), Property.string(name: "product_brand", value: "Laptop"), Property.bool(name: "product_discount", value: false), Property.string(name: "product_placement", value: "banner"), Property.int(name: "product_pricetaxincluded", value: 1399.9), Property.int(name: "product_pricetaxfree", value: 1120.9), Property.bool(name: "product_stock", value: true), Property.string(name: "product_category1", value: "Hardware"), Property.string(name: "product_category2", value: "Computer"), Property.string(name: "product_category3", value: "Gaming"), Property.string(name: "product_category4", value: "Laptop"), ]) ]); ``` ### HTTP ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "product.display", "data": { "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop" } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=product.display&props=[["product_id","LPTAX174",true],["product","Laptop AX174"],["product_variant","8Go RAM"],["product_brand","Laptop"],["product_discount","false"],["product_placement","banner"],["product_pricetaxincluded","1399.9"],["product_pricetaxfree","1120.9"],["product_stock","true"],["product_category1","Hardware"],["product_category2","Computer"],["product_category3","Gaming"],["product_category4","Laptop"]]) ### `product.page_display` Mandatory property: `product_id` Impression of a product page. Aside from the `product_id` that is mandatory, this implementation is recommended at least to allow you to fill all of the premade analyses in the interface. ```js pa.sendEvent('product.page_display', { 'product_id' : 'LPTAX174', // mandatory 'product' : 'Laptop AX174', 'product_variant' : '8Go RAM', 'product_brand' : 'Laptop', 'product_discount' : false, 'product_placement' : 'banner', 'product_pricetaxincluded' : 1399.9, 'product_pricetaxfree' : 1120.9, 'product_stock' : true, 'product_category1' : 'Hardware', 'product_category2' : 'Computer', 'product_category3' : 'Gaming', 'product_category4' : 'Laptop', }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("product.page_display") .properties( Property(PropertyName("product_id"), "LPTAX174"), // mandatory Property(PropertyName("product"), "Laptop AX174"), Property(PropertyName("product_variant"), "8Go RAM"), Property(PropertyName("product_brand"), "Laptop"), Property(PropertyName("product_discount"), false), Property(PropertyName("product_placement"), "banner"), Property(PropertyName("product_pricetaxincluded"), 1399.9), Property(PropertyName("product_pricetaxfree"), 1120.9), Property(PropertyName("product_stock"), true), Property(PropertyName("product_category1"), "Hardware"), Property(PropertyName("product_category2"), "Computer"), Property(PropertyName("product_category3"), "Gaming"), Property(PropertyName("product_category4"), "Laptop"), ) .build() ) ``` ```java pa.sendEvent(new Event("product.page_display", new HashMap() {{ put("product_id", "LPTAX174"); // mandatory put("product", "Laptop AX174"); put("product_variant", "8Go RAM"); put("product_brand", "Laptop"); put("product_discount", false); put("product_placement", "banner"); put("product_pricetaxincluded", 1399.9); put("product_pricetaxfree", 1120.9); put("product_stock", true); put("product_category1", "Hardware"); put("product_category2", "Computer"); put("product_category3", "Gaming"); put("product_category4", "Laptop"); }})); ``` ```swift pa.sendEvent(Event("product.page_display", data: [ "product_id" : "LPTAX174", // mandatory "product" : "Laptop AX174", "product_variant" : "8Go RAM", "product_brand" : "Laptop", "product_discount" : false, "product_placement" : "banner", "product_pricetaxincluded" : 1399.9, "product_pricetaxfree" : 1120.9, "product_stock" : true, "product_category1" : "Hardware", "product_category2" : "Computer", "product_category3" : "Gaming", "product_category4" : "Laptop" ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "product.page_display", properties: [ Property.string(name: "product_id", value: "LPTAX174"), // mandatory Property.string(name: "product", value: "Laptop AX174"), Property.string(name: "product_variant", value: "8Go RAM"), Property.string(name: "product_brand", value: "Laptop"), Property.bool(name: "product_discount", value: false), Property.string(name: "product_placement", value: "banner"), Property.int(name: "product_pricetaxincluded", value: 1399.9), Property.int(name: "product_pricetaxfree", value: 1120.9), Property.bool(name: "product_stock", value: true), Property.string(name: "product_category1", value: "Hardware"), Property.string(name: "product_category2", value: "Computer"), Property.string(name: "product_category3", value: "Gaming"), Property.string(name: "product_category4", value: "Laptop"), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "product.page_display", "data": { "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop" } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=product.page_display&props=[["product_id","LPTAX174",true],["product","Laptop AX174"],["product_variant","8Go RAM"],["product_brand","Laptop"],["product_discount","false"],["product_placement","banner"],["product_pricetaxincluded","1399.9"],["product_pricetaxfree","1120.9"],["product_stock","true"],["product_category1","Hardware"],["product_category2","Computer"],["product_category3","Gaming"],["product_category4","Laptop"]]) ### `product.add_to_cart` Mandatory properties: `product_id` Add a product to a cart. Aside from the `product_id` that is mandatory, this implementation is recommended at least to allow you to fill all of the premade analyses in the interface. Adding the cart.creation event is only needed whenever the 'product.add_to_cart' creates a new cart. ```js pa.sendEvents([ { 'name': 'product.add_to_cart', 'data': { 'cart_id': 'LAPW221C', 'product_id': 'LPTAX174' // mandatory, 'product': 'Laptop AX174', 'product_variant': '8Go RAM', 'product_brand': 'Laptop', 'product_discount': false, 'product_placement': 'banner', 'product_pricetaxincluded': 1399.9, 'product_pricetaxfree': 1120.9, 'product_stock': true, 'product_category1': 'Hardware', 'product_category2': 'Computer', 'product_category3': 'Gaming', 'product_category4': 'Laptop', 'product_quantity': 1, 'product_cartcreation': true } }, { 'name': 'cart.creation', 'data': { 'cart_id': 'LAPW221C' // mandatory, 'cart_currency': 'EUR', 'cart_turnovertaxincluded': 1399.9, 'cart_turnovertaxfree': 1120.9, 'cart_quantity': 1, 'cart_nbdistinctproduct': 1 } } ]); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("product.add_to_cart") .properties( Property(PropertyName("cart_id"), "LAPW221C"), Property(PropertyName("product_id"), "LPTAX174"), // mandatory Property(PropertyName("product"), "Laptop AX174"), Property(PropertyName("product_variant"), "8Go RAM"), Property(PropertyName("product_brand"), "Laptop"), Property(PropertyName("product_discount"), false), Property(PropertyName("product_placement"), "banner"), Property(PropertyName("product_pricetaxincluded"), 1399.9), Property(PropertyName("product_pricetaxfree"), 1120.9), Property(PropertyName("product_stock"), true), Property(PropertyName("product_category1"), "Hardware"), Property(PropertyName("product_category2"), "Computer"), Property(PropertyName("product_category3"), "Gaming"), Property(PropertyName("product_category4"), "Laptop"), Property(PropertyName("product_quantity"), 1), Property(PropertyName("product_cartcreation"), true), ) .build(), Event.Builder("cart.creation") .properties( Property(PropertyName("cart_id"), "LAPW221C"), // mandatory Property(PropertyName("cart_currency"), "EUR"), Property(PropertyName("cart_turnovertaxincluded"), 1399.9), Property(PropertyName("cart_turnovertaxfree"), 1120.9), Property(PropertyName("cart_quantity"), 1), Property(PropertyName("cart_nbdistinctproduct"), 1), ) .build() ) ``` ```java pa.sendEvents(Arrays.asList( new Event("product.add_to_cart", new HashMap() {{ put("cart_id", "LAPW221C"); put("product_id", "LPTAX174"); // mandatory put("product", "Laptop AX174"); put("product_variant", "8Go RAM"); put("product_brand", "Laptop"); put("product_discount", false); put("product_placement", "banner"); put("product_pricetaxincluded", 1399.9); put("product_pricetaxfree", 1120.9); put("product_stock", true); put("product_category1", "Hardware"); put("product_category2", "Computer"); put("product_category3", "Gaming"); put("product_category4", "Laptop"); put("product_quantity", 1); put("product_cartcreation", true); }}), new Event("cart.creation", new HashMap() {{ put("cart_id", "LAPW221C"); // mandatory put("cart_currency", "EUR"); put("cart_turnovertaxincluded", 1399.9); put("cart_turnovertaxfree", 1120.9); put("cart_quantity", 1); put("cart_nbdistinctproduct", 1); }}) )); ``` ```swift pa.sendEvents([ Event("product.add_to_cart", data: [ "cart_id": "LAPW221C", "product_id": "LPTAX174", // mandatory "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1, "product_cartcreation": true ]), Event("cart.creation", data: [ "cart_id": "LAPW221C", // mandatory "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1 ]) ]) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "product.add_to_cart", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), Property.string(name: "product_id", value: "LPTAX174"), // mandatory Property.string(name: "product", value: "Laptop AX174"), Property.string(name: "product_variant", value: "8Go RAM"), Property.string(name: "product_brand", value: "Laptop"), Property.bool(name: "product_discount", value: false), Property.string(name: "product_placement", value: "banner"), Property.int(name: "product_pricetaxincluded", value: 1399.9), Property.int(name: "product_pricetaxfree", value: 1120.9), Property.bool(name: "product_stock", value: true), Property.string(name: "product_category1", value: "Hardware"), Property.string(name: "product_category2", value: "Computer"), Property.string(name: "product_category3", value: "Gaming"), Property.string(name: "product_category4", value: "Laptop"), Property.int(name: "product_quantity", value: 1), Property.bool(name: "product_cartcreation", value: true), ]), Event(name: "cart.creation", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), // mandatory Property.string(name: "cart_currency", value: "EUR"), Property.int(name: "cart_turnovertaxincluded", value: 1399.9), Property.int(name: "cart_turnovertaxfree", value: 1120.9), Property.int(name: "cart_quantity", value: 1), Property.int(name: "cart_nbdistinctproduct", value: 1), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "product.add_to_cart", "data": { "cart_id": "LAPW221C", "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1, "product_cartcreation": true } },{ "name": "cart.creation", "data": { "cart_id": "LAPW221C", "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1 } }] }) }) ``` ### `product.remove_from_cart` Mandatory properties: `product_id` Remove a product from a cart. Aside from the `product_id` that is mandatory, this implementation is recommended at least to allow you to fill all of the premade analyses in the interface. ```js pa.sendEvent('product.remove_from_cart', { 'cart_id' : 'LAPW221C', 'product_id' : 'LPTAX174', // mandatory 'product' : 'Laptop AX174', 'product_variant' : '8Go RAM', 'product_brand' : 'Laptop', 'product_discount' : false, 'product_placement' : 'banner', 'product_pricetaxincluded' : 1399.9, 'product_pricetaxfree' : 1120.9, 'product_stock' : true, 'product_category1' : 'Hardware', 'product_category2' : 'Computer', 'product_category3' : 'Gaming', 'product_category4' : 'Laptop', 'product_quantity' : 1, }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("product.remove_from_cart") .properties( Property(PropertyName("cart_id"), "LAPW221C"), Property(PropertyName("product_id"), "LPTAX174"), // mandatory Property(PropertyName("product"), "Laptop AX174"), Property(PropertyName("product_variant"), "8Go RAM"), Property(PropertyName("product_brand"), "Laptop"), Property(PropertyName("product_discount"), false), Property(PropertyName("product_placement"), "banner"), Property(PropertyName("product_pricetaxincluded"), 1399.9), Property(PropertyName("product_pricetaxfree"), 1120.9), Property(PropertyName("product_stock"), true), Property(PropertyName("product_category1"), "Hardware"), Property(PropertyName("product_category2"), "Computer"), Property(PropertyName("product_category3"), "Gaming"), Property(PropertyName("product_category4"), "Laptop"), Property(PropertyName("product_quantity"), 1), ) .build() ) ``` ```java pa.sendEvent(new Event("product.remove_from_cart", new HashMap() {{ put("cart_id", "LAPW221C"); put("product_id", "LPTAX174"); // mandatory put("product", "Laptop AX174"); put("product_variant", "8Go RAM"); put("product_brand", "Laptop"); put("product_discount", false); put("product_placement", "banner"); put("product_pricetaxincluded", 1399.9); put("product_pricetaxfree", 1120.9); put("product_stock", true); put("product_category1", "Hardware"); put("product_category2", "Computer"); put("product_category3", "Gaming"); put("product_category4", "Laptop"); put("product_quantity", 1); }})); ``` ```swift pa.sendEvent(Event("product.remove_from_cart", data: [ "cart_id" : "LAPW221C", "product_id" : "LPTAX174", // mandatory "product" : "Laptop AX174", "product_variant" : "8Go RAM", "product_brand" : "Laptop", "product_discount" : false, "product_placement" : "banner", "product_pricetaxincluded" : 1399.9, "product_pricetaxfree" : 1120.9, "product_stock" : true, "product_category1" : "Hardware", "product_category2" : "Computer", "product_category3" : "Gaming", "product_category4" : "Laptop", "product_quantity" : 1 ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "product.remove_from_cart", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), Property.string(name: "product_id", value: "LPTAX174"), // mandatory Property.string(name: "product", value: "Laptop AX174"), Property.string(name: "product_variant", value: "8Go RAM"), Property.string(name: "product_brand", value: "Laptop"), Property.bool(name: "product_discount", value: false), Property.string(name: "product_placement", value: "banner"), Property.int(name: "product_pricetaxincluded", value: 1399.9), Property.int(name: "product_pricetaxfree", value: 1120.9), Property.bool(name: "product_stock", value: true), Property.string(name: "product_category1", value: "Hardware"), Property.string(name: "product_category2", value: "Computer"), Property.string(name: "product_category3", value: "Gaming"), Property.string(name: "product_category4", value: "Laptop"), Property.int(name: "product_quantity", value: 1), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "product.remove_from_cart", "data": { "cart_id": "LAPW221C", "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1 } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=product.remove_from_cart&props=[["cart_id","LAPW221C"],["product_id","LPTAX174",true],["product","Laptop AX174"],["product_variant","8Go RAM"],["product_brand","Laptop"],["product_discount","false"],["product_placement","banner"],["product_pricetaxincluded","1399.9"],["product_pricetaxfree","1120.9"],["product_stock","true"],["product_category1","Hardware"],["product_category2","Computer"],["product_category3","Gaming"],["product_category4","Laptop"],["product_quantity","1"]]) ## Cart events ### `cart.creation` Mandatory property: `cart_id` This event can be used alongside others or as a standalone event whenever a new cart is created. ```js pa.sendEvent('cart.creation', { 'cart_id' : 'LAPW221C', // mandatory 'cart_currency' : 'EUR', 'cart_turnovertaxincluded' : 1399.9, 'cart_turnovertaxfree' : 1120.9, 'cart_quantity' : 1, 'cart_nbdistinctproduct' : 1, }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("cart.creation") .properties( Property(PropertyName("cart_id"), "LAPW221C"), // mandatory Property(PropertyName("cart_currency"), "EUR"), Property(PropertyName("cart_turnovertaxincluded"), 1399.9), Property(PropertyName("cart_turnovertaxfree"), 1120.9), Property(PropertyName("cart_quantity"), 1), Property(PropertyName("cart_nbdistinctproduct"), 1), ) .build() ) ``` ```java pa.sendEvent(new Event("cart.creation", new HashMap() {{ put("cart_id", "LAPW221C"); // mandatory put("cart_currency", "EUR"); put("cart_turnovertaxincluded", 1399.9); put("cart_turnovertaxfree", 1120.9); put("cart_quantity", 1); put("cart_nbdistinctproduct", 1); }})); ``` ```swift pa.sendEvent(Event("cart.creation", data: [ "cart_id" : "LAPW221C", // mandatory "cart_currency" : "EUR", "cart_turnovertaxincluded" : 1399.9, "cart_turnovertaxfree" : 1120.9, "cart_quantity" : 1, "cart_nbdistinctproduct" : 1 ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "cart.creation", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), // mandatory Property.string(name: "cart_currency", value: "EUR"), Property.int(name: "cart_turnovertaxincluded", value: 1399.9), Property.int(name: "cart_turnovertaxfree", value: 1120.9), Property.int(name: "cart_quantity", value: 1), Property.int(name: "cart_nbdistinctproduct", value: 1), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "cart.creation", "data": { "cart_id": "LAPW221C", "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1 } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=cart.creation&props=[["cart_id","LAPW221C",true],["cart_currency","EUR"],["cart_turnovertaxincluded","1399.9"],["cart_turnovertaxfree","1120.9"],["cart_quantity","1"],["cart_nbdistinctproduct","1"]]) ### `cart.display` Mandatory property: `cart_id` This event can be sent everytime the cart page is loaded. ```js pa.sendEvent('cart.display', { 'cart_id' : 'LAPW221C', // mandatory 'cart_currency' : 'EUR', 'cart_turnovertaxincluded' : 1399.9, 'cart_turnovertaxfree' : 1120.9, 'cart_quantity' : 1, 'cart_nbdistinctproduct' : 1, }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("cart.display") .properties( Property(PropertyName("cart_id"), "LAPW221C"), // mandatory Property(PropertyName("cart_currency"), "EUR"), Property(PropertyName("cart_turnovertaxincluded"), 1399.9), Property(PropertyName("cart_turnovertaxfree"), 1120.9), Property(PropertyName("cart_quantity"), 1), Property(PropertyName("cart_nbdistinctproduct"), 1), ) .build() ) ``` ```java pa.sendEvent(new Event("cart.display", new HashMap() {{ put("cart_id", "LAPW221C"); // mandatory put("cart_currency", "EUR"); put("cart_turnovertaxincluded", 1399.9); put("cart_turnovertaxfree", 1120.9); put("cart_quantity", 1); put("cart_nbdistinctproduct", 1); }})); ``` ```swift pa.sendEvent(Event("cart.display", data: [ "cart_id" : "LAPW221C", // mandatory "cart_currency" : "EUR", "cart_turnovertaxincluded" : 1399.9, "cart_turnovertaxfree" : 1120.9, "cart_quantity" : 1, "cart_nbdistinctproduct" : 1 ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "cart.display", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), // mandatory Property.string(name: "cart_currency", value: "EUR"), Property.int(name: "cart_turnovertaxincluded", value: 1399.9), Property.int(name: "cart_turnovertaxfree", value: 1120.9), Property.int(name: "cart_quantity", value: 1), Property.int(name: "cart_nbdistinctproduct", value: 1), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "cart.display", "data": { "cart_id": "LAPW221C", "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1 } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=cart.display&props=[["cart_id","LAPW221C",true],["cart_currency","EUR"],["cart_turnovertaxincluded","1399.9"],["cart_turnovertaxfree","1120.9"],["cart_quantity","1"],["cart_nbdistinctproduct","1"]]) ### `cart.update` Mandatory property: `cart_id` This event can be sent everytime the cart gets updated. It is meant to send the latest known state of the cart's value. ```js pa.sendEvent('cart.update', { 'cart_id' : 'LAPW221C', // mandatory 'cart_currency' : 'EUR', 'cart_turnovertaxincluded' : 1399.9, 'cart_turnovertaxfree' : 1120.9, 'cart_quantity' : 1, 'cart_nbdistinctproduct' : 1, }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("cart.update") .properties( Property(PropertyName("cart_id"), "LAPW221C"), // mandatory Property(PropertyName("cart_currency"), "EUR"), Property(PropertyName("cart_turnovertaxincluded"), 1399.9), Property(PropertyName("cart_turnovertaxfree"), 1120.9), Property(PropertyName("cart_quantity"), 1), Property(PropertyName("cart_nbdistinctproduct"), 1), ) .build() ) ``` ```java pa.sendEvent(new Event("cart.update", new HashMap() {{ put("cart_id", "LAPW221C"); // mandatory put("cart_currency", "EUR"); put("cart_turnovertaxincluded", 1399.9); put("cart_turnovertaxfree", 1120.9); put("cart_quantity", 1); put("cart_nbdistinctproduct", 1); }})); ``` ```swift pa.sendEvent(Event("cart.update", data: [ "cart_id" : "LAPW221C", // mandatory "cart_currency" : "EUR", "cart_turnovertaxincluded" : 1399.9, "cart_turnovertaxfree" : 1120.9, "cart_quantity" : 1, "cart_nbdistinctproduct" : 1 ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "cart.update", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), // mandatory Property.string(name: "cart_currency", value: "EUR"), Property.int(name: "cart_turnovertaxincluded", value: 1399.9), Property.int(name: "cart_turnovertaxfree", value: 1120.9), Property.int(name: "cart_quantity", value: 1), Property.int(name: "cart_nbdistinctproduct", value: 1), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "cart.update", "data": { "cart_id": "LAPW221C", "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1 } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=cart.update&props=[["cart_id","LAPW221C",true],["cart_currency","EUR"],["cart_turnovertaxincluded","1399.9"],["cart_turnovertaxfree","1120.9"],["cart_quantity","1"],["cart_nbdistinctproduct","1"]]) ### `cart.delivery` Mandatory property: `cart_id` This event can be used to measure the delivery method selection step. The shipping properties in the example are not mandatory but can be sent on this step if known at this moment. Otherwise it can be done in the cart.payment step ```js pa.sendEvent('cart.delivery', { 'cart_id' : 'LAPW221C', // mandatory 'cart_currency' : 'EUR', 'cart_turnovertaxincluded' : 1399.9, 'cart_turnovertaxfree' : 1120.9, 'cart_quantity' : 1, 'cart_nbdistinctproduct' : 1, 'shipping_delivery' : 'Express', 'shipping_costtaxincluded' : 11.99, 'shipping_costtaxfree' : 10.99, }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("cart.delivery") .properties( Property(PropertyName("cart_id"), "LAPW221C"), // mandatory Property(PropertyName("cart_currency"), "EUR"), Property(PropertyName("cart_turnovertaxincluded"), 1399.9), Property(PropertyName("cart_turnovertaxfree"), 1120.9), Property(PropertyName("cart_quantity"), 1), Property(PropertyName("cart_nbdistinctproduct"), 1), Property(PropertyName("shipping_delivery"), "Express"), Property(PropertyName("shipping_costtaxincluded"), 11.99), Property(PropertyName("shipping_costtaxfree"), 10.99), ) .build() ) ``` ```java pa.sendEvent(new Event("cart.delivery", new HashMap() {{ put("cart_id", "LAPW221C"); // mandatory put("cart_currency", "EUR"); put("cart_turnovertaxincluded", 1399.9); put("cart_turnovertaxfree", 1120.9); put("cart_quantity", 1); put("cart_nbdistinctproduct", 1); put("shipping_delivery", "Express"); put("shipping_costtaxincluded", 11.99); put("shipping_costtaxfree", 10.99); }})); ``` ```swift pa.sendEvent(Event("cart.delivery", data: [ "cart_id" : "LAPW221C", // mandatory "cart_currency" : "EUR", "cart_turnovertaxincluded" : 1399.9, "cart_turnovertaxfree" : 1120.9, "cart_quantity" : 1, "cart_nbdistinctproduct" : 1, "shipping_delivery" : "Express", "shipping_costtaxincluded" : 11.99, "shipping_costtaxfree" : 10.99 ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "cart.delivery", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), // mandatory Property.string(name: "cart_currency", value: "EUR"), Property.int(name: "cart_turnovertaxincluded", value: 1399.9), Property.int(name: "cart_turnovertaxfree", value: 1120.9), Property.int(name: "cart_quantity", value: 1), Property.int(name: "cart_nbdistinctproduct", value: 1), Property.string(name: "shipping_delivery", value: "Express"), Property.int(name: "shipping_costtaxincluded", value: 11.99), Property.int(name: "shipping_costtaxfree", value: 10.99), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "cart.delivery", "data": { "cart_id": "LAPW221C", "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1, "shipping_delivery": "Express", "shipping_costtaxincluded": 11.99, "shipping_costtaxfree": 10.99 } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=cart.delivery&props=[["cart_id","LAPW221C",true],["cart_currency","EUR"],["cart_turnovertaxincluded","1399.9"],["cart_turnovertaxfree","1120.9"],["cart_quantity","1"],["cart_nbdistinctproduct","1"],["shipping_delivery","Express"],["shipping_costtaxincluded","11.99"],["shipping_costtaxfree","10.99"]]) ### `cart.payment` Mandatory property: `cart_id` This event can be used to measure the payment step. The payment method can be sent at this moment if known. ```js pa.sendEvent('cart.payment', { 'cart_id' : 'LAPW221C', // mandatory 'cart_currency' : 'EUR', 'cart_turnovertaxincluded' : 1399.9, 'cart_turnovertaxfree' : 1120.9, 'cart_quantity' : 1, 'cart_nbdistinctproduct' : 1, 'shipping_delivery' : 'Express', 'shipping_costtaxincluded' : 11.99, 'shipping_costtaxfree' : 10.99, 'payment_mode' : 'Credit card', }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("cart.payment") .properties( Property(PropertyName("cart_id"), "LAPW221C"), // mandatory Property(PropertyName("cart_currency"), "EUR"), Property(PropertyName("cart_turnovertaxincluded"), 1399.9), Property(PropertyName("cart_turnovertaxfree"), 1120.9), Property(PropertyName("cart_quantity"), 1), Property(PropertyName("cart_nbdistinctproduct"), 1), Property(PropertyName("shipping_delivery"), "Express"), Property(PropertyName("shipping_costtaxincluded"), 11.99), Property(PropertyName("shipping_costtaxfree"), 10.99), Property(PropertyName("payment_mode"), "Credit card"), ) .build() ) ``` ```java pa.sendEvent(new Event("cart.payment", new HashMap() {{ put("cart_id", "LAPW221C"); // mandatory put("cart_currency", "EUR"); put("cart_turnovertaxincluded", 1399.9); put("cart_turnovertaxfree", 1120.9); put("cart_quantity", 1); put("cart_nbdistinctproduct", 1); put("shipping_delivery", "Express"); put("shipping_costtaxincluded", 11.99); put("shipping_costtaxfree", 10.99); put("payment_mode", "Credit card"); }})); ``` ```swift pa.sendEvent(Event("cart.payment", data: [ "cart_id" : "LAPW221C", // mandatory "cart_currency" : "EUR", "cart_turnovertaxincluded" : 1399.9, "cart_turnovertaxfree" : 1120.9, "cart_quantity" : 1, "cart_nbdistinctproduct" : 1, "shipping_delivery" : "Express", "shipping_costtaxincluded" : 11.99, "shipping_costtaxfree" : 10.99, "payment_mode" : "Credit card" ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "cart.payment", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), // mandatory Property.string(name: "cart_currency", value: "EUR"), Property.int(name: "cart_turnovertaxincluded", value: 1399.9), Property.int(name: "cart_turnovertaxfree", value: 1120.9), Property.int(name: "cart_quantity", value: 1), Property.int(name: "cart_nbdistinctproduct", value: 1), Property.string(name: "shipping_delivery", value: "Express"), Property.int(name: "shipping_costtaxincluded", value: 11.99), Property.int(name: "shipping_costtaxfree", value: 10.99), Property.string(name: "payment_mode", value: "Credit card"), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "cart.payment", "data": { "cart_id": "LAPW221C", "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1, "shipping_delivery": "Express", "shipping_costtaxincluded": 11.99, "shipping_costtaxfree": 10.99, "payment_mode": "Credit card" } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=cart.payment&props=[["cart_id","LAPW221C",true],["cart_currency","EUR"],["cart_turnovertaxincluded","1399.9"],["cart_turnovertaxfree","1120.9"],["cart_quantity","1"],["cart_nbdistinctproduct","1"],["shipping_delivery","Express"],["shipping_costtaxincluded","11.99"],["shipping_costtaxfree","10.99"],["payment_mode","Credit card"]]) ### `cart.awaiting_payment` and `product.awaiting_payment` Mandatory property: `cart_id` and `product_id` and `cart_version` These events can be used whenever the transaction needs to be validated by a third party (3D Secure for example). The products are not mandatory but will allow you to see the different articles in the cart. You will then be able to validate the cart, once you get the response, through a transaction event (can also be done server-side). ```js pa.sendEvents([ { 'name': 'cart.awaiting_payment', 'data': { 'cart_id': 'LAPW221C' // mandatory, 'cart_version': 'VER211SQ' // mandatory, 'cart_currency': 'EUR', 'cart_creation_utc': 1666196008, 'cart_turnovertaxincluded': 1399.9, 'cart_turnovertaxfree': 1120.9, 'cart_quantity': 1, 'cart_nbdistinctproduct': 1, 'shipping_delivery': 'Express', 'shipping_costtaxincluded': 11.99, 'shipping_costtaxfree': 10.99 } }, { 'name': 'product.awaiting_payment', 'data': { 'cart_id': 'LAPW221C' // mandatory, 'cart_version': 'VER211SQ' // mandatory, 'product_id': 'LPTAX174' // mandatory, 'product': 'Laptop AX174', 'product_variant': '8Go RAM', 'product_brand': 'Laptop', 'product_discount': false, 'product_placement': 'banner', 'product_pricetaxincluded': 1399.9, 'product_pricetaxfree': 1120.9, 'product_stock': true, 'product_category1': 'Hardware', 'product_category2': 'Computer', 'product_category3': 'Gaming', 'product_category4': 'Laptop', 'product_quantity': 1 } } ]); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("cart.awaiting_payment") .properties( Property(PropertyName("cart_id"), "LAPW221C"), // mandatory Property(PropertyName("cart_version"), "VER211SQ"), // mandatory Property(PropertyName("cart_currency"), "EUR"), Property(PropertyName("cart_creation_utc"), 1666196008), Property(PropertyName("cart_turnovertaxincluded"), 1399.9), Property(PropertyName("cart_turnovertaxfree"), 1120.9), Property(PropertyName("cart_quantity"), 1), Property(PropertyName("cart_nbdistinctproduct"), 1), Property(PropertyName("shipping_delivery"), "Express"), Property(PropertyName("shipping_costtaxincluded"), 11.99), Property(PropertyName("shipping_costtaxfree"), 10.99), ) .build(), Event.Builder("product.awaiting_payment") .properties( Property(PropertyName("cart_id"), "LAPW221C"), // mandatory Property(PropertyName("cart_version"), "VER211SQ"), // mandatory Property(PropertyName("product_id"), "LPTAX174"), // mandatory Property(PropertyName("product"), "Laptop AX174"), Property(PropertyName("product_variant"), "8Go RAM"), Property(PropertyName("product_brand"), "Laptop"), Property(PropertyName("product_discount"), false), Property(PropertyName("product_placement"), "banner"), Property(PropertyName("product_pricetaxincluded"), 1399.9), Property(PropertyName("product_pricetaxfree"), 1120.9), Property(PropertyName("product_stock"), true), Property(PropertyName("product_category1"), "Hardware"), Property(PropertyName("product_category2"), "Computer"), Property(PropertyName("product_category3"), "Gaming"), Property(PropertyName("product_category4"), "Laptop"), Property(PropertyName("product_quantity"), 1), ) .build() ) ``` ```java pa.sendEvents(Arrays.asList( new Event("cart.awaiting_payment", new HashMap() {{ put("cart_id", "LAPW221C"); // mandatory put("cart_version", "VER211SQ"); // mandatory put("cart_currency", "EUR"); put("cart_creation_utc", 1666196008); put("cart_turnovertaxincluded", 1399.9); put("cart_turnovertaxfree", 1120.9); put("cart_quantity", 1); put("cart_nbdistinctproduct", 1); put("shipping_delivery", "Express"); put("shipping_costtaxincluded", 11.99); put("shipping_costtaxfree", 10.99); }}), new Event("product.awaiting_payment", new HashMap() {{ put("cart_id", "LAPW221C"); // mandatory put("cart_version", "VER211SQ"); // mandatory put("product_id", "LPTAX174"); // mandatory put("product", "Laptop AX174"); put("product_variant", "8Go RAM"); put("product_brand", "Laptop"); put("product_discount", false); put("product_placement", "banner"); put("product_pricetaxincluded", 1399.9); put("product_pricetaxfree", 1120.9); put("product_stock", true); put("product_category1", "Hardware"); put("product_category2", "Computer"); put("product_category3", "Gaming"); put("product_category4", "Laptop"); put("product_quantity", 1); }}) )); ``` ```swift pa.sendEvents([ Event("cart.awaiting_payment", data: [ "cart_id": "LAPW221C", // mandatory "cart_version": "VER211SQ", // mandatory "cart_currency": "EUR", "cart_creation_utc": 1666196008, "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1, "shipping_delivery": "Express", "shipping_costtaxincluded": 11.99, "shipping_costtaxfree": 10.99 ]), Event("product.awaiting_payment", data: [ "cart_id": "LAPW221C", // mandatory "cart_version": "VER211SQ", // mandatory "product_id": "LPTAX174", // mandatory "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1 ]) ]) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "cart.awaiting_payment", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), // mandatory Property.string(name: "cart_version", value: "VER211SQ"), // mandatory Property.string(name: "cart_currency", value: "EUR"), Property.int(name: "cart_creation_utc", value: 1666196008), Property.int(name: "cart_turnovertaxincluded", value: 1399.9), Property.int(name: "cart_turnovertaxfree", value: 1120.9), Property.int(name: "cart_quantity", value: 1), Property.int(name: "cart_nbdistinctproduct", value: 1), Property.string(name: "shipping_delivery", value: "Express"), Property.int(name: "shipping_costtaxincluded", value: 11.99), Property.int(name: "shipping_costtaxfree", value: 10.99), ]), Event(name: "product.awaiting_payment", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), // mandatory Property.string(name: "cart_version", value: "VER211SQ"), // mandatory Property.string(name: "product_id", value: "LPTAX174"), // mandatory Property.string(name: "product", value: "Laptop AX174"), Property.string(name: "product_variant", value: "8Go RAM"), Property.string(name: "product_brand", value: "Laptop"), Property.bool(name: "product_discount", value: false), Property.string(name: "product_placement", value: "banner"), Property.int(name: "product_pricetaxincluded", value: 1399.9), Property.int(name: "product_pricetaxfree", value: 1120.9), Property.bool(name: "product_stock", value: true), Property.string(name: "product_category1", value: "Hardware"), Property.string(name: "product_category2", value: "Computer"), Property.string(name: "product_category3", value: "Gaming"), Property.string(name: "product_category4", value: "Laptop"), Property.int(name: "product_quantity", value: 1), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "cart.awaiting_payment", "data": { "cart_id": "LAPW221C", "cart_version": "VER211SQ", "cart_currency": "EUR", "cart_creation_utc": 1666196008, "cart_turnovertaxincluded": 1399.9, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1, "shipping_delivery": "Express", "shipping_costtaxincluded": 11.99, "shipping_costtaxfree": 10.99 } },{ "name": "product.awaiting_payment", "data": { "cart_id": "LAPW221C", "cart_version": "VER211SQ", "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1 } }] }) }) ``` > note: > > Using this method, please note that the server-side confirmation needs to happen under 24h. The confirmation event will be excluded after this time limit. If needed, the `confirmation_delay` property can be added to your `awaiting_payment` events. Should this property be tagged with a relevant value, the limit can be extended from 24h to up to 72h. ## Server-side events ### Server-side transaction confirmation Mandatory property: `cart_id` and `transaction_id` and `offsite_confirmation:true` This server-side request allows you to validate a cart that was previously awaiting payment. ```html https://.pa-cd.com/hit.xiti?s=123456789&events=[{"name":"transaction.confirmation","data":{"cart_id":"XXXXX", "transaction_id":"XXXXX", "offsite_confirmation":true}}]&rdt=off ``` ## Transaction events ### `transaction.confirmation` and `product.purchased` Mandatory property: `product_id` and `transaction_id` These events are sent whenever a transaction is made. On this example, the cart and the products are validated. The `cart_id` is not mandatory for these events. ```js pa.sendEvents([ { 'name': 'transaction.confirmation', 'data': { 'cart_id': 'LAPW221C', 'cart_currency': 'EUR', 'cart_turnovertaxincluded': 1399.9, 'cart_creation_utc': 1666196008, 'cart_turnovertaxfree': 1120.9, 'cart_quantity': 1, 'cart_nbdistinctproduct': 1, 'shipping_delivery': 'Express', 'shipping_costtaxincluded': 11.99, 'shipping_costtaxfree': 10.99, 'transaction_id': 'TR221SI' // mandatory, 'transaction_promocode': ["REDUC10"], 'transaction_status': 'charged', 'transaction_firstpurchase': true, 'payment_mode': 'Credit card' } }, { 'name': 'product.purchased', 'data': { 'cart_id': 'LAPW221C', 'product_id': 'LPTAX174' // mandatory, 'product': 'Laptop AX174', 'product_variant': '8Go RAM', 'product_brand': 'Laptop', 'product_discount': false, 'product_placement': 'banner', 'product_pricetaxincluded': 1399.9, 'product_pricetaxfree': 1120.9, 'product_stock': true, 'product_category1': 'Hardware', 'product_category2': 'Computer', 'product_category3': 'Gaming', 'product_category4': 'Laptop', 'product_quantity': 1, 'payment_mode': 'Credit card', 'transaction_id': 'TR221SI' // mandatory, 'transaction_promocode': ["REDUC10"] } }, { 'name': 'product.purchased', 'data': { 'cart_id': 'LAPW221C', 'product_id': 'LPTAX176' // mandatory, 'product': 'Laptop AX176', 'product_variant': '16Go RAM', 'product_brand': 'Laptop', 'product_discount': false, 'product_placement': 'banner', 'product_pricetaxincluded': 1599.9, 'product_pricetaxfree': 1220.9, 'product_stock': true, 'product_category1': 'Hardware', 'product_category2': 'Computer', 'product_category3': 'Gaming', 'product_category4': 'Laptop', 'product_quantity': 1, 'payment_mode': 'Credit card', 'transaction_id': 'TR221SI' // mandatory, 'transaction_promocode': ["REDUC10"] } } ]); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("transaction.confirmation") .properties( Property(PropertyName("cart_id"), "LAPW221C"), Property(PropertyName("cart_currency"), "EUR"), Property(PropertyName("cart_turnovertaxincluded"), 1399.9), Property(PropertyName("cart_creation_utc"), 1666196008), Property(PropertyName("cart_turnovertaxfree"), 1120.9), Property(PropertyName("cart_quantity"), 1), Property(PropertyName("cart_nbdistinctproduct"), 1), Property(PropertyName("shipping_delivery"), "Express"), Property(PropertyName("shipping_costtaxincluded"), 11.99), Property(PropertyName("shipping_costtaxfree"), 10.99), Property(PropertyName("transaction_id"), "TR221SI"), // mandatory Property(PropertyName("transaction_promocode"), arrayOf("REDUC10")), Property(PropertyName("transaction_status"), "charged"), Property(PropertyName("transaction_firstpurchase"), true), Property(PropertyName("payment_mode"), "Credit card"), ) .build(), Event.Builder("product.purchased") .properties( Property(PropertyName("cart_id"), "LAPW221C"), Property(PropertyName("product_id"), "LPTAX174"), // mandatory Property(PropertyName("product"), "Laptop AX174"), Property(PropertyName("product_variant"), "8Go RAM"), Property(PropertyName("product_brand"), "Laptop"), Property(PropertyName("product_discount"), false), Property(PropertyName("product_placement"), "banner"), Property(PropertyName("product_pricetaxincluded"), 1399.9), Property(PropertyName("product_pricetaxfree"), 1120.9), Property(PropertyName("product_stock"), true), Property(PropertyName("product_category1"), "Hardware"), Property(PropertyName("product_category2"), "Computer"), Property(PropertyName("product_category3"), "Gaming"), Property(PropertyName("product_category4"), "Laptop"), Property(PropertyName("product_quantity"), 1), Property(PropertyName("payment_mode"), "Credit card"), Property(PropertyName("transaction_id"), "TR221SI"), // mandatory Property(PropertyName("transaction_promocode"), arrayOf("REDUC10")), ) .build(), Event.Builder("product.purchased") .properties( Property(PropertyName("cart_id"), "LAPW221C"), Property(PropertyName("product_id"), "LPTAX176"), // mandatory Property(PropertyName("product"), "Laptop AX176"), Property(PropertyName("product_variant"), "16Go RAM"), Property(PropertyName("product_brand"), "Laptop"), Property(PropertyName("product_discount"), false), Property(PropertyName("product_placement"), "banner"), Property(PropertyName("product_pricetaxincluded"), 1599.9), Property(PropertyName("product_pricetaxfree"), 1220.9), Property(PropertyName("product_stock"), true), Property(PropertyName("product_category1"), "Hardware"), Property(PropertyName("product_category2"), "Computer"), Property(PropertyName("product_category3"), "Gaming"), Property(PropertyName("product_category4"), "Laptop"), Property(PropertyName("product_quantity"), 1), Property(PropertyName("payment_mode"), "Credit card"), Property(PropertyName("transaction_id"), "TR221SI"), // mandatory Property(PropertyName("transaction_promocode"), arrayOf("REDUC10")), ) .build() ) ``` ```java pa.sendEvents(Arrays.asList( new Event("transaction.confirmation", new HashMap() {{ put("cart_id", "LAPW221C"); put("cart_currency", "EUR"); put("cart_turnovertaxincluded", 1399.9); put("cart_creation_utc", 1666196008); put("cart_turnovertaxfree", 1120.9); put("cart_quantity", 1); put("cart_nbdistinctproduct", 1); put("shipping_delivery", "Express"); put("shipping_costtaxincluded", 11.99); put("shipping_costtaxfree", 10.99); put("transaction_id", "TR221SI"); // mandatory put("transaction_promocode", ["REDUC10"]); put("transaction_status", "charged"); put("transaction_firstpurchase", true); put("payment_mode", "Credit card"); }}), new Event("product.purchased", new HashMap() {{ put("cart_id", "LAPW221C"); put("product_id", "LPTAX174"); // mandatory put("product", "Laptop AX174"); put("product_variant", "8Go RAM"); put("product_brand", "Laptop"); put("product_discount", false); put("product_placement", "banner"); put("product_pricetaxincluded", 1399.9); put("product_pricetaxfree", 1120.9); put("product_stock", true); put("product_category1", "Hardware"); put("product_category2", "Computer"); put("product_category3", "Gaming"); put("product_category4", "Laptop"); put("product_quantity", 1); put("payment_mode", "Credit card"); put("transaction_id", "TR221SI"); // mandatory put("transaction_promocode", ["REDUC10"]); }}), new Event("product.purchased", new HashMap() {{ put("cart_id", "LAPW221C"); put("product_id", "LPTAX176"); // mandatory put("product", "Laptop AX176"); put("product_variant", "16Go RAM"); put("product_brand", "Laptop"); put("product_discount", false); put("product_placement", "banner"); put("product_pricetaxincluded", 1599.9); put("product_pricetaxfree", 1220.9); put("product_stock", true); put("product_category1", "Hardware"); put("product_category2", "Computer"); put("product_category3", "Gaming"); put("product_category4", "Laptop"); put("product_quantity", 1); put("payment_mode", "Credit card"); put("transaction_id", "TR221SI"); // mandatory put("transaction_promocode", ["REDUC10"]); }}) )); ``` ```swift pa.sendEvents([ Event("transaction.confirmation", data: [ "cart_id": "LAPW221C", "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_creation_utc": 1666196008, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1, "shipping_delivery": "Express", "shipping_costtaxincluded": 11.99, "shipping_costtaxfree": 10.99, "transaction_id": "TR221SI", // mandatory "transaction_promocode": ["REDUC10"], "transaction_status": "charged", "transaction_firstpurchase": true, "payment_mode": "Credit card" ]), Event("product.purchased", data: [ "cart_id": "LAPW221C", "product_id": "LPTAX174", // mandatory "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1, "payment_mode": "Credit card", "transaction_id": "TR221SI", // mandatory "transaction_promocode": ["REDUC10"] ]), Event("product.purchased", data: [ "cart_id": "LAPW221C", "product_id": "LPTAX176", // mandatory "product": "Laptop AX176", "product_variant": "16Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1599.9, "product_pricetaxfree": 1220.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1, "payment_mode": "Credit card", "transaction_id": "TR221SI", // mandatory "transaction_promocode": ["REDUC10"] ]) ]) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "transaction.confirmation", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), Property.string(name: "cart_currency", value: "EUR"), Property.int(name: "cart_turnovertaxincluded", value: 1399.9), Property.int(name: "cart_creation_utc", value: 1666196008), Property.int(name: "cart_turnovertaxfree", value: 1120.9), Property.int(name: "cart_quantity", value: 1), Property.int(name: "cart_nbdistinctproduct", value: 1), Property.string(name: "shipping_delivery", value: "Express"), Property.int(name: "shipping_costtaxincluded", value: 11.99), Property.int(name: "shipping_costtaxfree", value: 10.99), Property.string(name: "transaction_id", value: "TR221SI"), // mandatory Property.stringArray(name: "transaction_promocode", value: ["REDUC10"]), Property.string(name: "transaction_status", value: "charged"), Property.bool(name: "transaction_firstpurchase", value: true), Property.string(name: "payment_mode", value: "Credit card"), ]), Event(name: "product.purchased", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), Property.string(name: "product_id", value: "LPTAX174"), // mandatory Property.string(name: "product", value: "Laptop AX174"), Property.string(name: "product_variant", value: "8Go RAM"), Property.string(name: "product_brand", value: "Laptop"), Property.bool(name: "product_discount", value: false), Property.string(name: "product_placement", value: "banner"), Property.int(name: "product_pricetaxincluded", value: 1399.9), Property.int(name: "product_pricetaxfree", value: 1120.9), Property.bool(name: "product_stock", value: true), Property.string(name: "product_category1", value: "Hardware"), Property.string(name: "product_category2", value: "Computer"), Property.string(name: "product_category3", value: "Gaming"), Property.string(name: "product_category4", value: "Laptop"), Property.int(name: "product_quantity", value: 1), Property.string(name: "payment_mode", value: "Credit card"), Property.string(name: "transaction_id", value: "TR221SI"), // mandatory Property.stringArray(name: "transaction_promocode", value: ["REDUC10"]), ]), Event(name: "product.purchased", properties: [ Property.string(name: "cart_id", value: "LAPW221C"), Property.string(name: "product_id", value: "LPTAX176"), // mandatory Property.string(name: "product", value: "Laptop AX176"), Property.string(name: "product_variant", value: "16Go RAM"), Property.string(name: "product_brand", value: "Laptop"), Property.bool(name: "product_discount", value: false), Property.string(name: "product_placement", value: "banner"), Property.float(name: "product_pricetaxincluded", value: 1599.9), Property.float(name: "product_pricetaxfree", value: 1220.9), Property.bool(name: "product_stock", value: true), Property.string(name: "product_category1", value: "Hardware"), Property.string(name: "product_category2", value: "Computer"), Property.string(name: "product_category3", value: "Gaming"), Property.string(name: "product_category4", value: "Laptop"), Property.int(name: "product_quantity", value: 1), Property.string(name: "payment_mode", value: "Credit card"), Property.string(name: "transaction_id", value: "TR221SI"), // mandatory Property.stringArray(name: "transaction_promocode", value: ["REDUC10"]), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "transaction.confirmation", "data": { "cart_id": "LAPW221C", "cart_currency": "EUR", "cart_turnovertaxincluded": 1399.9, "cart_creation_utc": 1666196008, "cart_turnovertaxfree": 1120.9, "cart_quantity": 1, "cart_nbdistinctproduct": 1, "shipping_delivery": "Express", "shipping_costtaxincluded": 11.99, "shipping_costtaxfree": 10.99, "transaction_id": "TR221SI", "transaction_promocode": ["REDUC10"], "transaction_status": "charged", "transaction_firstpurchase": true, "payment_mode": "Credit card" } },{ "name": "product.purchased", "data": { "cart_id": "LAPW221C", "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1, "payment_mode": "Credit card", "transaction_id": "TR221SI", "transaction_promocode": ["REDUC10"] } },{ "name": "product.purchased", "data": { "cart_id": "LAPW221C", "product_id": "LPTAX176", "product": "Laptop AX176", "product_variant": "16Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1599.9, "product_pricetaxfree": 1220.9, "product_stock": true, "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_quantity": 1, "payment_mode": "Credit card", "transaction_id": "TR221SI", "transaction_promocode": ["REDUC10"] } }] }) }) ``` ## Annexes ### Product properties | Property | Description | Type | Mandatory | Example | | ------------------------- | -------------------------------------- | ------- | --------- | -------------- | | product_id | ID | string | Yes | 'LPTAX174' | | product | Label | string | | 'Laptop AX174' | | product_variant | Variant | string | | '8Go RAM' | | product_brand | Brand | string | | 'Loptap' | | product_discount | Discounted product? | boolean | | false | | product_placement | Where is the product visible from? | string | | 'banner' | | product_pricetaxincluded | Price tax included | float | | 1399.90 | | product_pricetaxfree | Price tax free | float | | 1120.90 | | product_stock | Product in stock? | boolean | | true | | product_quantity | Quantity | int | | 1 | | product_category1 | Level 1 category | string | | 'Hardware' | | product_category2 | Level 2 category | string | | 'Computer' | | product_category3 | Level 3 category | string | | 'Gaming' | | product_category4 | Level 4 category | string | | 'Laptop' | | product_cartcreation | Cart created by this product addition? | boolean | | false | ### Cart properties | Property | Description | Type | Mandatory | Example | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | --------- | ---------- | | cart_id | ID | string | Yes | 'HW-8892' | | cart_currency | Currency (ISO 4217) | string | | 'EUR' | | cart_turnovertaxincluded | Turnover tax included | float | | 2900.00 | | cart_turnovertaxfree | Turnover tax free | float | | 2340.50 | | cart_creation_utc | Cart creation date (timestamp UTC in seconds) | int | | 1501065673 | | cart_quantity | Number of products | int | | 3 | | cart_nbdistinctproduct | Number of distinct products | int | | 2 | | cart_version | When updating the cart awaiting payment (adding/removing a product), it will be necessary to generate a new unique version identifier (cart_version) associated with the cart (cart_id). This is necessary when using pending carts/products (cart.awaiting_payment / product.awaiting_payment) | string | | 'v1' | | confirmation_delay | This property should be used if the default confirmation window needs to be extended, up to 72h. This is necessary when using pending carts/products (cart.awaiting_payment / product.awaiting_payment) | int | | 72 | ### Transaction properties | Property | Description | Type | Mandatory | Example | | -------------------------- | ------------------------------- | --------------- | --------- | ------------------------ | | transaction_id | ID | string | Yes | '29984' | | transaction_promocode | Promo code list | array of string | | \['BLACKFRIDAY', 'VIP'\] | | transaction_firstpurchase | First purchase of the customer? | boolean | | true | | transaction_status | Transaction status | string | | 'charged' | ### Shipping properties | Property | Description | Type | Mandatory | Example | | ------------------------- | -------------------------- | ------ | --------- | --------- | | shipping_delivery | Shipping type | string | | 'Express' | | shipping_costtaxincluded | Shipping cost tax included | float | | 10.50 | | shipping_costtaxfree | Shipping cost tax free | float | | 8.00 | ### Payment properties | Property | Description | Type | Mandatory | Example | | ------------- | ------------ | ------ | --------- | ------------- | | payment_mode | Payment mode | string | | 'Credit card' | ### Available currencies Available currencies | Code | Name | | ---- | --------------------------------------- | | AFN | Afghan Afghani | | ALL | Albanian Lek | | DZD | Algerian Dinar | | AOA | Angolan Kwanza | | ARS | Argentine Peso | | AMD | Armenian Dram | | AWG | Aruban Florin | | AUD | Australian Dollar | | AZN | Azerbaijani Manat | | BSD | Bahamian Dollar | | BHD | Bahraini Dinar | | BDT | Bangladeshi Taka | | BBD | Barbadian Dollar | | BYN | Belarusian Ruble | | BYR | Belarusian Ruble | | BZD | Belize Dollar | | BMD | Bermudian Dollar | | BTN | Bhutanese Ngultrum | | BOB | Bolivian Boliviano | | BAM | Bosnia and Herzegovina Convertible Mark | | BWP | Botswana Pula | | BRL | Brazilian Real | | GBP | British Pound | | BND | Brunei Dollar | | BGN | Bulgarian Lev | | BIF | Burundian Franc | | KHR | Cambodian Riel | | CAD | Canadian Dollar | | CVE | Cape Verdean Escudo | | KYD | Cayman Islands Dollar | | XAF | Central African Cfa Franc | | XPF | Cfp Franc | | CLP | Chilean Peso | | CNY | Chinese Renminbi Yuan | | CNH | Chinese Renminbi Yuan Offshore | | COP | Colombian Peso | | KMF | Comorian Franc | | CDF | Congolese Franc | | CRC | Costa Rican Colón | | HRK | Croatian Kuna | | CUC | Cuban Convertible Peso | | CZK | Czech Koruna | | DKK | Danish Krone | | DJF | Djiboutian Franc | | DOP | Dominican Peso | | XCD | East Caribbean Dollar | | EGP | Egyptian Pound | | EEK | Estonian Kroon | | ETB | Ethiopian Birr | | EUR | Euro | | FKP | Falkland Pound | | FJD | Fijian Dollar | | GMD | Gambian Dalasi | | GEL | Georgian Lari | | GHS | Ghanaian Cedi | | GIP | Gibraltar Pound | | XAU | Gold (Troy Ounce) | | GTQ | Guatemalan Quetzal | | GGP | Guernsey Pound | | GNF | Guinean Franc | | GYD | Guyanese Dollar | | HTG | Haitian Gourde | | HNL | Honduran Lempira | | HKD | Hong Kong Dollar | | HUF | Hungarian Forint | | ISK | Icelandic Króna | | INR | Indian Rupee | | IDR | Indonesian Rupiah | | IQD | Iraqi Dinar | | IMP | Isle of Man Pound | | ILS | Israeli New Sheqel | | JMD | Jamaican Dollar | | JPY | Japanese Yen | | JEP | Jersey Pound | | JOD | Jordanian Dinar | | KZT | Kazakhstani Tenge | | KES | Kenyan Shilling | | KWD | Kuwaiti Dinar | | KGS | Kyrgyzstani Som | | LAK | Lao Kip | | LVL | Latvian Lats | | LBP | Lebanese Pound | | LSL | Lesotho Loti | | LRD | Liberian Dollar | | LYD | Libyan Dinar | | LTL | Lithuanian Litas | | MOP | Macanese Pataca | | MKD | Macedonian Denar | | MGA | Malagasy Ariary | | MWK | Malawian Kwacha | | MYR | Malaysian Ringgit | | MVR | Maldivian Rufiyaa | | MRO | Mauritanian Ouguiya | | MUR | Mauritian Rupee | | MXN | Mexican Peso | | MDL | Moldovan Leu | | MNT | Mongolian Tögrög | | MAD | Moroccan Dirham | | MZN | Mozambican Metical | | MMK | Myanmar Kyat | | NAD | Namibian Dollar | | NPR | Nepalese Rupee | | ANG | Netherlands Antillean Gulden | | TWD | New Taiwan Dollar | | NZD | New Zealand Dollar | | NIO | Nicaraguan Córdoba | | NGN | Nigerian Naira | | NOK | Norwegian Krone | | OMR | Omani Rial | | PKR | Pakistani Rupee | | XPD | Palladium | | PAB | Panamanian Balboa | | PGK | Papua New Guinean Kina | | PYG | Paraguayan Guaraní | | PEN | Peruvian Sol | | PHP | Philippine Peso | | XPT | Platinum | | PLN | Polish Złoty | | QAR | Qatari Riyal | | RON | Romanian Leu | | RUB | Russian Ruble | | RWF | Rwandan Franc | | SHP | Saint Helenian Pound | | SVC | Salvadoran Colón | | WST | Samoan Tala | | STD | São Tomé and Príncipe Dobra | | SAR | Saudi Riyal | | RSD | Serbian Dinar | | SCR | Seychellois Rupee | | SLL | Sierra Leonean Leone | | XAG | Silver (Troy Ounce) | | SGD | Singapore Dollar | | SKK | Slovak Koruna | | SBD | Solomon Islands Dollar | | SOS | Somali Shilling | | ZAR | South African Rand | | KRW | South Korean Won | | LKR | Sri Lankan Rupee | | SDG | Sudanese Pound | | SRD | Surinamese Dollar | | SZL | Swazi Lilangeni | | SEK | Swedish Krona | | CHF | Swiss Franc | | TJS | Tajikistani Somoni | | TZS | Tanzanian Shilling | | THB | Thai Baht | | TOP | Tongan Paʻanga | | TTD | Trinidad and Tobago Dollar | | TND | Tunisian Dinar | | TRY | Turkish Lira | | TMT | Turkmenistani Manat | | TMM | Turkmenistani Manat | | UGX | Ugandan Shilling | | UAH | Ukrainian Hryvnia | | CLF | Unidad de Fomento | | AED | United Arab Emirates Dirham | | UYU | Uruguayan Peso | | USD | US Dollar | | UZS | Uzbekistan Som | | VUV | Vanuatu Vatu | | VEF | Venezuelan Bolívar | | VES | Venezuelan Bolívar Soberano | | VND | Vietnamese Đồng | | XOF | West African Cfa Franc | | YER | Yemeni Rial | | ZMK | Zambian Kwacha | | ZMW | Zambian Kwacha | | ZWD | Zimbabwean Dollar | --- ## Send events via SDKs If you're not yet confortable with the "SDK" notion, don't hesitate to consult the [Implementation methods](/analytics/data-collection/general/implementation-methods/) article. Our SDKs offer methods to manage properties and send events. ## Tagging methods The main method you will use is to send an event with properties. ### JavaScript Method: `pa.sendEvent(eventName[, eventData, options])` | Parameters | Type | Description | | -------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | eventName | string | Name of the event | | eventData (optional) | object | Object of properties | | options (optional) | object | Object of options | | options.onBeforeBuild(PianoAnalytics, model, next) | function | Callback plugged before the event is built. PianoAnalytics is the tracker reference, model is the model of the event, next calls the next step | | options.onBeforeSend(PianoAnalytics, model, next) | function | Callback plugged before the event is sent. PianoAnalytics is the tracker reference, model is the model of the event, next calls the next step | ```js pa.sendEvent("page.display", { page: "Page name", page_premium: false, page_authors: ["Clark Kent", "John Cena"], }); ``` In the following example, we are updating the site ID for the current event: ```js pa.sendEvent( "page.display", { page: "Page name", page_premium: false, page_authors: ["Clark Kent", "John Cena"], }, { onBeforeBuild: function (PianoAnalytics, model, next) { model.setConfiguration("site", "123456789"); next(); }, } ); ``` You can also send several events using one method: Method: `pa.sendEvents(eventsArray[, options])` | Parameters | Type | Description | | -------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | eventsArray | array | Array of event objects | | options (optional) | object | Object of options | | options.onBeforeBuild(PianoAnalytics, model, next) | function | Callback plugged before the event is built. PianoAnalytics is the tracker reference, model is the model of the event, next calls the next step | | options.onBeforeSend(PianoAnalytics, model, next) | function | Callback plugged before the event is sent. PianoAnalytics is the tracker reference, model is the model of the event, next calls the next step | ```js pa.sendEvents([ { 'name': 'page.display', 'data': { ... } },{ 'name': 'page.scroll', 'data': { ... } } ]); ``` ### Android (3.3.0+) Methods: `func PianoAnalytics.sendEvent(event) -> void` `func PianoAnalytics.sendEvent(event,config) -> void` `func PianoAnalytics.sendEvent(event,config,l) -> void` | Parameters | Type | Description | | ---------- | -------------- | ----------------------- | | event | Event | Event to send | | Event.name | String | Event name | | Event.data | Map | Event properties | | config | Configuration | Configuration object | | l | OnWorkListener | Hooks on specific steps | ```java pa.sendEvent(new Event("page.display", new HashMap() {{ put("page", "Page name"); put("page_premium", false); put("page_authors", new String[]{"Clark Kent", "John Cena"}); }})); ``` A more advanced example: ```java pa.sendEvent( new Event("page.display", new HashMap() {{ put("page", "Page name"); put("page_premium", false); put("page_authors", new String[]{"Clark Kent", "John Cena"}); }}), new Configuration.Builder().withSite(123456789).build(), new PianoAnalytics.OnWorkListener() { @Override public boolean onBeforeBuild(Model model) { // add custom actions here return true; } @Override public boolean onBeforeSend(BuiltModel built, Map stored) { // add custom actions here return true; } } ); ``` You can also send several events using one method: Method: `func PianoAnalytics.sendEvents(events) -> void` `func PianoAnalytics.sendEvents(events,config) -> void` `func PianoAnalytics.sendEvents(events,config,l) -> void` | Parameters | Type | Description | | ---------- | -------------- | ----------------------- | | events | Event\[\] | Event to send | | Event.name | String | Event name | | Event.data | Map | Event properties | | config | Configuration | Configuration object | | l | OnWorkListener | Hooks on specific steps | ```java pa.sendEvents(Arrays.asList( new Event("page.display", new HashMap<>(...)), new Event("page.scroll", new HashMap<>(...)) )); ``` ### Android Method: `fun PianoAnalytics.sendEvents(events) -> void` | Parameters | Type | Description | | ---------- | ---------------- | ---------------- | | events | EventBuilder\[\] | Events to send | | Event.name | String | Event name | | Event.data | Map | Event properties | ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("page.display") .properties( Property(PropertyName("page"), "Page name"), Property(PropertyName("page_premium"), false), Property(PropertyName("page_authors"), arrayOf("Clark Kent","John Cena")), Property(PropertyName("last_update"), 1698225000, Property.Type.DATE), // you can add properties here ) .build() // you can add other events here ) ``` ### Apple Method: `pa.sendEvent(_ event: Event, config: Configuration? = nil, p: PianoAnalyticsWorkProtocol? = nil)` | Parameters | Type | Description | | ---------- | --------------------------- | ----------------------- | | event | Event | Event to send | | Event.name | String | Event name | | Event.data | \[String: Any\]? | Event properties | | config | Configuration? | Configuration object | | p | PianoAnalyticsWorkProtocol? | Hooks on specific steps | ```swift pa.sendEvent(Event("page.display", data: [ "page": "Page name", "page_premium": false, "page_authors": ["Clark Kent", "John Cena"] ])) ``` A more advanced example: ```swift class PianoAnalyticsCustomProtocol: PianoAnalyticsWorkProtocol { func onBeforeBuild(model: inout Model) -> Bool { // add custom actions here return true } func onBeforeSend(built: BuiltModel?, stored: [String: BuiltModel]?) -> Bool { // add custom actions here return true } } pa.sendEvent( Event("page.display", data: [ "page": "Page name", "page_premium": false, "page_authors": ["Clark Kent", "John Cena"] ]), config: ConfigurationBuilder().withSite(123456789).build(), p: PianoAnalyticsCustomProtocol() ) ``` You can also send several events using one method: Method: `pa.sendEvents(_ events: [Event], config: Configuration? = nil, p: PianoAnalyticsWorkProtocol? = nil)` | Parameters | Type | Description | | ---------- | --------------------------- | ----------------------- | | events | \[Event\] | Event to send | | Event.name | String | Event name | | Event.data | \[String: Any\]? | Event properties | | config | Configuration? | Configuration object | | p | PianoAnalyticsWorkProtocol? | Hooks on specific steps | ```swift pa.sendEvents([ Event("page.display", data: [...]), Event("page.scroll", data: [...]) ]) ``` ### Flutter Method: `PianoAnalytics.sendEvents(events)` | Parameters | Type | Description | | ---------------- | ------------ | ---------------- | | events | Event\[\] | Events to send | | Event.name | String | Event name | | Event.properties | Property\[\] | Event properties | ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "page.display", properties: [ Property.string(name: "page", value: "Page name"), Property.bool(name: "page_premium", value: false), Property.stringArray(name: "page_authors", value: ["Clark Kent", "John Cena"]) ]) ]); ``` > tip: > > In your Data Model, a property is tied to a specific type. When you tag your properties, this type must be the same. > > The JSON type is automatically assigned to the property. If you want to assign a specific type to a property, please consult the dedicated ressource in our [Collection API](/analytics/data-collection/how-to-send-events/collection-api/#property-type) article. ## Add properties to subsequent events You can add properties to subsequent events, by using specific methods. > warning: > > We highly recommend pushing properties directly from `sendEvent` / `sendEvents`. Use only when required. 👍 Good practice ```js // ❌ Don't do setProperty('page', 'Contact us'); setProperty('customer_type', 'Individual'); sendEvent('page.display'); // ✅ Do sendEvent('page.display', { 'page': 'Contact us', 'customer_type': 'Individual' }); ``` Method: `pa.setProperty(propertyName, propertyValue[, options])` | Parameters | Type | Description | | ------------------ | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | propertyName | string | Name of the property | | propertyValue | string, number, boolean, array (string, boolean, number) | Value of the property | | options (optional) | object | Options | | options.persistent | boolean | Indicates whether the property should be sent on all subsequent events (true) or just the next event sent (false \- default) | | options.events | string, array | Event names the property will be sent on (all events by default) | ```js pa.setProperty("page_premium", false, { persistent: true, events: ["page.*", "click.navigation"], }); ``` This example sends `page_premium` property with the value `false` on all subsequent `page.*` and `click.navigation` events. You can also add multiple properties at once. Method: `pa.setProperties(propertiesObject[, options])` | Parameters | Type | Description | | ------------------ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | propertiesObject | object | Key value pairs of event name and event value | | options (optional) | object | Options | | options.persistent | boolean | Indicates whether the property should be sent on all subsequent events (true) or just the next event sent (false) (default: false) | | options.events | string, array | Event names the property will be sent on (all events by default) | ```js pa.setProperties( { page_premium: false, page_authors: ["Clark Kent", "John Cena"], }, { persistent: true, events: ["page.*", "click.navigation"], } ); ``` This example sends `page_premium` and `page_authors` properties on all subsequent `page.*` and `click.navigation` events. You can also delete properties previously set. Method: `pa.deleteProperty(propertyName)` | Parameters | Type | Description | | ------------ | ------ | ------------------------------ | | propertyName | string | Name of the property to delete | ```js pa.deleteProperty("page_premium"); ``` In order to manage properties with the Kotlin SDK, you must work with the `contextPropertiesStorage`. | Parameters | Type | Description | | --------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | properties | Set of Property | Set of properties to add | | persistent (optional) | boolean | Indicates whether the property should be sent on all subsequent events (true) or just the next event sent (false) (default: false) | | eventNames (optional) | List of string | Event names the properties will be sent on (all events by default) | ```kotlin val contextPropertiesStorage = PianoAnalytics.getInstance().contextPropertiesStorage // add new context property contextPropertiesStorage.add( ContextProperty( properties = setOf( Property(...), Property(...) ), persistent = false, eventNames = listOf("click.navigation", "click.action") ) ) // remove some property added before contextPropertiesStorage.deleteByKey(PropertyName("click.navigation")) ``` Method: `func PianoAnalytics.setProperty(key, value) -> void` `func PianoAnalytics.setProperty(key, value, persistent) -> void` `func PianoAnalytics.setProperty(key, value, persistent, events) -> void` | Parameters | Type | Description | | ---------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------- | | key | String | Name of the property | | value | Object | Value of the property | | persistent | Boolean | Indicates whether the property should be sent on all subsequent events (true) or just the next event sent (false \- default) | | events | String\[\] | Event names the property will be sent on (all events by default) | ```java pa.setProperty("page_premium", false, true, new String[]{"page.*", "click.navigation"}); ``` This example sends `page_premium` property with the value `false` on all subsequent `page.*` and `click.navigation` events. You can also add multiple properties at once. Method: `func PianoAnalytics.setProperties(data) -> void` `func PianoAnalytics.setProperties(data, persistent) -> void` `func PianoAnalytics.setProperties(data, persistent, events) -> void` | Parameters | Type | Description | | ---------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------- | | data | Map | Properties to set | | persistent | Boolean | Indicates whether the property should be sent on all subsequent events (true) or just the next event sent (false \- default) | | events | String\[\] | Event names the property will be sent on (all events by default) | ```java pa.setProperties(new HashMap() {{ put("page_premium", false); put("page_authors", new String[]{"Clark Kent", "John Cena"}); }}, true, new String[]{"page.*", "click.navigation"}); ``` This example sends `page_premium` property on all subsequent `page.*` and `click.navigation` events. Method: `pa.setProperty(key: String, value: Any, persistent: Bool = false, events: [String]? = nil)` | Parameters | Type | Description | | ---------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------- | | key | String | Name of the property | | value | Any | Value of the property | | persistent | Bool | Indicates whether the property should be sent on all subsequent events (true) or just the next event sent (false \- default) | | events | \[String\]? | Event names the property will be sent on (all events by default) | ```swift pa.setProperty(key: "page_premium", value: false, persistent: true, events: ["page.*", "click.navigation"]) ``` This example sends `page_premium` property with the value `false` on all subsequent `page.*` and `click.navigation` events. You can also add multiple properties at once. Method: `pa.setProperties(_ data: [String: Any], persistent: Bool = false, events: [String]? = nil)` | Parameters | Type | Description | | ---------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------- | | data | \[String: Any\] | Properties to set | | persistent | Bool | Indicates whether the property should be sent on all subsequent events (true) or just the next event sent (false \- default) | | events | \[String\]? | Event names the property will be sent on (all events by default) | ```swift pa.setProperties([ "page_premium": false, "page_authors": ["Clark Kent", "John Cena"] ], persistent: true, events: ["page.*", "click.navigation"]) ``` This example sends `page_premium` property on all subsequent `page.*` and `click.navigation` events. *Not available* --- ## Standard events ## Page display #### Event name `page.display` #### Standard properties | Property | Type | | -------------- | ------ | | page | string | | page_chapter1 | string | | page_chapter2 | string | | page_chapter3 | string | ### Javascript ```js pa.sendEvent('page.display', { 'page' : 'page name', 'page_chapter1' : 'level 1', 'page_chapter2' : 'level 2', 'page_chapter3' : 'level 3', }); ``` ### Android (3.3.0+) ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("page.display") .properties( Property(PropertyName("page"), "page name"), Property(PropertyName("page_chapter1"), "level 1"), Property(PropertyName("page_chapter2"), "level 2"), Property(PropertyName("page_chapter3"), "level 3"), ) .build() ) ``` ### Android ```java pa.sendEvent(new Event("page.display", new HashMap() {{ put("page", "page name"); put("page_chapter1", "level 1"); put("page_chapter2", "level 2"); put("page_chapter3", "level 3"); }})); ``` ### Apple ```swift pa.sendEvent(Event("page.display", data: [ "page" : "page name", "page_chapter1" : "level 1", "page_chapter2" : "level 2", "page_chapter3" : "level 3" ])) ``` ### Flutter ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "page.display", properties: [ Property.string(name: "page", value: "page name"), Property.string(name: "page_chapter1", value: "level 1"), Property.string(name: "page_chapter2", value: "level 2"), Property.string(name: "page_chapter3", value: "level 3"), ]) ]); ``` ### HTTP ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "page.display", "data": { "page": "page name", "page_chapter1": "level 1", "page_chapter2": "level 2", "page_chapter3": "level 3" } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=page.display&props=[["page","page name"],["page_chapter1","level 1"],["page_chapter2","level 2"],["page_chapter3","level 3"]]) ## Clicks #### Event name `click.action` / `click.navigation` / `click.download` / `click.exit` #### Standard properties | Property | Type | | --------------- | ------ | | click | string | | click_chapter1 | string | | click_chapter2 | string | | click_chapter3 | string | ```js pa.sendEvent('click.action', { 'click' : 'click name', 'click_chapter1' : 'level 1', 'click_chapter2' : 'level 2', 'click_chapter3' : 'level 3', }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("click.action") .properties( Property(PropertyName("click"), "click name"), Property(PropertyName("click_chapter1"), "level 1"), Property(PropertyName("click_chapter2"), "level 2"), Property(PropertyName("click_chapter3"), "level 3"), ) .build() ) ``` ```java pa.sendEvent(new Event("click.action", new HashMap() {{ put("click", "click name"); put("click_chapter1", "level 1"); put("click_chapter2", "level 2"); put("click_chapter3", "level 3"); }})); ``` ```swift pa.sendEvent(Event("click.action", data: [ "click" : "click name", "click_chapter1" : "level 1", "click_chapter2" : "level 2", "click_chapter3" : "level 3" ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "click.action", properties: [ Property.string(name: "click", value: "click name"), Property.string(name: "click_chapter1", value: "level 1"), Property.string(name: "click_chapter2", value: "level 2"), Property.string(name: "click_chapter3", value: "level 3"), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "click.action", "data": { "click": "click name", "click_chapter1": "level 1", "click_chapter2": "level 2", "click_chapter3": "level 3" } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=click.action&props=[["click","click name"],["click_chapter1","level 1"],["click_chapter2","level 2"],["click_chapter3","level 3"]]) ## Onsite Ads #### Event name `publisher.impression` / `publisher.click` / `self_promotion.impression` / `self_promotion.click` #### Standard properties | Property | Type | Possible value | | ----------------------------- | ------ | -------------------------- | | onsitead_type (mandatory) | string | Publisher / Self promotion | | onsitead_advertiser | string | | | onsitead_campaign | string | | | onsitead_category | string | | | onsitead_creation | string | | | onsitead_detailed_placement | string | | | onsitead_format | string | | | onsitead_general_placement | string | | | onsitead_url | string | | | onsitead_variant | string | | ```js pa.sendEvent('publisher.impression', { 'onsitead_type' : 'Publisher', 'onsitead_advertiser' : 'Pitchfork', 'onsitead_campaign' : '2', 'onsitead_category' : 'HotDeals', 'onsitead_creation' : 'brand', 'onsitead_detailed_placement' : 'right', 'onsitead_format' : '336x280', 'onsitead_general_placement' : 'side', 'onsitead_url' : 'https://www.piano.io', 'onsitead_variant' : 'newbies', }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("publisher.impression") .properties( Property(PropertyName("onsitead_type"), "Publisher"), Property(PropertyName("onsitead_advertiser"), "Pitchfork"), Property(PropertyName("onsitead_campaign"), "2"), Property(PropertyName("onsitead_category"), "HotDeals"), Property(PropertyName("onsitead_creation"), "brand"), Property(PropertyName("onsitead_detailed_placement"), "right"), Property(PropertyName("onsitead_format"), "336x280"), Property(PropertyName("onsitead_general_placement"), "side"), Property(PropertyName("onsitead_url"), "https://www.piano.io"), Property(PropertyName("onsitead_variant"), "newbies"), ) .build() ) ``` ```java pa.sendEvent(new Event("publisher.impression", new HashMap() {{ put("onsitead_type", "Publisher"); put("onsitead_advertiser", "Pitchfork"); put("onsitead_campaign", "2"); put("onsitead_category", "HotDeals"); put("onsitead_creation", "brand"); put("onsitead_detailed_placement", "right"); put("onsitead_format", "336x280"); put("onsitead_general_placement", "side"); put("onsitead_url", "https://www.piano.io"); put("onsitead_variant", "newbies"); }})); ``` ```swift pa.sendEvent(Event("publisher.impression", data: [ "onsitead_type" : "Publisher", "onsitead_advertiser" : "Pitchfork", "onsitead_campaign" : "2", "onsitead_category" : "HotDeals", "onsitead_creation" : "brand", "onsitead_detailed_placement" : "right", "onsitead_format" : "336x280", "onsitead_general_placement" : "side", "onsitead_url" : "https://www.piano.io", "onsitead_variant" : "newbies" ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "publisher.impression", properties: [ Property.string(name: "onsitead_type", value: "Publisher"), Property.string(name: "onsitead_advertiser", value: "Pitchfork"), Property.string(name: "onsitead_campaign", value: "2"), Property.string(name: "onsitead_category", value: "HotDeals"), Property.string(name: "onsitead_creation", value: "brand"), Property.string(name: "onsitead_detailed_placement", value: "right"), Property.string(name: "onsitead_format", value: "336x280"), Property.string(name: "onsitead_general_placement", value: "side"), Property.string(name: "onsitead_url", value: "https://www.piano.io"), Property.string(name: "onsitead_variant", value: "newbies"), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "publisher.impression", "data": { "onsitead_type": "Publisher", "onsitead_advertiser": "Pitchfork", "onsitead_campaign": "2", "onsitead_category": "HotDeals", "onsitead_creation": "brand", "onsitead_detailed_placement": "right", "onsitead_format": "336x280", "onsitead_general_placement": "side", "onsitead_url": "https://www.piano.io", "onsitead_variant": "newbies" } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=publisher.impression&props=[["onsitead_type","Publisher"],["onsitead_advertiser","Pitchfork"],["onsitead_campaign","2"],["onsitead_category","HotDeals"],["onsitead_creation","brand"],["onsitead_detailed_placement","right"],["onsitead_format","336x280"],["onsitead_general_placement","side"],["onsitead_url","https://www.piano.io"],["onsitead_variant","newbies"]]) ## Internal search engine ### Result display #### Event name `internal_search_result.display` #### Standard properties | Property | Type | | ------------ | ------ | | ise_keyword | string | | ise_page | int | ```js pa.sendEvent('internal_search_result.display', { 'ise_keyword' : 'daft', 'ise_page' : 2, }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("internal_search_result.display") .properties( Property(PropertyName("ise_keyword"), "daft"), Property(PropertyName("ise_page"), 2), ) .build() ) ``` ```java pa.sendEvent(new Event("internal_search_result.display", new HashMap() {{ put("ise_keyword", "daft"); put("ise_page", 2); }})); ``` ```swift pa.sendEvent(Event("internal_search_result.display", data: [ "ise_keyword" : "daft", "ise_page" : 2 ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "internal_search_result.display", properties: [ Property.string(name: "ise_keyword", value: "daft"), Property.int(name: "ise_page", value: 2), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "internal_search_result.display", "data": { "ise_keyword": "daft", "ise_page": 2 } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=internal_search_result.display&props=[["ise_keyword","daft"],["ise_page",2]]) ### Result click #### Event name `internal_search_result.click` #### Standard properties | Property | Type | | ---------------- | ------ | | ise_keyword | string | | ise_click_rank | int | | ise_page | int | ```js pa.sendEvent('internal_search_result.click', { 'ise_keyword' : 'daft', 'ise_click_rank' : 2, 'ise_page' : 1, }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("internal_search_result.click") .properties( Property(PropertyName("ise_keyword"), "daft"), Property(PropertyName("ise_click_rank"), 2), Property(PropertyName("ise_page"), 1), ) .build() ) ``` ```java pa.sendEvent(new Event("internal_search_result.click", new HashMap() {{ put("ise_keyword", "daft"); put("ise_click_rank", 2); put("ise_page", 1); }})); ``` ```swift pa.sendEvent(Event("internal_search_result.click", data: [ "ise_keyword" : "daft", "ise_click_rank" : 2, "ise_page" : 1 ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "internal_search_result.click", properties: [ Property.string(name: "ise_keyword", value: "daft"), Property.int(name: "ise_click_rank", value: 2), Property.int(name: "ise_page", value: 1), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "internal_search_result.click", "data": { "ise_keyword": "daft", "ise_click_rank": 2, "ise_page": 1 } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=internal_search_result.click&props=[["ise_keyword","daft"],["ise_click_rank",2],["ise_page",1]]) ## MV Testing #### Event name `mv_test.display` #### Standard properties | Property | Type | | ------------ | ------ | | mv_creation | string | | mv_test | string | | mv_wave | int | ```js pa.sendEvent('mv_test.display', { 'mv_creation' : 'BlueTheme', 'mv_test' : 'NewUX', 'mv_wave' : 2, }); ``` ```kotlin PianoAnalytics.getInstance().sendEvents( Event.Builder("mv_test.display") .properties( Property(PropertyName("mv_creation"), "BlueTheme"), Property(PropertyName("mv_test"), "NewUX"), Property(PropertyName("mv_wave"), 2), ) .build() ) ``` ```java pa.sendEvent(new Event("mv_test.display", new HashMap() {{ put("mv_creation", "BlueTheme"); put("mv_test", "NewUX"); put("mv_wave", 2); }})); ``` ```swift pa.sendEvent(Event("mv_test.display", data: [ "mv_creation" : "BlueTheme", "mv_test" : "NewUX", "mv_wave" : 2 ])) ``` ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "mv_test.display", properties: [ Property.string(name: "mv_creation", value: "BlueTheme"), Property.string(name: "mv_test", value: "NewUX"), Property.int(name: "mv_wave", value: 2), ]) ]); ``` ```javascript const site_id = `XXXXXXXXXX`; const visitor_id = ``; const endpoint = `.pa-cd.com`; fetch(`https://${endpoint}/event?s=${site_id}&idclient=${visitor_id}`, { method: "POST", body: JSON.stringify({ events: [{ "name": "mv_test.display", "data": { "mv_creation": "BlueTheme", "mv_test": "NewUX", "mv_wave": 2 } }] }) }) ``` [Edit code sample](/analytics/event-composer/?name=mv_test.display&props=[["mv_creation","BlueTheme"],["mv_test","NewUX"],["mv_wave",2]]) ## Batching similar events You can batch multiple similar events into a single event: they will be split by our processing. To do this, push each event as an object into the array property named `items_list`. Properties at the root of the `data` object will be pushed to each event properties. ```json { "name": "product.display", "data": { "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "items_list": [ { "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true }, { "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "16Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1499.9, "product_pricetaxfree": 1200.9, "product_stock": true } ] } } // equals to [{ "name": "product.display", "data": { "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "8Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1399.9, "product_pricetaxfree": 1120.9, "product_stock": true } }, { "name": "product.display", "data": { "product_category1": "Hardware", "product_category2": "Computer", "product_category3": "Gaming", "product_category4": "Laptop", "product_id": "LPTAX174", "product": "Laptop AX174", "product_variant": "16Go RAM", "product_brand": "Laptop", "product_discount": false, "product_placement": "banner", "product_pricetaxincluded": 1499.9, "product_pricetaxfree": 1200.9, "product_stock": true } }] ``` > note: > > You can send up to 100 items in the array. Please note that our Collection API has a payload size limit that may be reached before the 100 item limit. Please see the [dedicated page](/analytics/data-collection/how-to-send-events/collection-api/#technical-specifications). --- ## Users In order to track your authenticated users through their navigation, you can set their identifiers once and our SDKs will automatically send the dedicated properties on each event. Our SDKs will store these identifiers client-side by default. You can however disable this feature when calling the method. > important: > > The first string assigned to the `user_id` will be applied to all events within the visit. We recommend leaving it unset if the user is not logged in. ## Set user identifiers ### JavaScript Method: `pa.setUser(userId[, userCategory, enableStorage])` | Parameters | Type | Description | | ------------- | ------- | ----------------------------------------------------------------------------------- | | userId | string | User identifier | | userCategory | string | User category | | enableStorage | boolean | Indicates whether the identifiers should be stored (true \- default) or not (false) | ```js pa.setUser("WEB-192203AJ", "premium", false); ``` ### Android (3.3.0+) ```kotlin val userStorage = PianoAnalytics.getInstance().userStorage // set current user userStorage.currentUser = User("WEB-192203AJ", category = "premium", shouldBeStored = false) ``` ### Android ```dart await _pianoAnalytics.setUser( id: "WEB-192203AJ", category: "premium", enableStorage: false ); ``` ### Apple Method: `func PianoAnalytics.setUser(id) -> void` `func PianoAnalytics.setUser(id,category) -> void` `func PianoAnalytics.setUser(id,category,enableStorage) -> void` | Parameters | Type | Description | | ------------- | ------- | ----------------------------------------------------------------------------------- | | id | String | User identifier | | category | String | User category | | enableStorage | Boolean | Indicates whether the identifiers should be stored (true \- default) or not (false) | ```java pa.setUser("WEB-192203AJ", "premium", false); ``` ### Flutter Method: `pa.setUser(_ id: String, category: String? = nil, enableStorage: Bool = true)` | Parameters | Type | Description | | ------------- | ------- | ----------------------------------------------------------------------------------- | | id | String | User identifier | | category | String? | User category | | enableStorage | Bool | Indicates whether the identifiers should be stored (true \- default) or not (false) | ```swift pa.setUser("WEB-192203AJ", category: "premium", enableStorage: false); ``` ## Retrieve user data You can retrieve user data thanks to a dedicated method Method: `pa.getUser(callback)` | Parameters | Type | Description | | ---------- | -------- | ---------------------- | | callback | function | Callback of the method | ```js pa.getUser(function (userData) { console.log("User: " + userData.id + ", Category: " + userData.category); }); ``` Method: `func PianoAnalytics.getUser(PianoAnalytics.OnGetUserListener) -> void` ```java pa.getUser(user -> { // do something with user }); ``` ```dart var user = await _pianoAnalytics.getUser(); ``` Method: `pa.getUser(completionHandler: ((_ user: User?) -> Void)?)` ```swift pa.getUser { user in print(user?.id) print(user?.category) } ``` ## Delete user data You can delete user data thanks to a dedicated method Method: `pa.deleteUser()` ```js pa.deleteUser(); ``` Method: `func PianoAnalytics.deleteUser() -> void` ```java pa.deleteUser(); ``` ```dart await _pianoAnalytics.deleteUser(); ``` Method: `pa.deleteUser()` ```swift pa.deleteUser(); ``` --- ## Visitor identification ## How do we manage visitor identification ### What is visitor identification Visitor identification is the basis of all calculations in Analytics. Without a perfect management of this identifier, and a real persistence, we would not be able to calculate an exact number of visits and visitors. This visitor identifier, present on all the events we collect, is personal data. More information is available in our [Privacy Center](https://analytics-docs.piano.io/en/analytics/v1/personal-data). ### How it works ### JavaScript The visitor identification is created the first time you use a `pa.sendEvent()` / `pa.sendEvents()` method. The information is first stored in a cookie, and then sent to all future events into a query parameter. | Cookie | Querystring parameter | Format | SDK version | | ------- | --------------------- | -------- | ----------- | | pa_vid | idclient | GUID | < 6.7.0 | | _pcid | idclient | 16 char. | ≥ 6.7.0 | The visitor ID must be 16 or 36 characters long. ### Apple The visitor identification is created the first time you use a `pa.sendEvent()` / `pa.sendEvents()` method. Here is the decision tree leading to the output depending on configurations: ![Apple visitor identification decision tree](/analytics/assets/images/apple-visitor-decision-05df36816ee6e45e851c52b94ef4b17c.png) ### HTTP The management of the visitor identification is delegated to you when you use our [Collection API](/analytics/data-collection/how-to-send-events/collection-api/). Please, note that a break in the identifier will create a new visit and the detection of a new visitor. A `GUID` format is recommended. > caution: > > As the visitor identification is a key notion in Analytics (visits, visitors, ...), we recommend that you do not change our SDKs behavior regarding its management. ### Legacy visitor management More information about legacy visitor management in our [Cookies & storage](/analytics/data-collection/general/cookie-storage/#legacy-cookie-management) article. ## Visitor identification configuration You can configure the visitor identifier to suit your needs. Visitor identification behavior you can modify: | Name | Description | Type | Value | | ---------------------- | ----------------------------------------------------- | ------- | ------------------------- | | storageLifetimeVisitor | Lifetime Storage Visitor value | int | 395 (days) | | visitorStorageMode | Relative or fixed cookie lifetime value for visitor | string | fixed (default), relative | | isVisitorClientSide | Is cookie deposit client side ? If false, server side | boolean | true (default), false | To set up the configuration, see the [JavaScript SDK](/analytics/data-collection/sdks/javascript/#configuration) article. Visitor identification behavior you can modify: | Name | Description | Type | Value | | ----------------------- | --------------------------------------------------------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | visitorStorageLifetime | Lifetime Storage Visitor value | int | 395 (days) | | visitorStorageMode | Relative or fixed cookie lifetime value for visitor | string | fixed (default), relative | | ignoreLimitedAdTracking | Whether the SDK should ignore (true) or not (false) the end-user choice to limit ad tracking. | boolean | true, false (default) | | visitorIDType | Visitor ID type | string | VisitorIDType.UUID (default), VisitorIDType.ADVERTISING_ID, VisitorIDType.GOOGLE_ADVERTISING_ID, VisitorIDType.HUAWEI_OPEN_ADVERTISING_ID , VisitorIDType.CUSTOM | | visitorId | Custom visitor ID | string | 39001HUFEKK977894 | To set up the configuration, see the [Android (3.3.0+) SDK](/analytics/data-collection/sdks/android-kotlin/#instantiate-tracker) article. Visitor identification behavior you can modify: | Name | Description | Type | Value | | ----------------------- | --------------------------------------------------------------------------------------------- | ------- | ---------------------------------------------------------------------- | | visitorStorageLifetime | Lifetime Storage Visitor value | int | 395 (days) | | visitorStorageMode | Relative or fixed cookie lifetime value for visitor | string | VisitorStorageMode.fixed (default), VisitorStorageMode.relative | | ignoreLimitedAdTracking | Whether the SDK should ignore (true) or not (false) the end-user choice to limit ad tracking. | boolean | true, false (default) | | visitorIDType | Visitor ID type | string | VisitorIDType.uuid (default), VisitorIDType.adid, VisitorIDType.custom | | visitorId | Custom visitor ID (only for VisitorIDType.custom) | string | 39001HUFEKK977894 | Visitor identification behavior you can modify: | Name | Description | Type | Value | | -------------------------------- | --------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------- | | storageLifetimeVisitor | Lifetime Storage Visitor value | int | 395 (days) | | visitorStorageMode | Relative or fixed cookie lifetime value for visitor | string | fixed (default), relative | | ignoreLimitedAdvertisingTracking | Whether the SDK should ignore (true) or not (false) the end-user choice to limit ad tracking. | boolean | true, false (default) | | visitorIdType | Visitor ID type | string | uuid (default), androidId, advertisingId, googleAdvertisingId, huaweiOpenAdvertisingId , custom | | visitorId | Custom visitor ID | string | 39001HUFEKK977894 | To set up the configuration, see the [Android SDK](/analytics/data-collection/sdks/android-java/#configuration) article. Visitor identification behavior you can modify: | Name | Description | Type | Value | | -------------------------------- | --------------------------------------------------------------------------------------------- | ------- | ---------------------------------- | | storageLifetimeVisitor | Lifetime Storage Visitor value | int | 395 (days) | | visitorStorageMode | Relative or fixed cookie lifetime value for visitor | string | fixed (default), relative | | ignoreLimitedAdvertisingTracking | Whether the SDK should ignore (true) or not (false) the end-user choice to limit ad tracking. | boolean | true, false (default) | | visitorIdType | Visitor ID type | string | uuid (default), idfa, idfv, custom | | visitorId | Custom visitor ID | string | 39001HUFEKK977894 | To set up the configuration, see the [Apple SDK](/analytics/data-collection/sdks/ios-swift/#configuration) article. When using the [Collection API](/analytics/data-collection/general/implementation-methods/#collection-api), you manage the visitor identifier. ## Visitor identification management In some specific cases, it can be useful to manage the visitor identifier yourself. Depending on the platform, use dedicated configuration or methods for that matter. ≥ 6.15.0 **Custom visitor ID:** To force or set the visitor identifier, use the global `window.pdl` object: ```js window.pdl = window.pdl || {}; window.pdl.browserId = "CUSTOM_BROWSER_ID"; ``` Set `window.pdl.browserId` **before** loading the Piano Analytics script so the value is picked up on SDK initialization (same timing as other `window.pdl` settings, for example consent). The visitor ID must be 16 or 36 characters long (see the JavaScript tab in [How it works](#how-it-works) above). > Deprecated API: > > The `pa.setVisitorId(visitorId)` method is deprecated; prefer `window.pdl.browserId` for new implementations. > > For reference, the previous usage was: > > ```js pa.setVisitorId("97c7db4e-4514-4b8e-b693-bd6b57043cc1"); ``` You can also retrieve the visitor ID with a dedicated method. This can be useful to synchronize an ID between native and webviews. Method: `pa.getVisitorId()` ```js const PAVisitorId = pa.getVisitorId(); ``` ```kotlin PianoAnalytics.getInstance().customVisitorId = "97c7db4e-4514-4b8e-b693-bd6b57043cc1" ``` This will be taken into account only if `visitorIDType` is set to `VisitorIDType.CUSTOM`. You can also retrieve the visitor ID. This can be useful to synchronize an ID between native and webviews. ```kotlin val visitorId = PianoAnalytics.getInstance().visitorId ``` ```dart await _pianoAnalytics.setVisitorId( visitorId: "97c7db4e-4514-4b8e-b693-bd6b57043cc1" ); ``` This will be taken into account only if `visitorIDType` is set to `VisitorIDType.custom`. You can also retrieve the visitor ID. This can be useful to synchronize an ID between native and webviews. ```dart var visitorId = await _pianoAnalytics.getVisitorId(); ``` Method: `func PianoAnalytics.setVisitorId(_ visitorId: String) -> void` | Parameter | Type | Description | | --------- | ------ | ------------------------------------- | | visitorId | String | Visitor identifier (GUID recommended) | ```java pa.setVisitorId("97c7db4e-4514-4b8e-b693-bd6b57043cc1") ``` You can also retrieve the visitor ID with a dedicated method. This can be useful to synchronize an ID between native and webviews. Method: `func PianoAnalytics.getVisitorId(PianoAnalytics.OnGetVisitorIdListener) -> void` ```java pa.getVisitorId(visitorId -> { // visitorId fetched }); ``` Method: `pa.setVisitorId(_ visitorId: String)` | Parameter | Type | Description | | --------- | ------ | ------------------------------------- | | visitorId | String | Visitor identifier (GUID recommended) | ```swift pa.setVisitorId("97c7db4e-4514-4b8e-b693-bd6b57043cc1") ``` You can also retrieve the visitor ID with a dedicated method. This can be useful to synchronize an ID between native and webviews. Method: `pa.getVisitorId(completionHandler: ((_ visitorId: String) -> Void)?)` ```swift pa.getVisitorId { visitorId in print(visitorId) } ``` When using the [Collection API](/analytics/data-collection/general/implementation-methods/#collection-api), you have to feed the visitor identifier directly into the `idclient` querystring parameter. --- ## Catalogs data You can find detailed information about how catalogs work in our [Help center](https://analytics-docs.piano.io/en/analytics/v1/catalogs). ## Import single catalog line ### Endpoint Depending on your organization's region, you will need to send your catalog's data to the corresponding endpoint: - EU: `POST https://analytics-api-eu.piano.io/import/v1/catalogs` - US: `POST https://analytics-api-us.piano.io/import/v1/catalogs` - AP: `POST https://analytics-api-ap.piano.io/import/v1/catalogs` ### Headers #### Authentication - header name: `x-api-key` - header value: an API key from your profile in the solution with the following pattern: `_` #### `Content-Type` - header name: `Content-Type` - header value: `application/json` ### Payload The expected payload is JSON object, following the schema below: ```json { "import_id": "", "import_keys": { "key1": "val1" }, "associated_properties": { "prop1": "prop1" } } ``` #### Parameters | Parameter | Mandatory? | Type | Comment | | ---------------------- | ---------- | ------ | ----------------------------------------------------------------- | | import_id | YES | string | Catalog ID, you can retrieve it in your Data Management interface | | import_keys | YES | object | List of catalog keys and value to import | | associated_properties | YES | object | List of catalog data to import | > tip: > > You can find a catalog import example in your Data Management interface. ### Limits | Feature | Limit | | ------------------ | ----- | | JSON max body size | 100KB | ## Import multiple catalog lines In order to import multiple catalog lines, you can use a batch request. To do so, we offer a dedicated endpoint expecting ndJSON (newline-delimited JSON) as payload. ### Endpoint Depending on your organization's region, you will need to send your catalogs' data to the corresponding endpoint: - EU: `POST https://analytics-api-eu.piano.io/import/v1/catalogs/batch` - US: `POST https://analytics-api-us.piano.io/import/v1/catalogs/batch` - AP: `POST https://analytics-api-ap.piano.io/import/v1/catalogs/batch` ### Headers #### Authentication - header name: `x-api-key` - header value: an API key from your profile in the solution with the following pattern: `_` #### `Content-Type` - header name: `Content-Type` - header value: `application/x-ndjson` ### Payload The expected payload is one-line JSON object per import to proceed, following the schema below: ```json {"import_id": "","import_keys":{"key1": "val1"},"associated_properties":{"prop1": "prop1"}} {"import_id": "","import_keys":{"key1": "val2"},"associated_properties":{"prop1": "prop2"}} {"import_id": "","import_keys":{"key1": "val3"},"associated_properties":{"prop1": "prop3"}} {"import_id": "","import_keys":{"key1": "val4"},"associated_properties":{"prop1": "prop4"}} ``` #### Parameters | Parameter | Mandatory? | Type | Comment | | ---------------------- | ---------- | ------ | ----------------------------------------------------------------- | | import_id | YES | string | Catalog ID, you can retrieve it in your Data Management interface | | import_keys | YES | object | List of catalog keys and value to import | | associated_properties | YES | object | List of catalog data to import | > tip: > > You can find a catalog import example in your Data Management interface. ### Limits | Feature | Limit | | -------------------- | ----- | | ndJSON max body size | 1GB | | ndJSON max line size | 100KB | ## Date properties CSV catalog imports (manual upload and sFTP) do not support time zones. Send the value in UTC, with a `Z` suffix: `YYYY-MM-DDTHH:mm:ssZ` Example: `2026-10-09T15:11:00+09:00` is `2026-10-09T06:11:00Z`. An offset such as `+09:00` is rejected. Convert the instant to UTC before import. Removing the offset and keeping the same clock time stores a different moment. A value collected by the SDK can include an offset. That processing does not apply to a CSV catalog import. --- ## Measurements You can find detailed information about how catalogs work in our [Help center](https://analytics-docs.piano.io/en/analytics/v1/measurements_). ## Import single measurement ### Endpoint Depending on your organization's region, you will need to send your measurements to the corresponding endpoint: - EU: `POST https://analytics-api-eu.piano.io/import/v1/measurements` - US: `POST https://analytics-api-us.piano.io/import/v1/measurements` - AP: `POST https://analytics-api-ap.piano.io/import/v1/measurements` ### Headers #### Authentication - header name: `x-api-key` - header value: an API key from your profile in the solution with the following pattern: `_` #### `Content-Type` - header name: `Content-Type` - header value: `application/json` ### Payload The expected payload is a JSON object, following the schema below: ```json { "key": "", "period": "", "values": { "key1": 1, "key2": 2 }, "properties": { "property1": "Property value 1", "property2": "Property value 2" }, "site_id": 1245695 } ``` #### Parameters | Parameter | Mandatory? | Type | Comment | | ----------- | ---------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | key | YES | string | Measurement key | | period | YES / NO | string / number | Period for the measurement. Local time. [See Period format section](#period-format) for available formats. You should use either period or period_utc but it is mandatory to use one. | | period_utc | YES / NO | string / number | Period for the measurement. UTC time. [See Period format section](#period-format) for available formats. You should use either period or period_utc but it is mandatory to use one. | | values | YES | object | Measurement values | | properties | NO | object | List of analytics properties to cross data with | | site_id | YES / NO | int | Site ID. Mandatory for site-scoped measurements, must not be present for orga-scoped | > tip: > > You can find a measurement example in your Data Management interface. ### Size limits | Feature | Limit | | ------------------ | ----- | | JSON max body size | 100KB | ## Import multiple measurements In order to import multiple measurements, you can use a batch request. To do so, we offer a dedicated endpoint expecting ndJSON (newline-delimited JSON) as payload. ### Endpoint Depending on your organization's region, you will need to send your measurements to the corresponding endpoint: - EU: `POST https://analytics-api-eu.piano.io/import/v1/measurements/batch` - US: `POST https://analytics-api-us.piano.io/import/v1/measurements/batch` - AP: `POST https://analytics-api-ap.piano.io/import/v1/measurements/batch` ### Headers #### Authentication - header name: `x-api-key` - header value: an API key from your profile in the solution with the following pattern: `_` #### `Content-Type` - header name: `Content-Type` - header value: `application/x-ndjson` ### Payload The expected payload is one-line JSON object per measurement to import, following the schema below: ```json {"key":"","period":"","values":{"key1":1,"key2":2},"properties":{"property1":"Property value 1a","property2":"Property value 2a"},"site_id":1245695} {"key":"","period":"","values":{"key1":3,"key2":4},"properties":{"property1":"Property value 1b","property2":"Property value 2b"},"site_id":1245695} {"key":"","period":"","values":{"key1":5,"key2":6},"properties":{"property1":"Property value 1c","property2":"Property value 2c"},"site_id":1245695} {"key":"","period":"","values":{"key1":7,"key2":8},"properties":{"property1":"Property value 1d","property2":"Property value 2d"},"site_id":1245695} ``` #### Parameters | Parameter | Mandatory? | Type | Comment | | ----------- | ---------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | key | YES | string | Measurement key | | period | YES / NO | string / number | Period for the measurement. Local time. See Period format section for available formats. You should use either period or period_utc but it is mandatory to use one. | | period_utc | YES / NO | string / number | Period for the measurement. UTC time. See Period format section for available formats. You should use either period or period_utc but it is mandatory to use one. | | values | YES | object | Measurement values | | properties | NO | object | List of analytics properties to cross data with | | site_id | YES / NO | int | Site ID. Mandatory for site-scoped measurements, must not be present for orga-scoped | > tip: > > We highly recommend using NDJSON over JSON for your measurements ingestion. ### Size limits | Feature | Limit | | -------------------- | ----- | | ndJSON max body size | 1GB | | ndJSON max line size | 100KB | ## Period format Depending on your measurement's configured periodicity, you must use the corresponding format: | Periodicity | Format | | ----------- | ---------------------- | | Minute | YYYY-MM-DDTHH:MM:00 | | Hour | YYYY-MM-DDTHH:MM:00 | | Day | YYYYMMDD or YYYY-MM-DD | | Month | YYYYMMDD or YYYY-MM-DD | Notes: - Use `period` for local time, or `period_utc` for UTC time. Exactly one of them is required. ## Volume limits Global volume limits (maximum number of ingested measurements): - **Minute granularity:** 100 per minute, 140 000 per day - **Hour granularity:** 1 000 per hour, 24 000 per day - **Day granularity:** 100 000 per day - **Month granularity:** 100 000 per month --- ## Migration of Marketing Campaigns ## Property matching The following matching table will help you identify the property you need to use so that the data is available in the same property after migrating to the PA SDK. For example, with the PA SDK, if you want to send the affiliation type, you will need to use `at_aff_type` instead of `at_type` which was used for the smarttag. ### EMAIL MARKETING | SMARTTAG | PA SDK | | ------------------- | -------------------------- | | at_medium | at_medium | | at_campaign | at_campaign | | at_emailtype\* | at_email_type | | at_creation | at_creation | | at_send_date | at_email_send_date | | at_link | at_email_link | | at_recipient_id | at_email_recipient | | at_recipient_list | at_email_recipient_list | > note: > > `*` In some cases, the `src_campaign_group` property was filled with the value sent in the `at_emailtype` parameter. Please use the `property_key` of the property that was previously filled with the SmartTag for a seamless migration. (the `src_*` prefix must be changed into `at_*` as explained in the migration page.) ### ADVERTISING | SMARTTAG | PA SDK | | ---------------------- | -------------------------- | | at_medium | at_medium | | at_campaign | at_campaign | | at_creation | at_creation | | at_variant | at_variant | | at_format | at_format | | at_channel | at_ad_channel | | at_general_placement | at_ad_general_placement | | at_detail_placement | at_ad_detail_placement | ### SPONSORED LINKS | SMARTTAG | PA SDK | | -------------- | ---------------- | | at_medium | at_medium | | at_campaign | at_campaign | | at_platform\* | at_sl_platform | | at_creation | at_creation | | at_variant | at_variant | | at_network | at_sl_network | | at_term | at_sl_term | > note: > > `*` In some cases, the `src_campaign_group` property was filled with the value sent in the `at_platform` parameter. Please use the `property_key` of the property that was previously filled with the SmartTag for a seamless migration. (the `src_*` prefix must be changed into `at_*` as explained in the migration page.) ### AFFILIATION | SMARTTAG | PA SDK | | -------------- | ------------------- | | at_medium | at_medium | | at_campaign | at_campaign | | at_type | at_aff_type | | at_identifier | at_aff_identifier | | at_format | at_format | | at_creation | at_creation | | at_variant | at_variant | ## Value matching Some values were also transformed, you'll find the different rules below. For example, sending an advertising format = `"468"` would result in the interface as the string `"standard 468x60"`. ### EMAIL MARKETING (Emailing type) | SMARTTAG | PA SDK | | -------- | ----------- | | EREC | acquisition | | EPR | retention | | ES | promotion | ### ADVERTISING (Advertising type) | SMARTTAG | PA SDK | | -------- | -------------------- | | ADC | click advertisement | | ADI | banner advertisement | | AD | advertisement | ### ADVERTISING (Advertising format) | SMARTTAG | PA SDK | | -------- | ------------------------ | | 468 | standard 468x60 | | sky320 | skyscraper 160x320 | | sky600 | wide skyscraper 160x600 | | rect180 | small rectangle 180x150 | | rect300 | rectangle 300x250 | | wide | leaderboard 728x90 | | vert240 | vertical 120x240 | | vert600 | vertical 120x600 | | square | square 250x250 | | popup | pop-up | | popund | pop-under | | 16-9 | 16/9° 320x180 | | inter | interstitial 800x600 | | maxwid | maxi leaderboard 985x110 | | intext | intext | | rect336 | rectangle 336x280 | ### ADVERTISING (Advertising general placement) | SMARTTAG | PA SDK | | -------- | ---------------- | | GT | general rotation | | HP | homepage | | PHP | pre-homepage | ### SPONSORED LINKS (Sponsored Link Networks) | SMARTTAG | PA SDK | | -------- | ------- | | S | Search | | C | Content | | A | Action | ### SPONSORED LINKS (Sponsored Link Platforms) | SMARTTAG | PA SDK | | -------------- | ------------------------------ | | unclassified\* | Sponsored links (unclassified) | | goo | Google Adwords | | ysm | Yahoo Search Marketing | | miv | Miva | | wan | Orange | | msn | MSN | | mir | Mirago | | skl | Sklik | | adf | AdFox | | etg | eTarget | | yan | Yandex | | eba | Adcommerce (Ebay) | | sal | Search Alliance | | bin | Bing Ads | | nav | Naver | | bdu | Baidu | | qwt | Qwant | | waz | Waze | | amz | Amazon | | sez | Seznam | | syn | Google Adsense | > note: > > `*` \= represents everything that isn't on the list would be translated into the matching value. --- ## Privacy rules by Privacy Mode ## optin Details | Storage | Events | Properties | | ------- | ------ | ---------- | | All | All | All | ## exempt Details | Storage | Events | Properties | | ----------- | ---------------- | ---------------------------- | | pa_vid | click.action | app_crash | | pa_privacy | click.download | app_crash_class | | | click.exit | app_crash_screen | | | click.navigation | app_version | | | page.display | browser | | | | browser_cookie_acceptance | | | | browser_group | | | | browser_version | | | | click | | | | click_chapter1 | | | | click_chapter2 | | | | click_chapter3 | | | | click_full_name | | | | connection_monitor | | | | connection_organisation | | | | connection_type | | | | date | | | | date_day | | | | date_daynumber | | | | date_month | | | | date_monthnumber | | | | date_week | | | | date_year | | | | date_yearofweek | | | | device_brand | | | | device_display_height | | | | device_display_width | | | | device_name | | | | device_name_tech | | | | device_screen_diagonal | | | | device_screen_height | | | | device_screen_width | | | | device_type | | | | event_collection_platform | | | | event_collection_version | | | | event_hour | | | | event_id | | | | event_minute | | | | event_name | | | | event_position | | | | event_second | | | | event_time | | | | event_time_utc | | | | event_url | | | | event_url_domain | | | | event_url_full | | | | exclusion_cause | | | | exclusion_type | | | | geo_city | | | | geo_continent | | | | geo_country | | | | geo_metro | | | | geo_region | | | | hit_time_utc | | | | os | | | | os_group | | | | os_version | | | | os_version_name | | | | page | | | | page_chapter1 | | | | page_chapter2 | | | | page_chapter3 | | | | page_duration | | | | page_full_name | | | | page_position | | | | page_title_html | | | | pageview_id | | | | privacy_status | | | | site | | | | site_env | | | | site_id | | | | site_platform | | | | src | | | | src_detail | | | | src_direct_access | | | | src_organic | | | | src_organic_detail | | | | src_portal_domain | | | | src_portal_site | | | | src_portal_site_id | | | | src_portal_url | | | | src_referrer_site_domain | | | | src_referrer_site_url | | | | src_referrer_url | | | | src_se | | | | src_se_category | | | | src_se_country | | | | src_type | | | | src_url | | | | src_url_domain | | | | src_webmail | | | | visit_bounce | | | | visit_duration | | | | visit_entrypage | | | | visit_entrypage_chapter1 | | | | visit_entrypage_chapter2 | | | | visit_entrypage_chapter3 | | | | visit_entrypage_full_name | | | | visit_exitpage | | | | visit_exitpage_chapter1 | | | | visit_exitpage_chapter2 | | | | visit_exitpage_chapter3 | | | | visit_exitpage_full_name | | | | visit_hour | | | | visit_id | | | | visit_minute | | | | visit_page_views | | | | visit_second | | | | visit_time | | | | visitor_privacy_consent | | | | visitor_privacy_mode | | | | connection_type | | | | device_timestamp_utc | | | | ch_ua\* | ## no-storage Details | Storage | Events | Properties | | ------- | ------ | ---------- | | None | All | All | ## no-consent Details | Storage | Events | Properties | | ------- | ------ | ------------------------- | | None | All | visitor_privacy_consent | | | | visitor_privacy_mode | | | | connection_type | | | | device_timestamp_utc | | | | ch_ua\* | ## optout Details | Storage | Events | Properties | | ----------- | ------ | ------------------------- | | pa_vid | All | visitor_privacy_consent | | pa_privacy | | visitor_privacy_mode | | | | connection_type | | | | device_timestamp_utc | | | | ch_ua\* | ## custom Details | Storage | Events | Properties | | ----------- | ---------------- | ---------------------------- | | pa_vid | click.action | app_crash | | pa_privacy | click.download | app_crash_class | | | click.exit | app_crash_screen | | | click.navigation | app_version | | | page.display | browser | | | | browser_cookie_acceptance | | | | browser_group | | | | browser_version | | | | click | | | | click_chapter1 | | | | click_chapter2 | | | | click_chapter3 | | | | click_full_name | | | | connection_monitor | | | | connection_organisation | | | | connection_type | | | | date | | | | date_day | | | | date_daynumber | | | | date_month | | | | date_monthnumber | | | | date_week | | | | date_year | | | | date_yearofweek | | | | device_brand | | | | device_display_height | | | | device_display_width | | | | device_name | | | | device_name_tech | | | | device_screen_diagonal | | | | device_screen_height | | | | device_screen_width | | | | device_type | | | | event_collection_platform | | | | event_collection_version | | | | event_hour | | | | event_id | | | | event_minute | | | | event_name | | | | event_position | | | | event_second | | | | event_time | | | | event_time_utc | | | | event_url | | | | event_url_domain | | | | event_url_full | | | | exclusion_cause | | | | exclusion_type | | | | geo_city | | | | geo_continent | | | | geo_country | | | | geo_metro | | | | geo_region | | | | hit_time_utc | | | | os | | | | os_group | | | | os_version | | | | os_version_name | | | | page | | | | page_chapter1 | | | | page_chapter2 | | | | page_chapter3 | | | | page_duration | | | | page_full_name | | | | page_position | | | | privacy_status | | | | site | | | | site_env | | | | site_id | | | | site_platform | | | | src | | | | src_detail | | | | src_direct_access | | | | src_organic | | | | src_organic_detail | | | | src_portal_domain | | | | src_portal_site | | | | src_portal_site_id | | | | src_portal_url | | | | src_referrer_site_domain | | | | src_referrer_site_url | | | | src_referrer_url | | | | src_se | | | | src_se_category | | | | src_se_country | | | | src_type | | | | src_url | | | | src_url_domain | | | | src_webmail | | | | visit_bounce | | | | visit_duration | | | | visit_entrypage | | | | visit_entrypage_chapter1 | | | | visit_entrypage_chapter2 | | | | visit_entrypage_chapter3 | | | | visit_entrypage_full_name | | | | visit_exitpage | | | | visit_exitpage_chapter1 | | | | visit_exitpage_chapter2 | | | | visit_exitpage_chapter3 | | | | visit_exitpage_full_name | | | | visit_hour | | | | visit_id | | | | visit_minute | | | | visit_page_views | | | | visit_second | | | | visit_time | | | | visitor_privacy_consent | | | | visitor_privacy_mode | | | | connection_type | | | | device_timestamp_utc | | | | ch_ua\* | --- ## Renew CDDC certificate process ## Introduction > tip: > > We strongly recommend switching to a Piano-managed TLS certificate at any time for a seamless, hassle-free solution that ensures optimal performance and simplified management. > > The migration button is available in the custom domain side panel. Regularly, it is necessary to renew the SSL certificate linked to the CDDC collection domain, which has an expiration date by nature. The renewal goes through several phases: 1. Creation of a new CSR 2. Import of the new certificate 3. Verification of proper operation 4. Deployment We will describe here the different steps in order to proceed to the renewal of your CDDC certificate. ## Creation of a new CSR The creation of a new CSR is mandatory to renew your CDDC. This in order to renew also the private key (held by AT Internet) linked to your domain. To create your new CSR, click on the renewal link: ![Start renewing process](/analytics/assets/images/cddc-renew-start-06773374794214370a3b80e89043a02c.png) You will then be presented with a form inviting you to fill in the information related to your collection domain and the CSR. By default, the fields are pre-filled with the information filled in during the creation of the CDDC, so you can validate after proofreading: ![CSR form](/analytics/assets/images/cddc-renew-csr-form-55cec58c91647e1fb6610ba5c94c4e78.png) The CSR is then displayed: ![CSR displayed](/analytics/assets/images/cddc-renew-csr-ec3ee9a294f9111417bf1efbabda4be7.png) You can access it again later through the domain details panel. ## Import of the new certificate Once you have purchased the new certificate, you will be able to import it directly from the interface. Two fields have to be filled in: - The certificate body - The certificate chain ![Fill certificate fields](/analytics/assets/images/cddc-renew-import-593f33228c32cdcc5f0ebca3e63211f7.png) Once the certificates have been filled in and the form validated, a validation step is displayed, indicating potential errors: ![Certificate validation](/analytics/assets/images/cddc-renew-import-validation-9cd391c8033e04af8aaca984caae4bc7.png) The information in the certificate does not have to match the information in the CSR. Only the CN (Common Name) must be identical. If no errors are indicated, you will be able to finalize the import of the certificate. ## Functional check When renewing the certificate of your CDDC, we set up a test phase for the new certificate to ensure that it works properly. Here are a few ideas for you to try out. These are only examples of the possible tests. Other tests may be required by your technical teams. ![Open staging test info](/analytics/assets/images/cddc-renew-staging-02104b6a8f7bf5201d4f4b247f07b786.png) ### Retrieving the necessary information In order to perform this test procedure, you need to know: - your CDDC address: `my.domain.com` - the IP of the temporary server You can retrieve the IP address(es) from the renewal interface of your CDDC: ![Staging test info](/analytics/assets/images/cddc-renew-staging-test-06c4b0c949c753c4212b4c2decf04ef9.png) These IPs are subject to change, so make sure you update the list before testing: ### Modification of the hosts file Edit your hosts file to add one of the IP retrieved in the previous step: ```bash 34.x.y.z my.domain.com ``` ### Certificate Validation Go to the URL of your CDDC, and check: - that the padlock on your browser confirms that the connection is secure - that the message "OK" is displayed on the loaded page. Once these checks have been made, you can assume that the new certificate is attached and is working properly. ## Deployment You can then proceed with the deployment of this new certificate on your collection domain, by confirming the renewal. --- ## Android (Java) ## Integrate the library The first step to use our SDK is to integrate our library in your project. You have multiple ways to do this. ### Maven Add this following line in your `build.gradle` file (app-level) under `dependencies`: ```java implementation 'io.piano:analytics:3.x.x' // replace 3.x.x with the version you target ``` ### Manually 1. Clone the Android SDK from our [GitHub repository](https://github.com/at-internet/piano-analytics-android): - SSH: `git@github.com:at-internet/piano-analytics-android.git` - HTTPS: `https://github.com/at-internet/piano-analytics-android.git` 2. From your Android Studio - Go to File > Project Structure > Modules - Click on the plus sign + and go to Import... - Search for the cloned directory and select the piano-analytics folder - Click on Finish 3. After a sync of Gradle you might have an error like 'Build was configured to prefer settings repositories over project repositories' - Open your project-level settings.gradle file and replace/add the repositoriesMode as below - `repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)` - Resync Gradle 4. As a support to Huawei in our SDK, you might also have a warning on sync (error on build) talking about a library from `com.huawei.hms` - For Gradle plugin earlier than 7.0 - Open your project-level `build.gradle` file - Add the Maven repository as below under buildscript > repositories and allproject > repositories - `maven {url 'https://developer.huawei.com/repo/'}` - For Gradle plugin 7.0 - Open your project-level `build.gradle` file - Add the Maven repository as below under buildscript > repositories - `maven {url 'https://developer.huawei.com/repo/'}` - Open your project-level `settings.gradle` file - Add the Maven repository as below under dependencyResolutionManagement > repositories - `maven {url 'https://developer.huawei.com/repo/'}` - For Gradle plugin 7.1 or Later - Open your project-level `settings.gradle` file - Add the Maven repository as below under pluginManagement > repositories and dependencyResolutionManagement > repositories - `maven {url 'https://developer.huawei.com/repo/'}` `piano-analytics` should now be recognized as a library ## Instantiate tracker First of all, you should ensure that your app permissions are correctly set. You need the following permissions in your `AndroidManifest.xml`: ```xml ``` Our Android SDK requires you to instantiate a tracker before using it. You should pass the application context as a parameter. ```java PianoAnalytics pa = PianoAnalytics.getInstance(getApplicationContext()); ``` ## Configuration In order to set up your tracking, you need to set the configuration of the library: ```java func PianoAnalytics.setConfiguration(config); ``` Here is the minimal configuration required: ```java pa.setConfiguration(new Configuration.Builder() .withCollectDomain(".pa-cd.com") .withSite(123456789) .build() ); ``` > note: > > Don't hesitate to read our [collection methods article](/analytics/data-collection/general/collection-methods/) to find the collection domain that has been assigned to you. > > You can also use a custom domain thanks to our [CDDC](/analytics/data-collection/general/collection-methods/#custom-domain-data-collection). Here are the available configurations: | Category | Name | ConfigurationBuilder function | Description | Type | Value | More info | | -------------- | -------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | | Global | collectDomain | withCollectDomain | Collection domain | string | https://.pa-cd.com | [View](/analytics/data-collection/general/collection-methods/) | | Global | site | withSite | Site id | int | 123456789 | [View](https://analytics-docs.piano.io/en/analytics/v1/dashboard) | | Global | path | withPath | Request path | string | event | | | Global | customUserAgent | withCustomUserAgent | Custom user agent | string | My User Agent | | | Global | crashDetection | enableCrashDetection | Enable (true) or not (false) automatic crash detection | boolean | true (default), false | | | Global | sessionBackgroundDuration | withSessionBackgroundDuration | Backgound delay before considering a session as over (seconds) | int | 30 | | | Privacy | ignoreLimitedAdvertisingTracking | enableIgnoreLimitedAdvertisingTracking | Whether the SDK should ignore (true) or not (false) the end-user choice to limit ad tracking. | boolean | true, false (default) | | | Privacy | sendEventWhenOptout | enableSendEventWhenOptout | Do you want to send events when optout? | boolean | true (default), false | | | Privacy | privacyDefaultMode | withPrivacyDefaultMode | Privacy mode by default | string | optin (default) | [View](/analytics/data-collection/how-to-send-events/privacy/#default-privacy-modes) | | Storage | offlineEncryptionMode | withOfflineEncryptionMode | Offline feature encryption mode. | string | none, ifCompatible (default), force | | | Storage | offlineStorageMode | withOfflineStorageMode | Offline feature storage mode. always will always store data, you need to send data yourself required automatically manage offline storage depending on network conditions, never will never store data | string | always, required (default), never | | | Storage | offlineSendInterval | withOfflineSendInterval | Offline feature interval between sent requests | int | 500 | | | Storage | storageLifetimePrivacy | withStorageLifetimePrivacy | Lifetime Storage Privacy value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | storageLifetimeUser | withStorageLifetimeUser | Lifetime Storage User value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | storageLifetimeVisitor | withStorageLifetimeVisitor | Lifetime Storage Visitor value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | visitorStorageMode | withVisitorStorageMode | Relative or fixed cookie lifetime value for visitor | string | fixed (default), relative | | | Visitor Policy | visitorIdType | withVisitorIdType | Visitor ID type | Configuration.VisitorIDType | Configuration.VisitorIDType.UUID (default), Configuration.VisitorIDType.ANDROID_ID, Configuration.VisitorIDType.ADVERTISING_ID, Configuration.VisitorIDType.GOOGLE_ADVERTISING_ID, Configuration.VisitorIDType.HUAWEI_OPEN_ADVERTISING_ID, Configuration.VisitorIDType.CUSTOM | | | Visitor Policy | visitorId | withVisitorID | Custom visitor ID | string | 39001HUFEKK977894 | | ## Changelog You can find the Android changelog directly on [GitHub](https://github.com/at-internet/piano-analytics-android/releases). > info: > > If you want to stay updated with our SDK releases, subscribe on GitHub: > > ![Subscribe to GitHub releases](/analytics/assets/images/github-releases-89e7a4a9906dec2ea59d72c7a6f5066c.png) --- ## Android (3.3.0+) ## Before I start Since version `3.3.0`, our Android SDK is written in Kotlin. ## Integrate the library The first step to use our SDK is to integrate our library in your project. You have multiple ways to do this. ### Maven Add this following line in your `build.gradle` file (app-level) under `dependencies`: ```kotlin implementation("io.piano.android:analytics:VERSION") // replace VERSION with the version you target ``` Add required Google/Huawei ID libraries, if you want to use it as Visitor ID ```kotlin dependencies { ... // for GOOGLE_ADVERTISING_ID or ADVERTISING_ID implementation("com.google.android.gms:play-services-ads-identifier:GOOGLE_VERSION") // for HUAWEI_OPEN_ADVERTISING_ID or ADVERTISING_ID implementation("com.huawei.hms:hms-ads-identifier:HUAWEIVERSION") } ``` Add Huawei libraries repository (only if you've added Huawei ID library at the previous step) ```kotlin repositories { ... maven("https://developer.huawei.com/repo/") } ``` ### Manually 1. Clone the Android SDK from our [GitHub repository](https://github.com/at-internet/piano-analytics-android): - SSH: `git@github.com:at-internet/piano-analytics-android.git` - HTTPS: `https://github.com/at-internet/piano-analytics-android.git` 2. From your Android Studio - Go to File > Project Structure > Modules - Click on the plus sign + and go to Import... - Search for the cloned directory and select the piano-analytics folder - Click on Finish 3. After a sync of Gradle you might have an error like 'Build was configured to prefer settings repositories over project repositories' - Open your project-level settings.gradle file and replace/add the repositoriesMode as below - `repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)` - Resync Gradle 4. As a support to Huawei in our SDK, you might also have a warning on sync (error on build) talking about a library from `com.huawei.hms` - For Gradle plugin earlier than 7.0 - Open your project-level `build.gradle` file - Add the Maven repository as below under buildscript > repositories and allproject > repositories - `maven {url 'https://developer.huawei.com/repo/'}` - For Gradle plugin 7.0 - Open your project-level `build.gradle` file - Add the Maven repository as below under buildscript > repositories - `maven {url 'https://developer.huawei.com/repo/'}` - Open your project-level `settings.gradle` file - Add the Maven repository as below under dependencyResolutionManagement > repositories - `maven {url 'https://developer.huawei.com/repo/'}` - For Gradle plugin 7.1 or Later - Open your project-level `settings.gradle` file - Add the Maven repository as below under pluginManagement > repositories and dependencyResolutionManagement > repositories - `maven {url 'https://developer.huawei.com/repo/'}` `piano-analytics` should now be recognized as a library ## Instantiate tracker First of all, you should ensure that your app permissions are correctly set. You need the following permissions in your `AndroidManifest.xml`: ```xml ``` Our Android SDK requires you to configure and init a tracker before using it. You should pass the application context as a parameter. ```kotlin val configuration = Configuration.Builder( collectDomain = ".pa-cd.com", site = 123456789, // you can set other configurations here ).defaultPrivacyMode(...) // or set configurations via builder methods .build() PianoAnalytics.init(applicationContext, configuration) ``` > note: > > Don't hesitate to read our [collection methods article](/analytics/data-collection/general/collection-methods/) to find the collection domain that has been assigned to you. > > You can also use a custom domain thanks to our [CDDC](/analytics/data-collection/general/collection-methods/#custom-domain-data-collection). Here are the available configurations: | Category | Name | Description | Type | Value | More info | | -------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | Global | collectDomain | Collection domain | string | https://.pa-cd.com | [View](/analytics/data-collection/general/collection-methods/) | | Global | site | Site id | int | 123456789 | [View](https://analytics-docs.piano.io/en/analytics/v1/dashboard) | | Global | path | Request path | string | event | | | Global | reportUrlProvider | ≥ 3.3.2 Dynamic provider for collection domain, site id and path. Overrides static collectDomain, site and path. | ReportUrlProvider | Custom implementation or StaticReportUrlProvider | [View](#reporturlprovider) | | Global | detectCrashes | Enable (true) or not (false) automatic crash detection | boolean | true (default), false | | | Global | sessionBackgroundDuration | Backgound delay before considering a session as over (seconds) | int | 30 (default) | | | Privacy | ignoreLimitedAdTracking | Whether the SDK should ignore (true) or not (false) the end-user choice to limit ad tracking. | boolean | true, false (default) | | | Privacy | sendEventWhenOptout | Do you want to send events when optout? | boolean | true (default), false | | | Privacy | defaultPrivacyMode | Privacy mode by default | Configuration.PrivacyMode | optin (default) | [View](/analytics/data-collection/how-to-send-events/privacy/#default-privacy-modes) | | Storage | offlineStorageMode | Offline feature storage mode. Configuration.OfflineStorageMode.ALWAYS will always store data, you need to send data yourself Configuration.OfflineStorageMode.REQUIRED automatically manage offline storage depending on network conditions. If you want to disable storage, set eventsOfflineStorageLifetime to 0. | Configuration.OfflineStorageMode | Configuration.OfflineStorageMode.ALWAYS, Configuration.OfflineStorageMode.REQUIRED (default) | | | Storage | eventsOfflineStorageLifetime | Offline feature storage lifetime (days). | int | 30 (default) | | | Storage | privacyStorageLifetime | Lifetime Storage Privacy value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | userStorageLifetime | Lifetime Storage User value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | visitorStorageLifetime | Lifetime Storage Visitor value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | visitorStorageMode | Relative or fixed cookie lifetime value for visitor | Configuration.VisitorStorageMode | Configuration.VisitorStorageMode.FIXED (default), Configuration.VisitorStorageMode.RELATIVE | | | Visitor Policy | visitorIDType | Visitor ID type | Configuration.VisitorIDType | Configuration.VisitorIDType.UUID (default), Configuration.VisitorIDType.ADVERTISING_ID, Configuration.VisitorIDType.GOOGLE_ADVERTISING_ID, Configuration.VisitorIDType.HUAWEI_OPEN_ADVERTISING_ID, Configuration.VisitorIDType.CUSTOM | | ### Dynamically update collect domain and site `ReportUrlProvider` is available since ≥ 3.3.2. Since version `3.3.0`, the SDK configuration cannot be replaced after `PianoAnalytics.init()`. If you need to switch `collectDomain`, `site`, or `path` at runtime (for example when the end user changes country or environment), pass a custom `ReportUrlProvider` at initialization. You cannot replace the `ReportUrlProvider` instance after init, but the SDK does not cache the values it returns. Each time an event is sent, the SDK reads the current `collectDomain`, `site`, and `path` from your provider. ```kotlin class CustomReportUrlProvider( private val remoteConfig: FirebaseRemoteConfig, ) : ReportUrlProvider { override val collectDomain: String get() = remoteConfig.getString("collectDomain") override val site: Int get() = remoteConfig.getInt("site") // Optional — defaults to Configuration.DEFAULT_PATH ("event") // override val path: String // get() = remoteConfig.getString("path") } val configuration = Configuration.Builder( reportUrlProvider = CustomReportUrlProvider(remoteConfig), ).build() PianoAnalytics.init(applicationContext, configuration) ``` You can also keep mutable fields in your provider and update them when the selected environment changes: ```kotlin class MutableReportUrlProvider( override var collectDomain: String, override var site: Int, ) : ReportUrlProvider val reportUrlProvider = MutableReportUrlProvider( collectDomain = ".pa-cd.com", site = 123456789, ) val configuration = Configuration.Builder( reportUrlProvider = reportUrlProvider, ).build() PianoAnalytics.init(applicationContext, configuration) // Later, when the environment changes: reportUrlProvider.collectDomain = ".pa-cd.com" reportUrlProvider.site = 987654321 ``` > warning: > > Events already stored offline keep being flushed with the **current** provider values. If you change `collectDomain` or `site`, previously stored events may be sent to the new destination. > > Call `PianoAnalytics.getInstance().deleteOfflineStorage()` before switching if you want to drop unsynced events instead. ### Data storage encryption If you need your data storage to be encrypted, you should specify an encoder on SDK init: ```kotlin object PlainDataEncoder : DataEncoder { override fun encode(data: String): String = data override fun decode(data: String): String = data } PianoAnalytics.init(applicationContext, configuration, PlainDataEncoder) ``` ## Changelog You can find the Android changelog directly on [GitHub](https://github.com/at-internet/piano-analytics-android/releases). > info: > > If you want to stay updated with our SDK releases, subscribe on GitHub: > > ![Subscribe to GitHub releases](/analytics/assets/images/github-releases-89e7a4a9906dec2ea59d72c7a6f5066c.png) ### Migration from `< 3.3.0` We rewritten our SDK from Java to Kotlin starting from version `3.3.0`. Here are the breaking changes you should be aware of when migrating from a version `< 3.3.0`: - `io.piano.analytics` is now `io.piano.android.analytics`. - You should update your Maven implementation: `implementation("io.piano.android:analytics:VERSION")`. - You should update your imports: `import io.piano.android.analytics.PianoAnalytics`. - Event tagging has changed. Please [check our documentation](/analytics/data-collection/how-to-send-events/send-events-via-sdks/#tagging-methods). - We do not provide `sendEvent()` method anymore, only `sendEvents()`. - AV Insights tagging has changed. Please [check our documentation](/analytics/data-collection/how-to-send-events/av-insights/). - `setProperty` method should be updated to [use ContextProperties](/analytics/data-collection/how-to-send-events/send-events-via-sdks/#add-properties-to-subsequent-events). - Privacy management has been reviewed, please [check our documentation](/analytics/data-collection/how-to-send-events/privacy/). - We don't offer Android ID as a visitor identification option anymore, to follow [Android guidelines](https://developer.android.com/training/articles/user-data-ids). - SDK initialisation has changed. Please [check our documentation](#instantiate-tracker). - Configuration can't be changed after init anymore. To switch `collectDomain`, `site`, or `path` at runtime, use a [ReportUrlProvider](#reporturlprovider) (≥ 3.3.2). - Some configuration names have changes: - `visitorIdType` \-> `visitorIDType` - `privacyDefaultMode` \-> `defaultPrivacyMode` - `storageLifetimeVisitor` \-> `visitorStorageLifetime` - `storageLifetimePrivacy` \-> `privacyStorageLifetime` - `storageLifetimeUser` \-> `userStorageLifetime` - `storageLifetimeVisitor` \-> `visitorStorageLifetime` - `ignoreLimitedAdvertisingTracking` \-> `ignoreLimitedAdTracking` - `crashDetection` \-> `detectCrashes` - Some configurations must be implemented in another way: - `offlineEncryptionMode` must be replaced by an [encoder set on SDK init](#data-storage-encryption). - `visitorId` must be set using `PianoAnalytics.getInstance().customVisitorId = "custom-visitor-id"` (used only if `visitorIDType` is set to `VisitorIDType.CUSTOM`) - You can't set custom User-Agent anymore (now fixed to `Piano Analytics SDK `). --- ## Flutter Our Flutter SDK is available on [pub.dev](https://pub.dev/packages/piano_analytics), sources are available on [GitHub](https://github.com/at-internet/piano-analytics-flutter). > tip: > > You can check our [demo application](https://github.com/at-internet/piano-analytics-flutter/tree/main/example) for minimal implementation example. > warning: > > AV Insight tracking is currently not available on Flutter SDK. Do not hesitate to contribute on GitHub! ## Getting Started You need to use [piano_consents package](https://pub.dev/packages/piano_consents). 1. Add this to your `pubspec.yaml` file: ```yaml dependencies: piano_analytics: ^1.1.3 ``` 1. Install the plugin using the command ```bash flutter pub get ``` ## Usage 1. Initialize `PianoAnalytics` with your site and collect domain in your application initialization ```dart import 'package:piano_analytics/piano_analytics.dart'; ... class _MyAppState extends State { final _pianoAnalytics = PianoAnalytics( site: 123456789, collectDomain: "xxxxxxx.pa-cd.com", visitorIDType: VisitorIDType.uuid, storageLifetimeVisitor: 395, visitorStorageMode: VisitorStorageMode.fixed, ignoreLimitedAdvertisingTracking: true, visitorId: "97c7db4e-4514-4b8e-b693-bd6b57043cc1" ); @override void initState() { super.initState(); initPlugins(); } Future initPlugins() async { ... await _pianoAnalytics.init(); } ... } ``` 1. Send events ```dart await _pianoAnalytics.sendEvents(events: [ Event(name: "page.display", properties: [ Property.bool(name: "bool", value: true), Property.int(name: "int", value: 1), Property.int(name: "long", value: 9007199254740992), Property.double(name: "double", value: 1.0), Property.string(name: "string", value: "value"), Property.date(name: "date", value: DateTime.now()), Property.intArray(name: "intArray", value: [1, 2, 3]), Property.doubleArray(name: "doubleArray", value: [1.0, 2.0, 3.0]), Property.stringArray(name: "stringArray", value: ["a", "b", "c"]) ]) ]); ``` ## Consents 1. Add this to your `pubspec.yaml` file: ```yaml dependencies: piano_consents: ^1.0.1 ``` 1. Install the plugin using the command ```bash flutter pub get ``` ### Initialize PianoConsents > Important: > > Initialize `PianoConsents` before initializing `PianoAnalytics` ```dart import 'package:piano_consents/piano_consents.dart'; import 'package:piano_analytics/piano_analytics.dart'; ... class _MyAppState extends State { final _pianoConsents = PianoConsents( requireConsents: true, defaultPurposes: { PianoConsentProduct.pa: PianoConsentPurpose.audienceMeasurement } ); final _pianoAnalytics = PianoAnalytics(...); @override void initState() { super.initState(); initPlugins(); } Future initPlugins() async { ... await _pianoConsents.init(); ... } ... } ``` ### Set consents ```dart await _pianoConsents.set( purpose: PianoConsentPurpose.audienceMeasurement, mode: PianoConsentMode.essential, products: [PianoConsentProduct.pa]); ``` ### Set all consents ```dart await _pianoConsents.setAll(mode: PianoConsentMode.essential); ``` ### Set default consents ```dart await _pianoConsents.clear(); ``` --- ## iOS (Swift) ## Integrate the library The first step to use our SDK is to integrate our library in your project. You have multiple ways to do this. ### SPM (Swift Package Manager) Add our SDK's GitHub repository as an external dependency: `https://github.com/at-internet/piano-analytics-apple` ### Carthage Add our SDK's GitHub repository as an external dependency in your `Cartfile`: ```json github "at-internet/piano-analytics-apple" ~> 3.0 ``` ### Cocoapods Add our SDK's Cocoapods podname as an external dependency in your `Podfile`: ```json pod "PianoAnalytics/iOS", ">=3.0" ``` ## Configuration In order to set up your tracking, you need to set the configuration of the library: ```swift pa.setConfiguration(_ config: Configuration); ``` Here is the minimal configuration required: ```swift pa.setConfiguration(ConfigurationBuilder() .withCollectDomain(".pa-cd.com") .withSite(123456789) .build() ) ``` > note: > > Don't hesitate to read our [collection methods article](/analytics/data-collection/general/collection-methods/) to find the collection domain that has been assigned to you. > > You can also use a custom domain thanks to our [CDDC](/analytics/data-collection/general/collection-methods/#custom-domain-data-collection). Here are the available configurations: | Category | Name | ConfigurationBuilder function | Description | Type | Value | More info | | -------------- | -------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | ----------------------------------- | ------------------------------------------------------------------------------------ | | Global | collectDomain | withCollectDomain | Collection domain | string | .pa-cd.com | [View](/analytics/data-collection/general/collection-methods/) | | Global | site | withSite | Site id | int | 123456789 | [View](https://analytics-docs.piano.io/en/analytics/v1/dashboard) | | Global | path | withPath | Request path | string | event | | | Global | customUserAgent | withCustomUserAgent | Custom user agent | string | My User Agent | | | Global | crashDetection | enableCrashDetection | Enable (true) or not (false) automatic crash detection | boolean | true (default), false | | | Global | sessionBackgroundDuration | withSessionBackgroundDuration | Backgound delay before considering a session as over (seconds) | int | 30 | | | Privacy | ignoreLimitedAdvertisingTracking | enableIgnoreLimitedAdvertisingTracking | Whether the SDK should ignore (true) or not (false) the end-user choice to limit ad tracking. | boolean | true, false (default) | | | Privacy | sendEventWhenOptout | enableSendEventWhenOptout | Do you want to send events when optout? | boolean | true (default), false | | | Privacy | privacyDefaultMode | withPrivacyDefaultMode | Privacy mode by default | string | optin (default) | [View](/analytics/data-collection/how-to-send-events/privacy/#default-privacy-modes) | | Storage | offlineEncryptionMode | withOfflineEncryptionMode | Offline feature encryption mode. | string | none, ifCompatible (default), force | | | Storage | offlineStorageMode | withOfflineStorageMode | Offline feature storage mode. always will always store data, you need to send data yourself required automatically manage offline storage depending on network conditions, never will never store data | string | always, required (default), never | | | Storage | offlineSendInterval | withOfflineSendInterval | Offline feature interval between sent requests | int | 500 | | | Storage | storageLifetimePrivacy | withStorageLifetimePrivacy | Lifetime Storage Privacy value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | storageLifetimeUser | withStorageLifetimeUser | Lifetime Storage User value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | storageLifetimeVisitor | withStorageLifetimeVisitor | Lifetime Storage Visitor value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | visitorStorageMode | withVisitorStorageMode | Relative or fixed cookie lifetime value for visitor | string | fixed (default), relative | | | Visitor Policy | visitorIdType | withVisitorIdType | Visitor ID type | string | uuid (default), idfa, idfv, custom | | | Visitor Policy | visitorId | withVisitorID | Custom visitor ID | string | 39001HUFEKK977894 | | ## Changelog You can find the iOS changelog directly on [GitHub](https://github.com/at-internet/piano-analytics-apple/releases). > info: > > If you want to stay updated with our SDK releases, subscribe on GitHub: > > ![Subscribe to GitHub releases](/analytics/assets/images/github-releases-89e7a4a9906dec2ea59d72c7a6f5066c.png) ## Apple Privacy Manifest Apple is emphasizing transparency and user privacy on the App Store by guiding developers on how to describe data usage and permissions required in their apps. Developers must detail data usage in their [privacy manifests](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests#4250556), including data managed by third-party SDKs, to inform users about data collection and usage. Developers are guided on the use of the [Required Reason API](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api) to justify requested permissions, improving users' understanding of the need for certain data or functionality. As provided our DPA: > "The processor shall refrain from any use of the data other than that strictly necessary to provide the solution to the controller". > > — Article 8 of our DPA - Purpose limitation That's why we've provided you with a sample table to meet Apple's needs, to be completed as required. ### Data usage | Data type | Value | NSPrivacyCollectedDataTypeLinked | NSPrivacyCollectedDataTypeTracking | NSPrivacyCollectedDataTypePurposes | | ----------------------------- | -------------------------------------------- | -------------------------------- | ---------------------------------- | ------------------------------------------ | | Device ID | NSPrivacyCollectedDataTypeProductInteraction | True | True | NSPrivacyCollectedDataTypePurposeAnalytics | | Other usage data | NSPrivacyCollectedDataTypeOtherUsageData | True | True | NSPrivacyCollectedDataTypePurposeAnalytics | | Crash data *(optional)* | NSPrivacyCollectedDataTypeCrashData | True | True | NSPrivacyCollectedDataTypePurposeAnalytics | | User ID *(optional)* | NSPrivacyCollectedDataTypeUserID | True | True | NSPrivacyCollectedDataTypePurposeAnalytics | | Other data types *(optional)* | NSPrivacyCollectedDataTypeOtherDataTypes | True | True | NSPrivacyCollectedDataTypePurposeAnalytics | > note: > > Optional data types depend on your implementation. ### API | API | NSPrivacyAccessedAPIType | NSPrivacyAccessedAPITypeReasons | | ------------ | ---------------------------------------- | ------------------------------- | | UserDefaults | NSPrivacyAccessedAPICategoryUserDefaults | CA92.1 | --- ## JavaScript (browserless) Our JS browserless SDK is intended for JavaScript runtimes outside the browser (for example Node.js or other server-side environments). The main difference from the standard JS SDK is that it doesn't call browser APIs (for example cookie storage, window dimensions, `navigator.sendBeacon()`, …). In this article, we will explain the specific implementation requirements. Tagging methods and most of the JS SDK features are the same. ## Library installation Install our [NPM package](https://www.npmjs.com/package/piano-analytics-js): ### NPM ```bash npm install piano-analytics-js --save ``` ### Yarn ```bash yarn add piano-analytics-js ``` ## Tracker initialization You need to initialize a tracker instance in order to use the SDK. Here is an example: ```js import { pianoAnalytics } from "piano-analytics-js"; // for commonJS environment you can do the following // const pianoAnalytics = require('piano-analytics-js').pianoAnalytics; pianoAnalytics.setConfigurations({ site: 123456789, collectDomain: "https://my.collect.domain", }); pianoAnalytics.sendEvent("page.display", { page: "Page label", }); ``` ## Unavailable properties Since the SDK doesn't use browsers' APIs, here are the properties it can't retrieve automatically - `idclient` - `device_screen_width` - `device_screen_height` - `device_display_width` - `device_display_height` - `browser_language` - `browser_language_local` - `previous_url` - `event_url_full` - `ch_ua` --- ## JavaScript ## Introduction The Piano Analytics JavaScript SDK is the most popular way to implement data collection on websites. This lightweight library enables you to track user interactions, page views, conversions, and custom events with minimal setup. **What you'll learn in this guide:** - How to load and configure the JavaScript SDK - Different implementation methods - Basic and advanced configuration options - How to send events and track user behavior **Prerequisites:** - Basic knowledge of HTML and JavaScript - Access to your Piano Analytics site ID and collection domain - Ability to modify your website's code > attention: > > The legacy `xtor` marketing campaign syntax is no longer recognized. Use ["at_"](/analytics/data-collection/how-to-send-events/marketing-campaigns/) instead. ## Load the library The first step to use our SDK is to load the JS file. You have two ways to do this: ### CDN We offer delivery of our JS SDK on our CDN. You can choose between different implementation approaches: #### Standard implementation (≥ 6.16.0) Our recommended approach combines library loading and configuration in a single, self-contained script: ```javascript (function (_config) { var script = document.createElement("script"); script.src = "https://tag.aticdn.net/piano-analytics.js"; script.async = true; script.dataset.config = JSON.stringify(_config); document.head.appendChild(script); })({ site: 123456789, collectDomain: "https://xxxxxxx.pa-cd.com", consentDefaultMode: "opt-in", }); ``` > advantages: > - **Single script**: No need to manage separate loading and configuration steps > - **Asynchronous loading**: Non-blocking script execution > - **Configuration via data attribute**: Clean configuration management > note: > > Replace `123456789` with your site ID and `xxxxxxx.pa-cd.com` with your collection domain. You can customize any configuration parameters within the `_config` object. > > To use a specific version, replace `piano-analytics.js` with `js-sdk/piano-analytics-.js` in the script source (≥ 6.16.0). #### Traditional script tag You can also load our SDK using traditional HTML script tags: ```html ``` #### Available files We offer delivery of every version of our JS SDK on our CDN, the file URL follows this pattern: `https://tag.aticdn.net/js-sdk/piano-analytics-.js`. You can also load the latest version from `https://tag.aticdn.net/piano-analytics.js`. **Latest version: 6.18.0** **Standard implementation:** ```javascript (function (_config) { var script = document.createElement("script"); script.src = "https://tag.aticdn.net/js-sdk/piano-analytics-6.18.0.js"; script.async = true; script.dataset.config = JSON.stringify(_config); document.head.appendChild(script); })({ site: 123456789, collectDomain: "https://xxxxxxx.pa-cd.com", consentDefaultMode: "opt-in", }); ``` **Traditional script tag:** ```html ``` You can find a list of all our JS SDK versions on the [GitHub releases page](https://github.com/at-internet/piano-analytics-js/releases). Available files #### 6.18.0 Release date (CDN file): 2026-05-05 CDN URL: `https://tag.aticdn.net/js-sdk/piano-analytics-6.18.0.js` SHA384 SRI checksum: `integrity="sha384-QIOkC7r0xWo/J/PbjqOAAS8H3Lc8KIbOOKaf36oiZkwWpKC/SofEtNlX+88GBmif"` Source code: [View on Github](https://github.com/at-internet/piano-analytics-js/tree/v6.18.0) #### 6.17.1 Release date (CDN file): 2026-05-05 CDN URL: `https://tag.aticdn.net/js-sdk/piano-analytics-6.17.1.js` SHA384 SRI checksum: `integrity="sha384-gpmdaEaw46zmf6BOVonMShB5XOQT7V/te2r+ffTpLFGPe+y6QSzSXeb52+LTP9+6"` Source code: [View on Github](https://github.com/at-internet/piano-analytics-js/tree/v6.17.1) #### 6.17.0 Release date (CDN file): 2026-01-19 CDN URL: `https://tag.aticdn.net/js-sdk/piano-analytics-6.17.0.js` SHA384 SRI checksum: `integrity="sha384-vLmChHJVXxcl/Emd2dCu+ol0482rB3EFX1escCBS25RTUd04lU12OeYzHKKIwkwO"` Source code: [View on Github](https://github.com/at-internet/piano-analytics-js/tree/v6.17.0) [View all available files →](../../cdn/js) > attention: > > Using the latest version file (`piano-analytics.js`) will automatically upgrade the SDK when new releases ship. If you need control over the version in use, use a versioned file instead. #### Custom domain (CDDC) If you collect data with [Custom Domain Data Collection (CDDC)](/analytics/data-collection/general/collection-methods/#custom-domain-data-collection), the latest SDK file is also served from your collection domain: ```text https:///piano-analytics.js ``` For example, if your CDDC domain is `collect.example.com`, load the SDK from `https://collect.example.com/piano-analytics.js`. This URL follows the latest release, with the same automatic upgrade behavior as `https://tag.aticdn.net/piano-analytics.js`. ### Download You can also [download the file from GitHub](https://github.com/at-internet/piano-analytics-js) and host it on your own server or CDN. ## Configuration In order to set up your tracking, you need to set the configuration of the library. To do this, we offer two configuration methods depending on what you want to set up. ### Basic configuration ```js pa.setConfiguration(configurationKey, configurationValue); // or pa.setConfigurations(configurationObject); ``` Here is the minimal configuration required: ```js try { // Basic configuration method pa.setConfiguration("site", 123456789); // your site id pa.setConfiguration("collectDomain", "https://.pa-cd.com"); // your collection domain // or bulk configuration (recommended) pa.setConfigurations({ site: 123456789, collectDomain: "https://.pa-cd.com", }); } catch (error) { console.error("Piano Analytics configuration error:", error); // Handle configuration failure gracefully } ``` > note: > > Don't hesitate to read our [collection methods article](/analytics/data-collection/general/collection-methods/) to find the collection domain that has been assigned to you. > > You can also use a custom domain thanks to our [CDDC](/analytics/data-collection/general/collection-methods/#custom-domain-data-collection). Here are the available configurations: | Category | Name | Description | Type | Value | More info | | -------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------- | | Global | collectDomain | Collection domain | string | "https://.pa-cd.com" | [View](/analytics/data-collection/general/collection-methods/) | | Global | site | Site id | int | 123456789 | [View](https://analytics-docs.piano.io/en/analytics/v1/dashboard) | | Global | path | Request path | string | "event" | | | Global | addEventURL | Automatically adds a event_url_full property to all events, containing the URL of the current page. Was page_url on < 6.10.0 | string | "false", "withoutQS" (default), "true" | | | Global | sendEmptyProperties | ≥ 6.9.0 Allow sending properties with an empty value (empty string or undefined) | boolean | true (default), false | | | Global | useSendBeacon | ≥ 6.16.0 Allow using sendBeacon browser API to send events. Use fetch if false | boolean | true, false (default since 6.18.0) | | | Global | enableAutomaticPageRefresh | ≥ 6.12.0 Allow the SDK to automatically manage page context refresh | boolean | true (default), false | [View](/analytics/data-collection/sdks/javascript/#spa) | | Privacy | sendEventWhenOptout | Whether to send events when the user has opted out | boolean | true (default), false | | | Campaign | campaignPrefix | Choose with an order of priority the type of campaign to be collected | array | \["at_"\] | [View](/analytics/data-collection/how-to-send-events/marketing-campaigns/#collect-utm-as-sources) | | Campaign | enableUTMTracking | UTM parameters collected as properties | boolean | true (default), false | [View](/analytics/data-collection/how-to-send-events/marketing-campaigns/#collect-utm-as-properties) | | Global | allowHighEntropyClientHints | ≥ 6.9.0 Allow retrieving of high entropy client hints | boolean | true (default), false | [View](https://developer.mozilla.org/en-US/docs/Web/HTTP/Client_hints#low_entropy_hints) | ### SDK configuration This method runs asynchronously and overrides the SDK configuration. You have to define it before SDK's loading. ```js window._pac = window._pac || {}; ; ``` > tip: > > We recommend setting the configuration within the `` of your page. Here is an example of what you can configure: ```js window._pac = window._pac || {}; _pac.cookieDomain = ".mysite.com"; _pac.path = "event"; ; ``` These configurations must be set before loading the SDK: | Category | Name | Description | Type | Value | More info | | -------------- | ---------------------- | ------------------------------------------------------------ | ------- | ---------------------------------------- | ------------------------------------------------------------------------------------ | | Global | cookieDomain | Cookie domain | string | "mysite.com" (current domain by default) | | | Global | cookieSameSite | SameSite attribute for client-side cookies | string | "lax" (default), "none", "strict" | | | Global | cookieSecure | Secure attribute for client-side cookies | boolean | true (default), false | | | Global | encodeStorageBase64 | Whether storage values are Base64-encoded | boolean | true, false (default) | | | Global | queueVarName | ≥ 6.4.0 Variable name used for queuing | string | "_paq" (default) | [View](#asynchronous-tagging) | | Global | globalVarName | ≥ 6.12.0 Variable name used for global instance | string | "pa" (default) | | | Privacy | privacyDefaultMode | Privacy mode by default | string | "optin" (default) | [View](/analytics/data-collection/how-to-send-events/privacy/#default-privacy-modes) | | Privacy | enableExtendedOptout | ≥ 6.13.0 Enable extended opt-out feature | boolean | false (default) | [View](/analytics/data-collection/how-to-send-events/consent/) | | Storage | storageLifetimePrivacy | Lifetime Storage Privacy value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | storageLifetimeUser | Lifetime Storage User value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | storageLifetimeVisitor | Lifetime Storage Visitor value | int | 395 (days) | [View](/analytics/data-collection/general/cookie-storage/) | | Storage | visitorStorageMode | Relative or fixed cookie lifetime value for visitor | string | "fixed" (default), "relative" | | | Visitor Policy | isVisitorClientSide | Whether the cookie is set client-side. If false, server-side | boolean | true (default), false | | > note: > > All configurations in "Basic configuration" are compatible with "SDK configuration" method. ## Asynchronous tagging The object `_paq` can be used to push commands in a queue, executed as soon as the tracker is loaded. Each command is represented by an array pushed to the queue: `_paq.push([command, (... args)]);` The first element of the array represents the tracker's method to call (e.g.: `sendEvent`, `setProperty`, `setUser`...). The following elements are the method's arguments. Example: ```javascript let _paq = window._paq || []; try { _paq.push(["setUser", "ID18859", "Premium user", true]); _paq.push(["sendEvent", "page.display", { page: "homepage" }]); } catch (error) { console.error("Piano Analytics error:", error); } ``` > note: > > In some cases, you could need to change the name of the variable used for queuing asynchronous calls (e.g.: Matomo conflict). This can be changed thanks to the configuration key `queueVarName`. > > ```javascript window._pac = window._pac || {}; _pac.queueVarName = '_paqueue'; // set the queue variable name window._paqueue = window._paqueue || []; _paqueue.push(['sendEvent', 'page.display', {"page": "homepage", ...}]); ``` ## Piano Cross-product integration Since v6.7.0, PA JS SDK integrates native synchronization with other Piano products SDKs. This includes automatic retrieval of a common visitor ID, pageview ID, user access, and content properties. ### SPA In order to refresh the `pageview_id` in your SPA, you can call the method `pa.refresh()` to regenerate the page context. #### Automatic page context management Since version `6.12.0`, the SDK automatically refreshes the page context when a second `page.display` event is sent on the same instance (configuration `enableAutomaticPageRefresh`: `true` by default). Only one of both (`pa.refresh()` or automatic detection) is possible for an implementation. Only the first one encountered on an instance will be available for the lifetime of the instance. ### Content properties Since 6.7.0, the SDK automatically sends content properties from HTML markup. Please check [this page](https://docs.piano.io/en/subscriptions/composer-1x-meta-tag-recommendations) for expected markup. In order to set the content properties, you can either do it through Composer implementation, or through PA SDK: ```javascript // set one content property pa.setContentProperty("type", "article"); // -> content_type = 'article' // or set multiple properties at once pa.setContentProperties({ type: "article", publication_date: 1669109350, }); // -> content_type = 'article' // -> content_publication_date = 1669109350 ``` > note: > > When using these methods, `content_` prefix is automatically added to the property key. ## Content Security Policy (CSP) | Configure your CSP settings: | | | ---------------------------- | -------------- | | SDK loading source | CDNSelf-hosted | | Collection domain | | The following directives are needed in the CSP to use this setup: ```bash script-src: 'unsafe-inline' https://tag.aticdn.net connect-src: https://xxxxxxx.pa-cd.com ``` ## Changelog You can find the JavaScript changelog directly on [GitHub](https://github.com/at-internet/piano-analytics-js/releases). > info: > > If you want to stay updated with our SDK releases, subscribe on GitHub: > > ![Subscribe to GitHub releases](/analytics/assets/images/github-releases-89e7a4a9906dec2ea59d72c7a6f5066c.png) --- ## Other implementations This article lists other implementation methods that we offer. ## AMP AMP doesn't offer native Piano Analytics integration. You need to use a dedicated `` tag to track events. Example (highlighted lines must be edited): ```js ``` --- ## Authentication ## Foreword An API Key gives the same permissions than the user who created it. If the user loses rights on a site, then he won’t be able to use his API key to get data on this site anymore. If the user gets rights on a new site, then he will be able to use his API key to get data on this site. The API Key aims at being used with API URLs retrieved from Data Query. If you are an SSO user, you must use an API Key to query AT Internet REST API. You can create a new API key on your [profile page](https://my.piano.io/profile/#/apikeys). An API Key can only be created by an authenticated user who can manipulate data. This user must have at least one of the following roles: - Administrators - Delegates - Advanced Analysts - Analysts or Custom Roles with the “Handle data” tool The API Key is created, enabled, disabled and deleted by each user independently. API key has to be included in all API requests to the server in a header that looks like the following: `x-api-key: YOURAPIKEY` You can find more information in the [help centre](https://analytics-docs.piano.io/en/analytics/v1/api-keys). ## Examples You can authenticate to our API by passing your API Key in the header, here are a few possibilities. ### JavaScript ```javascript xhr.setRequestHeader("x-api-key", "YOURAPIKEY"); ``` ### Shell ```shell curl "https://api.atinternet.io/v3/data/getData" \ -H "x-api-key: YOURAPIKEY" ``` ### Python ```python headers = { 'x-api-key': "YOURAPIKEY", } ``` ### Ruby ```ruby request["x-api-key"] = 'YOURAPIKEY' ``` --- ## Make your first API call ## Basic example You can find in this table the explanation of the main parameters. If you want more information, see the corresponding articles in the documentation under **Parameters**. | Parameter | Required | Description | | ----------- | -------- | --------------------------------------------------------------------------- | | space | true | Analysis scope (single site or multi-sites). | | columns | true | List of properties & metrics to query (separated by a comma). | | period | true | Analysis period (single, multiple, relative). | | filter | false | Filters to be applied on properties/metrics. | | evo | false | To obtain the evolution of a group of metrics over a certain time period. | | sort | true | List of properties / metrics according to which the results will be sorted. | | max-results | true | Number of results in the results page. | | page-num | true | Page number of the data set. | | options | false | Additional parameters | ## Parameter syntax | PARAMETER | SYNTAX | | ----------- | --------------------------------------------------------------------------------------------------- | | space | "space": { "s":\[123456789\] } | | columns | "columns": \[ "visit_device_type", "m_visits" \] | | period | "period": { "p1": \[ { "type": "D", "start": "2019-10-20", "end": "2019-10-24" } \] } | | filter | "filter": { "metric": { "m_visits": { "$eq": 19 } }, } | | evo | "evo": { "granularity": "D", "top": { "max-results": 5, "page-num": 1, "sort": \["-m_visits"\] } } | | sort-by | "sort": \[ "m_visits" \] | | max-results | "max-results": 50 | | page-num | "page-num": 1 | | options | "options": {"ignore_null_properties": true, "eco_mode": true} | ### JavaScript ```javascript var data = JSON.stringify({ "columns": [ "device_type", "m_visits", "m_users" ], "sort": [ "-m_visits" ], "space": { "s": [429023] }, "period": { "p1": [{ "type": "D", "start": "2019-10-24", "end": "2019-10-24" }] }, "max-results": 50, "page-num": 1 }); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); } }); xhr.open("POST", "https://api.atinternet.io/v3/data/getData"); xhr.setRequestHeader("x-api-key", "YOURAPIKEY"); xhr.send(data); ``` ### Shell ```shell curl -X POST \ https://api.atinternet.io/v3/data/getData \ -H 'x-api-key: YOURAPIKEY' \ -H 'Content-Type: application/json' \ -d '{ "columns": [ "device_type", "m_visits", "m_users" ], "sort": [ "-m_visits" ], "space": { "s": [429023] }, "period": { "p1": [ { "type": "D", "start": "2019-10-24", "end": "2019-10-24" } ] }, "max-results": 50, "page-num": 1 }' ``` ### Python ```python import http.client conn = http.client.HTTPSConnection("api.atinternet.io") payload = '''{ "columns": [ "device_type", "m_visits", "m_users" ], "sort": [ "-m_visits" ], "space": { "s": [429023] }, "period": { "p1": [ { "type": "D", "start": "2019-10-24", "end": "2019-10-24" } ] }, "max-results": 50, "page-num": 1 }''' headers = { 'x-api-key': "YOURAPIKEY", 'Content-type': "application/json" } conn.request("POST", "/v3/data/getData", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) ``` ### Ruby ```ruby request["x-api-key"] = 'YOURAPIKEY' request.body = <<~JSON { "columns": [ "device_type", "m_visits", "m_users" ], "sort": [ "-m_visits" ], "space": { "s": [429023] }, "period": { "p1": [ { "type": "D", "start": "2019-10-24", "end": "2019-10-24" } ] }, "max-results": 50, "page-num": 1 } JSON response = http.request(request) puts response.read_body ``` ## Output format This Reporting API v3 allows you to get a response either in `csv` or in `json`, the default format being `json`: - JSON output: `https://api.atinternet.io/v3/data/getData` or `https://api.atinternet.io/v3/data/json/getData` - CSV output: `https://api.atinternet.io/v3/data/csv/getData` ## POST or GET method? The Reporting API v3.0 is designed to be used with the POST method. As you may have noticed, the content of the API call is getting longer and longer as all the fields are well described, and the GET method can be limited because of th length of the http request. --- ## How it works ## Foreword Please read the [terms & conditions](/analytics/data-api/technical-information/terms-conditions/) before using this Reporting API. ## General information You can find the endpoint for our [Reporting API v3 on Data Query](https://analytics-docs.piano.io/en/analytics/v1/product-tour#Producttour-ReportingAPIv3). This Reporting API v3.0 is designed to query your analytics data. Here is important information about key parameters: - `columns`: you can get up to 50 different items (properties + metrics) in this parameter, - `max-results`: you can retrieve up to 10,000 rows per API call (200,000 rows maximum), - `page-num`: you can choose which page of results to retrieve. The maximum value for this parameter depends on `max-results` (200,000 rows maximum). - You can use up to 6 different segments in a request (including the segment used in metrics) If you need to download, export, share more than 200,000 rows, please get in touch with our Support Centre as there are many different ways to get this done efficiently. --- ## Breakdown ## Overview The breakdown parameter allows you to create sub-breakdowns of your data by additional dimensions. It enables you to drill down into specific segments of your main query results. ## Parameters | Parameter | Description | Values | Required | | ----------- | ---------------------------------------------------- | ------------------------------ | -------- | | columns | The columns you want to spread on with the breakdown | Array of property/metric names | Yes | | page-num | Page number for pagination of breakdown results | Integer (default: 1) | No | | max-results | Maximum number of results per breakdown | Integer | No | > note: > > Other parameters are forbidden in the breakdown object and will throw an error if present. ## Examples ### Example 1: Single breakdown column Breaking down countries by their cities. ```json { "columns": ["geo_country", "m_events", "m_visits"], "breakdown": { "columns": ["geo_city"], "page-num": 1, "max-results": 5 } } ``` ### Example 2: Multiple breakdown columns Breaking down countries by metro region and then by city. ```json { "columns": ["geo_country", "m_events", "m_visits"], "breakdown": { "columns": ["geo_metro", "geo_city"], "page-num": 1, "max-results": 5 } } ``` --- ## Evolution ## Overview The `evo` parameter describes the context of the evolution analysis, allowing you to track how your data changes over time with specific granularity and element selection. ## Parameters | Parameter | Description | Values | Required | | ----------- | -------------------------------------------------------------------------------- | -------------------------------------- | -------- | | granularity | Time granularity for the evolution | M (Month), W (Week), D (Day), H (Hour) | Yes | | top | Configuration for selecting top elements based on period, pagination and sorting | Object (see below) | Yes | ### Top Parameters | Parameter | Description | Values | Required | | ----------- | ----------------------------------- | --------------------- | -------- | | max-results | Maximum number of results to return | Integer | No | | page-num | Page number for pagination | Integer | No | | sort | Sort by metrics | Array of metric names | No | ## Examples ### Example 1: Monthly evolution with top elements ```json { "evo": { "granularity": "M", "top": { "max-results": 10, "page-num": 1, "sort": ["-m_visits"] } }, "space": { "s": [123456789] } } ``` ### Example 2: Daily evolution for multiple sites ```json { "evo": { "granularity": "D", "top": { "max-results": 20, "sort": ["-m_visits", "m_users"] } }, "space": { "s": [123456789, 1234567890] } } ``` --- ## Filter ## Overview The `filter` object allows you to filter your dataset on both properties and metrics using various comparison operators. Filters support logical operations and multiple values. ## Parameters ### Number Filters | Parameter | Description | Values | Required | | ---------- | --------------------------------- | ---------------- | -------- | | $eq | Equals to | Number | No | | $neq | Does not equal to | Number | No | | $in | Value is in array | Array of numbers | No | | $gt | Greater than | Number | No | | $gte | Greater or equal to | Number | No | | $lt | Less than | Number | No | | $lte | Less than or equal to | Number | No | | $na | NULL value | true or false | No | | $undefined | Undefined value | true or false | No | | $empty | Combination of $na and $undefined | true or false | No | ### String Filters | Parameter | Description | Values | Required | | ---------- | --------------------------------- | ---------------- | -------- | | $eq | Equals to | String | No | | $neq | Does not equal to | String | No | | $in | Value is in array | Array of strings | No | | $lk | Contains | String | No | | $nlk | Does not contain | String | No | | $start | Starts with | String | No | | $nstart | Does not start with | String | No | | $end | Ends with | String | No | | $nend | Does not end with | String | No | | $na | NULL value | true or false | No | | $undefined | Undefined value | true or false | No | | $empty | Combination of $na and $undefined | true or false | No | ### Date Filters | Parameter | Description | Values | Required | | --------- | --------------------- | ----------- | -------- | | $eq | Equals to | Date string | No | | $gt | Greater than | Date string | No | | $gte | Greater or equal to | Date string | No | | $lt | Less than | Date string | No | | $lte | Less than or equal to | Date string | No | ### Boolean Filters | Parameter | Description | Values | Required | | ---------- | --------------------------------- | ------------- | -------- | | $eq | Equals to | true or false | No | | $neq | Does not equal to | true or false | No | | $na | NULL value | true or false | No | | $undefined | Undefined value | true or false | No | | $empty | Combination of $na and $undefined | true or false | No | > note: > > For all filter types, you can filter on multiple values by using arrays. For example: `"$lk": ["A", "B", "C"]` creates an OR condition. ## Examples ### Example 1: Complex filter with logical operations Filter for visits equal to 19 AND device type is Tablet or Desktop AND source starts with "Referrer". ```json { "filter": { "metric": { "m_visits": { "$eq": 19 } }, "property": { "$AND": [ { "$OR": [{ "device_type": { "$in": ["Tablet", "Desktop"] } }] }, { "visit_src": { "$start": "Referrer" } } ] } } } ``` ### Example 2: Simple property filter Filter for desktop devices only. ```json { "filter": { "property": { "device_type": { "$eq": "Desktop" } } } } ``` --- ## Period ## Overview The `period` parameter defines the time context for analysis. It supports both absolute dates and relative periods, with multiple period comparisons possible (p1, p2, etc.). ## Parameters | Parameter | Description | Values | Required | | ----------- | ---------------------------------------- | --------------------------------------------------------------------------------------- | ---------------- | | type | Period type | D (Day), M (Month), Q (Quarter), Y (Year), H (Hour), R (Relative), AP (Adaptive Period) | Yes | | start | Start date (absolute periods only) | Date format: yyyy-mm-dd | Yes for absolute | | end | End date (absolute periods only) | Date format: yyyy-mm-dd | Yes for absolute | | granularity | Time granularity (relative periods only) | D, M, Q, Y, H | Yes for relative | | startOffset | Start offset (relative periods only) | Integer (negative for past) | Yes for relative | | endOffset | End offset (relative periods only) | Integer (negative for past) | Yes for relative | ## Time Zone Behavior - **Single site**: Relative periods use the site's time zone - **Multiple sites**: Relative periods use the most easterly time zone of requested sites Example: Site A (UTC-1) + Site B (UTC+2) → Uses UTC+2 time zone ## Period Types - **Absolute periods**: Fixed date ranges using start/end dates - **Relative periods (R)**: Dynamic periods relative to current date - **Adaptive periods (AP)**: Used in segments, adapt to the analysis date ## Examples ### Example 1: Absolute periods comparison Compare two specific date ranges. ```json { "period": { "p1": [ { "type": "D", "start": "2019-10-20", "end": "2019-10-24" } ], "p2": [ { "type": "D", "start": "2019-10-15", "end": "2019-10-19" } ] } } ``` ### Example 2: Relative period with segment Monthly analysis with adaptive segment period. ```json { "period": { "p1": [ { "type": "R", "granularity": "M", "startOffset": -1, "endOffset": -1 } ] }, "space": { "s": [123456789] }, "columns": ["visit_src", "m_visits"], "segment": { "section": { "mode": "include", "scope": "visitor_id", "period": { "p1": [ { "type": "AP", "granularity": "M", "startOffset": -1, "endOffset": -1 } ] }, "content": { "condition": { "filter": { "visit_geo_country": { "$eq": "France" } } } } } } } ``` --- ## Properties & metrics ## Overview The `columns` parameter defines which properties and metrics to include in your API response. You can reference available properties and metrics from your Data Model configuration. ## Parameters | Parameter | Description | Values | Required | | --------- | ------------------------------------------- | ---------------------------------------- | -------- | | columns | Array of properties and metrics to retrieve | Array of strings (property/metric names) | Yes | ## Column Format - **Properties**: Use the property key directly (e.g., `"device_type"`) - **Metrics**: Use the metric key directly (e.g., `"m_visits"`) - **Period-specific metrics**: Prefix with period identifier (e.g., `"p1.m_visits"`) ## Data Model Reference To find available properties and metrics, visit your [Data Model](https://analytics.piano.io/datamanagement/#/data-model/properties/list/) and look for the property key. ## Examples ### Example 1: Single period query Basic request with device type property and visits metric. ```json { "columns": ["device_type", "m_visits"] } ``` ### Example 2: Multiple periods comparison Compare visits across different periods. ```json { "columns": ["device_type", "p1.m_visits", "p2.m_visits"] } ``` ### Example 3: Multiple properties and metrics Comprehensive analysis with geography, device, and various metrics. ```json { "columns": [ "geo_country", "device_type", "m_visits", "m_users", "m_bounce_rate" ] } ``` --- ## Segment ## Overview The `segment` parameter allows you to define behavioral segments for your analysis. Segments can filter your data based on specific user behaviors and characteristics across different scopes. ## Parameters ### Main Parameters | Parameter | Description | Values | Required | | ---------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------ | ---------------------- | | scope | Defines the segmentation type | visit_id, user_id, visitor_id, event_id, av_session_id, cart_id, pageview_id | Yes | | segmentKey | Reference to a saved segment | String | No | | content | Segment definition (see below) | Object | Yes (if no segmentKey) | | mode | Include or exclude the behavior | include, exclude | Yes | | period | Time period for the behavior (visitor/user segments) | [See Period documentation](/analytics/data-api/parameters/period/) | No | | space | Sites where behavior occurred (visitor/user segments) | [See Sites documentation](/analytics/data-api/parameters/sites/) | No | ### Content Parameters | Parameter | Description | Values | Required | | --------- | ----------------------------------- | ------------------------------------------------------------------ | -------- | | condition | Contains the filter for the segment | Object | Yes | | filter | Describes the behavior to track | [See Filter documentation](/analytics/data-api/parameters/filter/) | Yes | ## Scope Types Find detailed information about different segmentation scopes in the [help center](https://analytics-docs.piano.io/en/analytics/v1/new-segmentation-engine#Newsegmentationengine-Thedifferentscopesofthesegmentation). ## Examples ### Example 1: Simple device type segment Segment visitors using desktop devices. ```json { "segment": { "section": { "scope": "visit_id", "content": { "condition": { "filter": { "device_type": { "$eq": "Desktop" } } } }, "mode": "include" } } } ``` ### Example 2: Visitor segment with time period Segment visitors from France in the previous month. ```json { "segment": { "section": { "scope": "visitor_id", "mode": "include", "period": { "p1": [ { "type": "R", "granularity": "M", "startOffset": -1, "endOffset": -1 } ] }, "content": { "condition": { "filter": { "visit_geo_country": { "$eq": "France" } } } } } } } ``` ### Example 3: Using saved segment Reference a previously saved segment. ```json { "segment": { "section": { "segmentKey": "mobile_users_france", "mode": "include" } } } ``` --- ## Sites ## Overview The `space` parameter defines the scope of sites you want to query in your analysis. You can query data from single or multiple sites simultaneously. ## Parameters | Parameter | Description | Values | Required | | --------- | ----------------------------------------- | ----------------- | -------- | | s | Array of site IDs to include in the query | Array of integers | Yes | ## Usage Notes - Site IDs are numerical identifiers unique to each site in your Piano Analytics account - You can query multiple sites in a single request for comparative analysis - When using multiple sites with relative periods, timezone handling follows the most easterly timezone ## Examples ### Example 1: Single site query Query data from one specific site. ```json { "space": { "s": [123456789] } } ``` ### Example 2: Multiple sites query Query data from multiple sites for comparison. ```json { "space": { "s": [123456789, 1234567890] } } ``` ### Example 3: Multi-site analysis with breakdown Analyze multiple sites with device type breakdown. ```json { "space": { "s": [123456789, 1234567890, 9876543210] }, "columns": ["site_id", "device_type", "m_visits"], "breakdown": { "columns": ["geo_country"], "max-results": 10 } } ``` --- ## Sort by ## Overview The `sort` parameter controls the ordering of your query results. You can sort by any column (metrics or properties) included in your `columns` parameter. ## Parameters | Parameter | Description | Values | Required | | --------- | -------------------------------- | ------------------------------------------ | -------- | | sort | Array of column names to sort by | Array of strings (with optional \- prefix) | No | ## Sorting Rules - **Ascending order**: Use column name directly (e.g., `"device_type"`) - **Descending order**: Prefix column name with `-` (e.g., `"-m_visits"`) - **Multiple sorts**: Order matters - first item has highest priority - **Column requirement**: Can only sort on columns present in the `columns` parameter ## Examples ### Example 1: Simple ascending sort Sort results by device type in ascending order. ```json { "columns": ["device_type", "m_visits"], "sort": ["device_type"] } ``` ### Example 2: Descending sort by metric Sort results by visits in descending order (highest first). ```json { "columns": ["device_type", "m_visits"], "sort": ["-m_visits"] } ``` ### Example 3: Multiple column sorting Sort by country (descending), then device type (ascending), then visits (descending), then users (ascending). ```json { "columns": ["geo_country", "device_type", "m_visits", "m_users"], "sort": [ "-geo_country", "device_type", "-m_visits", "m_users" ] } ``` --- ## API Methods ## `getData` If you need to return the data of a query, you can use the `getData` method as described below. `https://api.atinternet.io/v3/data/getData?param={"columns":["visit_device_type","m_visits"],"sort":["-m_visits"],"space":{"s":[123456789]},"period":{"p1":[{"type":"D","start":"2019-10-24","end":"2019-10-24"}]},"max-results":50,"page-num":1}` ## `getRowCount` If you need to get the number of results of a query, you can use the `getRowCount` method as described below. `https://api.atinternet.io/v3/data/getRowCount?param={"columns":["visit_device_type","m_visits"],"space":{"s":[123456789]},"period":{"p1":[{"type":"D","start":"2019-10-24","end":"2019-10-24"}]}}` Here are the mandatory query parameters: - columns - space - period ## `getTotal` If you need to get the total for each metric, you can use the `getTotal` method as described below. `https://api.atinternet.io/v3/data/getTotal?param={"columns":["visit_device_type","m_visits"],"space":{"s":[123456789]},"period":{"p1":[{"type":"D","start":"2019-10-24","end":"2019-10-24"}]}}` Here are the mandatory query parameters: - columns - space - period --- ## Error codes | API Code | Status Code | Error Message | | ---------------------------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | QuotasExceeded_TooManyRequests | 509 | You have exceeded the number of simultaneous calls allowed. Please wait a moment and try again. | | InvalidJSON | 400 | Syntax error in url json | | InvalidRequestIdForExtract | 400 | The provided request ID is not compatible for Identified Visitors extraction. | | UnknownError | 500 | Unknown error | | InvalidSort_ForbiddenSort | 400 | Sort parameter is not permitted | | BadAuthentication_NoHeader | 401 | Incorrect login or password | | InvalidSort_InvalidArray | 400 | Sort is not an array of string | | UnauthorizedSite | 403 | You are not authorised to access this site. | | InvalidSort_HiddenSort | 400 | Sort column must be part of the columns parameter | | InvalidSort_MissingSort | 400 | Sort should be set | | InvalidSort_SortNotAllowed | 400 | Sort is only available in data mode | | BadAuthentication_InvalidAuthType | 401 | Incorrect login or password | | InvalidIncomingContent_UnknownParam | 400 | The URL contains an unknown parameter. | | InvalidSort_OnlyOneSort | 400 | Sort is forbidden on more than 1 element | | InvalidSort_UnknownColumn | 400 | Sort column column doesn’t exist | | InvalidColumns_IncoherentColumns | 400 | Columns does not belong to this analysis. | | InvalidColumns_InvalidMultiPeriodMetric | 400 | Param columns column isn’t allowed in multi period | | InvalidColumns_MoreThanOneTable | 400 | Columns must belong to one and only one table | | InvalidColumns_InvalidArray | 400 | The column is not an array | | InvalidColumns_NoDimension | 400 | No property are allowed on this analysis | | InvalidColumns_OnlyOneDimension | 400 | Only one selected property allowed | | InvalidColumns_UnknownColumns | 400 | Param columns column unknown | | InvalidColumns_TooManyColumns | 400 | The number of columns must be between 0 and 50 | | InvalidEvolution_DisallowedRootMaxResults | 400 | max-results is only allowed in the top object | | InvalidEvolution_BadGranularity | 400 | The evo granularity is not valid | | InvalidEvolution_DisallowedComparisonPeriod | 400 | Comparison periods can’t be used in an evo request | | InvalidEvolution_DisallowedRootFilter | 400 | Filter is only allowed in the top object | | InvalidEvolution_DisallowedRootPageNum | 400 | page-num is only allowed in the top object | | InvalidEvolution_EmptyEvo | 400 | The evo object is empty | | InvalidEvolution_MissingGranularity | 400 | The evo granularity hasn’t been specified | | InvalidEvolution_DisallowedRootSort | 400 | sort is only allowed in the top object | | EvoNotAvailable | 400 | Evolution not available for this mode | | InvalidEvolution_MissingTop | 400 | The evo top parameter hasn’t been specified | | InvalidEvolution_TopMissingSort | 400 | The evo top sort parameter hasn’t been specified | | InvalidEvolution_HourMoreThanTwoMonths | 400 | The evo hour period lasts for more than two months | | InvalidEvolution_TopMissingMaxResults | 400 | The evo top max-results parameter hasn’t been specified | | InvalidEvolution_TopMissingPageNum | 400 | The evo top page-num parameter hasn’t been specified | | InvalidIncomingContent_OpOnMetric | 400 | The provided op cannot be used on a metric | | InvalidEvolution_MultiPeriod | 400 | The evo is not available for this API call | | InvalidIncomingContent_CalculatedColumnOnProperty | 400 | The calculatedColumn specifies properties | | InvalidIncomingContent_ValuesQuantityDiffers | 400 | The operator operator only allows quantity values | | InvalidIncomingContent_OpOnWrongType | 400 | The operator operator can only be used on the following types: types | | InvalidIncomingContent_CalculatedColumnInvalidMetricFormat | 400 | The calculatedColumn’s metrics must be an array | | InvalidIncomingContent_CalculatedColumnWithoutOp | 400 | One of the calculatedColumns does not specify any op | | InvalidIncomingContent_CsvNotAvailable | 400 | Csv format not available with shortcode shortCode | | InvalidIncomingContent_CalculatedColumnWithoutMetric | 400 | The calculatedColumn does not specify any metrics | | InvalidMaxResults_ForbiddenPagination | 400 | MaxResult and Pagenum parameters are not permitted | | InvalidIncomingContent_VarWithoutMetrics | 400 | One of the var’s values is not a metric | | InvalidIncomingContent_CalculatedColumnWithoutKey | 400 | One of the calculatedColumns does not specify any key | | InvalidIncomingContent_UrlFormat | 400 | Invalid format in URL | | InvalidIncomingContent_CalculatedColumnInvalidFormat | 400 | One of the calculatedColumns is not an object | | InvalidIncomingContent_CalculatedColumnInvalidValuesType | 400 | One of the calculatedColumn’s metrics does not specify any “values” array | | InvalidIncomingContent_DifWithoutMetrics | 400 | One of the dif’s values is not a metric | | InvalidMaxResults_MaxResultInt | 400 | max-results is not an integer | | InvalidSegment_EmptyOrAnd | 400 | Invalid OR/AND filter | | InvalidSegment_CrossTable | 400 | The Segment uses properties from different tables | | InvalidSegment_InvalidGranularity | 400 | The period type of segment description must be D | | InvalidSegment_InvalidPeriodArray | 400 | The period value of segment description must be an Array | | InvalidSegment_EmptySegment | 400 | The segment object must contain a filter or a period object | | InvalidSegment_InvalidBool | 400 | Filter value must be a boolean | | InvalidSegment_OnlyOnePeriod | 400 | The period object of the segment description must contain 1 period | | InvalidSegmentDesc_EndBeforeStart | 400 | The end date cannot be lower than the start date | | InvalidSegment_UnknownColumn | 400 | Unknown segment column: column | | InvalidSegmentDesc_MissingDate | 400 | The period must contain a Start date and an End date | | InvalidSegment_CrossTableWithoutVisits | 400 | The Segment uses properties from different tables but visits was not found | | InvalidSegment_EmptyFilterArray | 400 | The filter object of the segment description must contain at least 1 filter | | InvalidMaxResults_Over2000 | 400 | max-results must be at most 2000 | | InvalidSpace_EmptySpace | 400 | No space specified | | InvalidGsharpPeriod_MalformedPeriod | 400 | The “period” parameter contains a syntax error. | | InvalidPeriod_InvalidArray | 400 | The period is not an array | | InvalidPeriod_InvalidPeriodArray | 400 | The period value must be an Array | | InvalidSegment_InvalidExtractNotEqualFilter | 400 | The filter $neq must be the latest filter’s segment of the extract | | InvalidSegmentDesc_InvalidSegmentPart | 400 | The segment contains unrecognized member | | InvalidSegment_InvalidOr | 400 | Cannot do an OR filter on different properties | | InvalidSegment_NoMetric | 400 | Segmentation on metrics is forbidden | | InvalidSegment_UnknownOperator | 400 | The segment’s operator operator is unknown | | InvalidSegmentDesc_InvalidPeriodsNumber | 400 | The number of periods in segment and main demand should be the same | | InvalidSegmentV3_NoSegmentId | 400 | SegmentId not found | | InvalidMaxResults_MaxResultValue | 400 | max-results must be 5, 10, 20, 50, 100 or 200 | | InvalidMaxResults_Over10000 | 400 | max-results must be at most 10000 | | InvalidPeriod_EmptyPeriod | 400 | No period specified | | InvalidPeriod_MalformedDate | 400 | One of the dates is malformed | | InvalidPeriod_MalformedPeriod | 400 | The period is malformed | | InvalidPeriod_MalformedRelativePeriod | 400 | The relative period is malformed | | InvalidMaxResults_NegativeMaxResult | 400 | max-results must be greater than 0 | | InvalidPeriod_InvalidRelativePeriodUnit | 400 | The relative period unit must be D, W, M, Q or Y | | InvalidSegment_MalformedDate | 400 | One of the dates in the period of segment description is malformed | | InvalidSegment_InvalidFilterArray | 400 | The filter of segment description is not an array | | InvalidSegment_InvalidPeriodsNumber | 400 | The number of periods in segment and main demand should be the same | | InvalidSegment_NoSegment | 400 | The segment description is undefined | | InvalidSegment_StartEndOnly | 400 | The period of segment description must contain only a Start date or an End date | | InvalidSegmentV3_NotEligibleToV3Api | 400 | Segment is not eligible to v3 api | | InvalidMaxResults_MissingPagination | 400 | MaxResult and Pagenum should be set | | InvalidPeriod_StartEndOnly | 400 | The period must contain only a Start date or an End date | | InvalidSegment_InvalidInt | 400 | Filter value must be an integer | | InvalidSegmentDesc_WrongArchitecture | 400 | The first parameter cannot contain second parameter | | InvalidSegmentV3_TooManyKeys | 400 | Segment parameter should contains only one key | | InvalidMaxResults_PageNumBelowZero | 400 | page-num must be greater than 0 | | InvalidMaxResults_PageNumInt | 400 | page-num is not an integer | | InvalidPeriod_MissingDate | 400 | The period must contain a Start date and an End date | | InvalidSegment_InvalidColumn | 400 | The property property is unavailable for segmentation | | InvalidSegment_OnlyOneStartEnd | 400 | The period of segment description must contain only one Start date and one End date | | InvalidSegmentDesc_InvalidArray | 400 | The period of segment description is not an array | | InvalidSegment_InvalidAnd | 400 | AND operator must contain an Array | | InvalidSegment_InvalidToManyNotEqualFilter | 400 | Only one $neq filter is allowed on the extract | | InvalidSegment_PeriodTooLarge | 400 | The Segment period cannot be greater than 31 days | | InvalidSegmentDesc_MalformedPeriod | 400 | The period is malformed | | InvalidPeriod_EndBeforeStart | 400 | The end date cannot be lower than the start date | | InvalidPeriod_InvalidRelativePeriodOffset | 400 | The relative period offset must be an integer | | InvalidPeriod_MissingStartDate | 400 | The period must at least contain a Start date | | InvalidSegmentDesc_InvalidScope | 400 | Given scope is not authorized | | InvalidSpace_InvalidArray | 400 | The space is not an array | | InvalidSpace_InvalidInt | 400 | One of the sites is not an integer | | InvalidSpace_InvalidString | 400 | l2name is not a string | | InvalidSpace_L2InvalidInt | 400 | Site is not an integer | | InvalidSpace_TooManySpace | 400 | The number of sites must be between 1 and 100 | | DataFeedQueryFilter_UnknownColumn | 400 | Unknown column filter : column | | InvalidSpaceForRequestId_TooManySites | 400 | The number of sites exceed the limit for this analysis. | | DataFeedQueryFilter_FilterableFalse | 400 | Cannot apply filter on column. Filterable is set to false | | InvalidPeriod_MultiPeriodNotAvailable | 400 | Multi-period mode and evolution mode are not available for this API call | | InvalidSpace_l2TooManySpace | 400 | Only one site can be specified with l2name | | InvalidPeriodForRequestId_InvalidPeriod | 400 | The requested period is too large for this analysis. | | DataFeedQueryFilter_InvalidValueForBoolean | 400 | Invalid value (value) for Boolean filter | | DataFeedQueryFilter_InvalidNullValue | 400 | null value can only be applied on uid columns and with equality operators | | DataFeedQueryFilter_FilterNotInConfiguration | 400 | A step filter does not belongs to the configuration | | DataFeedQueryFilter_EmptyOnNonBoolean | 400 | Empty filter contains invalid value: value | | DataFeedQueryFilter_InvalidDate | 400 | Filter value on column is not a valid timestamp. The expected format is YYYY-MM-DD | | DataFeedQueryFilter_InvalidValueForType | 400 | Filter value for column must be a type | | DataFeedQueryFilter_OutOfBoundNumber | 400 | Value range is -2147483648 to +2147483647 | | DataFeedQueryFilter_UnknownOperator | 400 | One of the operators is not correct: operator | | DataFeedQueryFilter_ClassicFilterOnFirstStep | 400 | Forbidden classic filter on a first step | | DataFeedQueryFilter_ArrayFilter | 400 | Filter value must not be an array | | DataFeedQueryFilter_InvalidOperatorForBoolean | 400 | Invalid operator (operator) for Boolean filter | | DataFeedQueryFilter_MissingFilterOnAStep | 400 | Missing filter on a step | | DataFeedQueryFilter_ClassicFilterWithoutUidOnPrevious | 400 | Forbidden classic filter without specifying its uid counterpart on the previous step | | DataFeedQueryFilter_InvalidOperatorForType | 400 | Wrong operator operator for type attribute type | | Internal_InvalidErrorCodeContract_InvalidStatusCode | 422 | Invalid statusCode | | InvalidLanguage_Empty | 400 | Language was not provided | | DataFeedQueryFilter_EmptyFiltersOnFunnel | 400 | Empty filter for funnel vision | | DataFeedQueryFilter_ClassicFilterOnMultipleStep | 400 | Forbidden classic filter on multiple steps | | Internal_InvalidErrorCodeContract_InvalidApiCode | 422 | Invalid apiCode | | Internal_InvalidContract | 400 | Invalid contract (key: value) | | InvalidLanguage_Unknown | 400 | The “lng” parameter has been entered incorrectly. Expected values: allowedValues | | Internal_InvalidErrorCodeContract_MismatchErrorCode | 422 | errorCode should be errorCode for errorName errorName | | Internal_ElementAlreadyExists_ErrorCode | 400 | Element already exist (keys: values) | | Internal_InvalidErrorCodeContract_MalformedKey | 422 | Malformed key key. Allowed characters are \[a-z0-9_-\] | | Internal_InvalidErrorCodeContract_InvalidDescription | 422 | Descriptions should have the same custom parameters | | Internal_InvalidErrorCodeContract_MismatchErrorName | 422 | errorName should be errorName for errorCode errorCode | | BadRetention_Empty | 400 | The object of retention is empty | | Internal_InvalidErrorCodeContract_apiCodeSWErrorName | 422 | apiCode should start with errorName | | BadRetention_MaxProperties | 400 | The object of retention must contains 2, 3 or 4 properties | | BadRetention_InvalidReferenceDateFormat | 400 | The retention reference date format must be YYY-MM-DD | | BadRetention_EmptyPeriod | 400 | The period of retention is empty | | BadRetention_EmptyGranularity | 400 | The granularity of retention is empty | | BadRetention_TooMuchOnMonth | 400 | The retention period must not exceed 6 months | | BadRetention_InvalidGranularity | 400 | The granularity of retention is not valid | | BadRetention_InvalidRetentionType | 400 | The retention type (v) should be “ratio” or “value” | | InvalidSampling_OnSegment | 400 | Sampling parameter can not be used with segments | | BadRetention_TooMuchOnDay | 400 | The retention period must not exceed 14 days | | InvalidSampling_OnSQA | 400 | Sampling parameter can not be used with SQA requestid | | ElementAlreadyExists_Metric | 409 | The provided metric (keys) already exists (values) | | UnknownColumns_Property | 400 | Unknown property: key | | BadRetention_TooMuchOnWeek | 400 | The retention period must not exceed 14 weeks | | ResourceNotFound_Organization | 404 | Organization organization does not exist | | ElementAlreadyExists_Property | 409 | The provided property (keys) already exists (values) | | InvalidFilter_TooManyElements | 400 | Filter sent too many results | | BadRetention_InvalidPeriodType | 400 | The period of retention is not an integer | | InvalidSampling_InvalidValue | 400 | The sampling parameter has been entered incorrectly. Expected values between 0 and 100 | | CancelledRequest | 400 | Request aborted. | | DataAvailableAfter20170101 | 400 | The requested data is not available from before January 1, 2017\. Please adjust the date of your request. | | DataNotReady | 400 | The data is not yet available. It is either currently being processed, or relates to a period too far in the past. | | API_REST_1026_V2 | 403 | You are not authorised to access this application. | | UnknownColumns_CalculatedColumn | 400 | Unknown calculated column: key | | UnknownColumns_Metric | 400 | Unknown metric: key | | SegmentNotFound | 400 | The requested segment does not exist, or it was closed. | | InvalidSpace_L2Forbidden | 400 | The space cannot contain any second level site | | InvalidIncomingContent_SegmentInvalidThenType | 400 | Then object should be an array | | InvalidIncomingContent_SegmentInvalidThenKey | 400 | Unknown then parameter identifier: key | | InvalidIncomingContent_SegmentInvalidContentKey | 400 | Unknown segment section parameter identifier: key | | InvalidIncomingContent_SegmentInvalidOrKey | 400 | Unknown or parameter identifier: key | | InvalidIncomingContent_SegmentInvalidConditionFilter | 400 | Missing condition’s filter definition | | InvalidIncomingContent_SegmentInvalidThenMember | 400 | Invalid then object construction, should have only one member | | InvalidIncomingContent_SegmentInvalidThen | 400 | Then object should contain at least 2 elements | | InvalidIncomingContent_SegmentSectionNoPeriod | 400 | No period in section object | | InvalidIncomingContent_CalculatedColumnFormulaMalformed | 400 | CalculatedColumn formula malformed | | InvalidIncomingContent_SegmentInvalidConditionFilterType | 400 | Filter object in condition block should be an object | | InvalidIncomingContent_SegmentInvalidCondition | 400 | Condition object is undefined | | InvalidIncomingContent_CalculatedColumnComposedMetricMalformed | 400 | CalculatedColumn composedMetric malformed | | InvalidIncomingContent_CalculatedColumnUnknownOperator | 400 | Unknown calculatedColumn operator: operator | | InvalidIncomingContent_SegmentInvalidOrMember | 400 | Invalid or object construction, should have only one member | | InvalidIncomingContent_SegmentSectionNoScope | 400 | No scope defined in segment object | | InvalidIncomingContent_EmptyBody | 400 | Filter value must be an integer | | InvalidIncomingContent_SegmentInvalidOrType | 400 | Or object should be an array | | InvalidIncomingContent_SegmentInvalidAndMember | 400 | Invalid and object construction, should have only one member | | InvalidIncomingContent_SegmentInvalidAndKey | 400 | Unknown and parameter identifier: key | | InvalidIncomingContent_SegmentInvalidContentMember | 400 | Invalid segment section content construction, should have only one member | | InvalidIncomingContent_SegmentInvalidAndType | 400 | And object should be an array | | InvalidIncomingContent_SegmentSectionContentMalformed | 400 | Content in section should be an object | | InvalidIncomingContent_CalculatedColumnUnknownMetric | 400 | Unknown calculatedColumns metric: key | | InvalidFilter_WrongParameter | 400 | Only metric or property is allowed in a filter | | InvalidIncomingContent_CalculatedColumnMetricMalformed | 400 | CalculatedColumn metric malformed | | InvalidSpace_InvalidL2sString | 400 | The level 2 name must be a string | | InvalidFilter_WrongPropertyFilter | 400 | Cannot filter on anything else than a property in property object | | InvalidProject_DuplicateKey | 400 | Unable to save project ‘label’ because the label already exists. | | InvalidSegmentSpace_EmptySpace | 400 | No space specified in segment | | InvalidSpace_MissingSite | 400 | The space doesn’t contain any site | | AbortedRequest | 204 | Request canceled by user. | | InvalidProject_ProjectNotFound | 400 | Unable to load project ‘id’ because it does not exist or cannot be modified. | | InvalidOptions_InvalidIgnoreNullWithRequestId | 400 | The parameter “ignore_null_properties” is incompatible with the “requestdid” parameter. | | InvalidIncomingContent_DivisionWrongValuesQuantity | 400 | A custom metric using a division must be based on two metrics | | InvalidSegmentDesc_InvalidFilter | 400 | Given scope is not authorized | | InvalidIncomingContent_MissingFilteringParameter | 400 | The param parameter is mandatory | | InvalidSegmentSpace_InvalidInt | 400 | One of the segment sites is not an integer | | InvalidOptions_InvalidEcoModeType | 400 | The parameter ‘eco_mode’ should be a boolean | | demo_test_today | 400 | updateTESTEN | | InvalidParameter_DataSourceNullOrBadValue | 400 | The parameter data-source cannot be undefined and must be have NDF or CDF value | | InvalidSpace_InvalidL2sArray | 400 | The level 2 name cannot an array | | InvalidIncomingContent_UnmatchedFilteringParameter | 400 | The param parameter has the wrong value. Allowed values: (values) | | InvalidSegmentV3_UnknownDefinitionType | 400 | Unknown segment definitionType: definitionType | | InvalidOptions_JsonFormat | 400 | The “options” parameter cannot be used in json mode | | InvalidSegmentSpace_InvalidString | 400 | l2name in segment is not a string | | InvalidOptions_SameDelimiters | 400 | The “csvDelimiter” and “decimalSeparator” parameter are identical | | InvalidProject_DeletedProject | 400 | Unable to load project ‘label’ because it have been deleted. | | InvalidFilter_MalformedFilter | 400 | Filter is malformed | | DataFeedQueryFilter_MissingUidFilterOnAStep | 400 | An uid filter object is missing on a step | | InvalidOptions_InvalidDecimalSeparator | 400 | The “decimalSeparator” parameter is invalid. It must be defined as “,” or “.”. | | InvalidSegmentSpace_InvalidArray | 400 | The segment space is not an array | | Internal_InvalidMetricContract_hidden | 422 | You can’t modify the hidden parameter with another parameter | | InvalidSort_EmptyArray | 400 | The sort parameter cannot be an empty array | | InvalidSegmentSpace_TooManySpace | 400 | The number of segment sites must be between 1 and 100 | | InvalidWarehouseConfig_DuplicateKey | 400 | Warehouse type,size config already exists | | InvalidSpace_L2NameEmptyString | 400 | The level 2 name cannot be an empty string | | InvalidSpace_L2NameUndefined | 400 | The level 2 name must be defined | | InvalidSegment_DuplicateKey | 400 | Unable to save segment segmentKey because the segmentKey already exists. | | InvalidOptions_InvalidIgnoreNullType | 400 | The parameter “ignore_null_properties” should be a boolean | | InvalidMaxResults_MaxRowsLimit | 400 | You’ve reached the limit of maxRowsLimit rows for this query. | | InvalidIncomingContent_ArithmeticColumnWrongMinimumValuesQuantity | 400 | A custom metric using an addition, substraction, multiplication must be based on a minimum of two metrics | | InvalidCombination_SegmentAndSaam | 400 | You are not able to apply a segment on a dataset which contains a segmented metric | | mon_test_TEST_API_CODE | 400 | Update This is a test. This is the language: language | | InvalidIncomingContent_OldCalculatedColumnWithoutLabel | 400 | (Old Format) One of the calculated columns’ metric does not specify any label | | demoErrorApi | 400 | update Api error | | InvalidColumns_TooManySaams | 400 | A data set contains a maximum of 5 segmented metrics | | InvalidSegment_UnknownParameter | 400 | Unknown segment parameter: parameter | | UnknownMetrics | 400 | Unknown metrics: keys | | InvalidColumns_EmptyColumns | 400 | No columns specified | | UnknownProperties | 400 | Unknown properties: keys | | InvalidDataSet_DuplicateKey | 400 | Unable to save dataset ‘label’ because the label already exists. | | InvalidSegmentSpace_l2TooManySpace | 400 | Only one segment site can be specified with l2name | | InvalidSegmentKey_MalformatedSegmentKey | 400 | Unable to save segment because the segmentKey is malformated | | InvalidOptions_InvalidIgnoreNullWithTotalMode | 400 | The parameter “ignore_null_properties” is not available with the Total. | | InvalidSegment_InvalidSectionParameter | 400 | The parameter ‘parameter’ is not allowed for segments with ‘scope’ scope. | | InvalidSpace_NoActiveSite | 400 | One of the selected sites didn’t exist on the selected period. Please change the list of sites or the period. | | InvalidMetric_MalformatedInputeContract | 400 | Unable to save metric because the input contract is wrong | | InvalidRequestId_OnGetQuery | 400 | The provided request ID is not compatible with ‘getQuery’ mode. | | InvalidIncomingContent_DuplicatedCalculatedColumnKeys | 400 | A calculated metric key can be only used once in an API call. | | InvalidIncomingContent_InvalidFilterType | 400 | The filter’s type should be an object | | InvalidIncomingContent_CalculatedColumnInvalidSegmentedMetricsFormat | 400 | The calculatedColumn’s segmentedMetrics must be an array | | InvalidCalculatedColumn_MisusedLastImportedOperator | 400 | LAST_IMPORTED_VALUE operator can only be used on a retroactive property | | InvalidIncomingContent_LastImportedValueWrongValues | 400 | A custom property using a last imported value operator must be based on property | | InvalidIncomingContent_CalculatedColumnForbiddenOperator | 400 | One of the calculatedColumn’s metrics have an invalid operator | | InvalidMetric_ForbiddenDelete | 400 | The metric you tried to delete does not exist or you don’t have the permission to perform this operation | | InvalidMetric_LiveSegmentedMetricKeyMalformed | 400 | Segmented calculated metric key malformed (should start with ‘*sm*’). | | InvalidSegment_InvalidMode | 400 | In the “mode” parameter of the segment, the value include or exclude is needed. | | InvalidSegment_MissingFilter | 400 | Segments with scope ‘scope’ must contain at least one filter. | | InvalidSampling_OnGetQuery | 400 | Sampling parameter can not be used in ‘getQuery’ mode | | InvalidSegment_ForbiddenUpdate | 403 | You can’t update this segment | | ResourceNotFound_Metric | 404 | Metric metric does not exist | | InvalidIncomingContent_CalculatedColumnWithoutValidKey | 400 | The calculatedColumn does not specify any metrics or properties | | InvalidSegment_UnauthorizedMode | 400 | The exclusion mode is not authorized for segments with ‘scope’ scope. | | InvalidSegment_ForbiddenDelete | 403 | The segment you tried to delete does not exist or you don’t have the permission to perform this operation | | InvalidSegment_InvalidSectionOperator | 400 | AND, OR, THEN section operators are not allowed for segments with ‘scope’ scope. | | InvalidMetric_CustomMetricSegmented | 400 | A segmented metric cannot be saved if one of its elements contains a segment. | | InvalidIncomingContent_CalculatedColumnInvalidPropertiesFormat | 400 | The calculatedColumn’s properties must be an array | | InvalidIncomingContent_LastImportedValueWrongValuesQuantity | 400 | A custom property using a last imported value operator must be based on one property | | InvalidMetric_LiveMetricKeyMalformed | 400 | Calculated metric key malformed (should start with ‘*m*’). | | InvalidSegment_UnauthorizedMetricScope | 400 | The ‘scope’ scope is not authorized for segments with category ‘metric’. | | InvalidMetric_ForbiddenUpdate | 403 | You can’t update this metric | | InvalidIncomingContent_InvalidOffsetParameters | 400 | startOffset or endOffset must be integer | | InvalidCalculatedColumn_InvalidLastImportedProperty | 400 | A custom property using a last imported value operator must be based on one property | | InvalidIncomingContent_InvalidStartOffset | 400 | startOffset must be lower or equal to endOffset | | InvalidIncomingContent_CalculatedColumnPropertyInvalidKey | 400 | Calculated properties keys should not start with “*m*” | | InvalidMetric_ForbiddenGet | 400 | You do not have the required rights to get the definition of the metric. | | InvalidMetric_ForbiddenTranslate | 400 | You can use the function GetMetrics only for the metrics you create and not for the ATI Standard metrics. | | InvalidIncomingContent_CalculatedColumnPropertyInvalidValue | 400 | One of the calculated properties does not specify any “value” | | InvalidIncomingContent_InvalidOffset | 400 | startOffset/endOffset must be a negative number | | InvalidRessource_InvalidVisibility | 400 | The Ressource visibility was incorrect | | InvalidIncomingContent_InvalidSegmentCategory | 400 | The segment’s category value should be ‘metric’ or ‘property’ | | InvalidSegment_IncompatibleWithNavigation | 400 | Events segments are incompatible with Navigation analyses | | InvalidMetric_MetricKeyInValues | 400 | We can’t use the same metric | | InvalidIncomingContent_InvalidMixedData | 400 | we can’t mix real time data with past data | | InvalidSegment_UnauthorizedSegmentOnLiveMetric | 400 | Creating a segment based on a non-saved metric is not authorized | | InvalidSegment_InvalidMetricSectionOperator | 400 | AND, OR, THEN section operators are not allowed for segments with metric category. | | InvalidIncomingContent_InvalidCalculatedColumnMetric | 400 | CalculatedColum is not defined | | InvalidSegment_UnauthorizedSegmentOnSegmentedMetric | 400 | Using a segmented element into a segment definition is not authorized. (element) | | ImportUpdateFailed_InvalidUpdatedElementsNumber | 400 | updatedElements updated elements should be expectedElements | | InvalidSegment_WithRelativePeriodAP | 400 | The visit segmentation is not compatible with cohort based on relative period compared to the analysis period. | | InvalidMetric_InvalidMetricKey | 400 | MetricKey is not defined | | InvalidIncomingContent_InvalidConstant | 400 | Value or type of constant is invalid | | InvalidMetric_InvalidInputContract | 400 | One of the parameters of the contract is invalid | | InvalidMetric_InvalidVisibilityOrUser | 400 | The visibility or creator is undefined | | InvalidIncomingContent_DistinctTouchpoint | 400 | The parameter disctinctTouchpoint should be defined and value must be 0 or 1 | | InvalidIncomingContent_NoColumnSpecified | 400 | Request need to specify at least one metric in columns parameter. | | InvalidIncomingContent_InvalidConstantValue | 400 | the value can’t be négative | | InvalidIncomingContent_CalculatedColumnInvalidConstantsFormat | 400 | The calculatedColumn’s constants must be an array | | InvalidSegment_AllVisitsSequenced | 400 | ‘All Visits’ coverage is incompatible with sequenced segmentation. | | InvalidSegment_IncompatibleModeWithSQA | 400 | The exclusion type segment is not compatible with this analysis | | InvalidMetric_MalformatedInputContract | 400 | Unable to save metric because the input contract is wrong | | InvalidFunnel_UnknownDefinitionType | 400 | Unknown definitionType value: definitionType | | InvalidSegment_InvalidMultiperiod | 400 | Multiperiod is not allowed for saved segments. | | NoDataAccessBecauseUnpayment | 403 | Following a number of unpaid invoices, our accounts department has suspended access to your data and requests that you send us your email address and telephone number as quickly as possible to the following address so that the matter can be resolved as quickly as possible: [invoicing@atinternet.com](mailto:invoicing@atinternet.com). \\r\\nYour site will continue to be tracked by AT Internet for the moment: only access to the reports has been suspended until you contact the AT Internet accounting department.\\r\\nBy clicking on the following URL: , and by going to the section entitled “Contract details” you can enter the required information which is missing. We thank you for your understanding and co-operation in this matter. | | InvalidSegment_InvalidCoverage | 400 | Invalid value for parameter “coverage”. Valid values are: values | | InvalidCalculatedColumn_MisusedMultiperiodMetrics | 400 | The calculatedColumns.multiperiodMetrics parameter is forbidden in a non-multiperiod context | | InvalidSegment_InvalidAllVisitsScope | 400 | ‘All Visits’ coverage is incompatible with scope scope. | | InvalidPeriod_IntervalUnder30Minutes | 400 | The difference between startOffset and endOffset must not be less than 30 minutes | | InvalidFunnel_InvalidScope | 400 | Funnel scope is not allowed. Available scopes are visit_id, visitor_id, user_id. | | InvalidIncomingContent_FunnelInvalidStepsMember | 400 | Invalid steps object construction, it should contain only one member. | | InvalidWatcherAlertType | 400 | The type parameter is incorrect. Please specify the required type amongst the values : #values#. | | Timeout | 400 | Time out. The request cannot be processed. | | MissingAppId | 400 | This request needs an app ID to succeed | | InvalidWatcherSites | 400 | The sites parameter is incorrect. | | InvalidWatcherAlertName | 400 | The name parameter is incorrect. | | InvalidPeriod_InvalidDateValue | 400 | You have to request in order to retrieve the data related to the requested period | | InvalidIncomingContent_OldFormat | 400 | The format of one of the request parameters is deprecated | | InvalidFilter_VisibilityParam | 400 | Accepted values for “visibility” parameter are visibilities | | InvalidFilter_SearchParam | 400 | The “Search” parameter must contain at least minimum characters | | InvalidFilter_MaxResultsParam | 400 | max-results must be at most limit | | InvalidEvolution_InvalidPeriod | 400 | Minute and second granularity are available on a day period. | | InvalidPeriod_EndBeforeStart_Updated | 400 | The end date cannot be lower than the start date | | BadRetention_UnknownParameter | 400 | Unknown retention parameter. Available parameters are “p”, “nb”, “d” and “v” | | InvalidAttributionTouchpoint | 400 | The touchpoint parameter is incorrect. Please specify the required touchpoint amongst the values : values. | | InvalidIncomingContent_MultiperiodMetricUnknownOperator | 400 | One of the calculatedColumn’s multiperiodMetric’s operator is invalid | | TooManyRows | 400 | This analysis does not function when multiple dimension values are queried simultaneously. Please restrict your query to a single dimension value. | | InvalidIncomingContent_MetricBasedOnMultiperiodMetric | 400 | One of the calculatedColumn’s metric’s values is a multiperiodMetric | | InvalidIncomingContent_FunnelStepsContentMalformed | 400 | Steps in funnel ne to be an array. | | InvalidEvolution_MissingEvo | 400 | The evolution parameter is missing. | | InvalidWatcherMailingList | 400 | The mailingList parameter is incorrect. | | InvalidWatcherAlertId | 400 | The id parameter is incorrect. | | InvalidWatcherAlertInfo | 400 | The info parameter is incorrect. | | InvalidEvolutionDate_Missing | 400 | The evo-date parameter hasn’t been specified | | ResourceNotFound_Path | 404 | Path does not exist | | QuotasExceeded_TooManySimultaneousRequests | 429 | You have exceeded the number of simultaneous calls allowed. Please wait a moment and try again. | | NotWatcherAlertAdmin | 400 | You are not administrator of the alert. | | InvalidWatcherAlertDescription | 400 | The description parameter is incorrect. | | InvalidFilter_InvalidValueFilter | 400 | invalid filter value with the operator: $period | | InvalidMetric_MalformedKey | 400 | Malformed key key. Allowed characters are \[a-z0-9_-\] | | InvalidIncomingContent_FunnelNoScope | 400 | The « scope » parameter is undefined in « funnel » object. Available scopes are: visit_id, visitor_id, user_id. | | StaticRequestCodeInvalid | 400 | The API call is not recognised, or contains an analysis that no longer exists. | | InvalidInputContent_Level2Incompatibility | 400 | Sources analyses are not available for a level 2 site perimeter. | | InvalidIncomingContent_EmptyParam | 400 | The API call can’t contain empty parameters. | | InvalidIncomingContent_ForbiddenCalculatedColumnsWithRequestId | 400 | The calculatedColumns parameter is forbidden alongside a RequestId | | InvalidIncomingContent_CalculatedColumnInvalidMultiperiodMetricFormat | 400 | The calculatedColumn’s multiperiodMetrics must be an array | | InvalidFilter_FieldsParamForSegments | 400 | Accepted values for “fields” parameter for the segments are fields | | BadRetention_EmptyRetentionType | 400 | The retention type (v) should be set. Possible values are “ratio” or “value” | | InvalidIncomingContent_NoPeriodSpecified | 400 | Request need to specify a period parameter. | | InvalidAttributionModels | 400 | The attribution model parameter is incorrect. Please specify a valid model amongst the following attribution models: values. | | InvalidIncomingContent_UnavailableMetric | 400 | Metric unavailable in this mode | | InvalidAttributionLookbackWindow | 400 | The attribution window parameter is incorrect. Please specify a figure between min and max. | | TooManyMetrics | 400 | This analysis does not function when multiple metrics are queried simultaneously. Please restrict your query to a single metric. | | BadRetention_ForbiddenSegmentScope | 400 | The scope of your segment is different from the scope level scope of your analysis: it is not possible to combine scope types, please adjust your segment scope in order to continue. | | InvalidFilter_FieldsParamForMetrics | 400 | Accepted values for “fields” parameter for the metrics are fields | | InvalidFilter_WrongMetricParameter | 400 | The metric filter parameter should be an object | | ContributionInfeasible | 400 | We are unable to run the contribution algorithm on this anomaly for the time being. This could be due to the fact is has the value “0” or no significant trend stands out in the underlying data. If you would like to be able to run the contribution algorithm on anomalies with the value “0” please inform us via the product feedback tool. | | InvalidSegment_InvalidFilterOperator | 400 | The operator $period cannot be used in a segment | | InvalidFilter_VisibilityParamForAdmin | 400 | The value “admin” for the “visibility” parameter is usable only if the user is Admin | | ContributionWithoutAnomaly | 400 | The requested date is not in error, please select a date with an error so that the contribution API can provide results. | | InvalidColumns_ForbiddenMultiperiodMetricsDate | 400 | Forbidden use of a metric with date type in var of dif | | InvalidFilter_WrongPropertyParameter | 400 | The property filter parameter should be an object | | InvalidFunnel_ForbiddenParam | 400 | forbiddenParam parameter is forbidden with funnel call | | AbsoluteMetricOnly | 400 | The AXON Contribution algorithm is not configured to work on relative metrics. Please choose an absolute metric (a metric that is not a ratio). If you need AXON Contribution on relative metrics, please mention it in the Product Feedback tool. | | InvalidAttributionConversion | 400 | The conversion parameter is incorrect. Please specify the required conversion type amongst the values : values. | | InvalidFunnel_InvalidStepsNumber | 400 | The number of funnel steps must be between 2 and 6 | | InvalidIncomingContent_MultiperiodMetricBasedOnMultiperiodMetric | 400 | One of the calculatedColumn’s multiperiodMetric’s values is a multiperiodMetric | | InvalidFunnel_ContentMalformed | 400 | Steps in funnel should be an object | | InvalidIncomingContent_FunnelInvalidStepsKey | 400 | Unknown steps parameter identifier: key | | NoRealTime | 400 | This analysis is not available in real time | | InvalidWatcherStatus | 400 | The isActive parameter is incorrect. | | InvalidSpace_NavigationL2Forbidden | 400 | Navigation analyses are not available for a level 2 site. | | InvalidMetric_MetricKeyNotFound | 400 | the requested metric does not exist | | InvalidParam_TotalRequest | 400 | Parameters fields are not authorized for a Total request | | InvalidMetric_MalformedMetricKey | 400 | the value of metricKey is invalid | | InvalidFilter_ModeParam | 400 | Accepted values for “mode” parameter are modes | | InvalidColumns_OnlyOneMetric | 400 | Only one metric allowed | | InvalidSegmentedMetrics_TooManyDistinctSegments | 400 | A dataset can contain up to 6 distinct segments | | InvalidFilter_InvalidTypePropertyFilter | 400 | We only filter on a property of type date with the operator $period | | InvalidFilter_FieldsParam | 400 | The “Fields” parameter can not be empty | | ResourceNotFound_Segment | 404 | Segment segment does not exist | --- ## Terms & conditions ## Foreword The Reporting API 3.0 is included in the *Piano Analytics*. In order to ensure a stability in the usage, here are the terms & conditions: - 20 concurrent API calls per organisation - 5 concurrent API calls per user If you exceed these quotas, the [429 error code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) will be returned. We try to make the usage as fair as possible. Please make sure you follow the terms & conditions to maintain access to the Reporting API 3.0 If your user account or organisation has been blacklisted, [please get in touch](mailto:support@piano.io). --- ## Authentication (2) ## General information You will first need to create an API-Key from your Piano Analytics [profile page](https://my.piano.io/profile/#/apikeys). To authenticate, pass your API-Key in header of each API request, using the following header: `x-api-key=ACCESSKEY_SECRETKEY` This API is reserved for administrators of organizations. --- ## How it works (2) ## Foreword Please read the [terms & conditions](/analytics/configuration/technical-information/terms-conditions/) before using this Configuration API. ## General information Here is the URL of the Access Management API V2: - EU `https://analytics-api-eu.piano.io/config/v2` - US `https://analytics-api-us.piano.io/config/v2` - AP `https://analytics-api-ap.piano.io/config/v2` This Access Management API v2.0 is designed to manage users and rights. Access rights can alternatively be managed through the user interface. Please refer to [the dedicated documentation](https://analytics-docs.piano.io/en/analytics/v1/access-security-management) for further details. The available HTTP methods are: | Method | Description | | ------ | --------------------------- | | GET | Get resources | | POST | Create or update a resource | | DELETE | Delete a resource | | PATCH | Partially update a resource | --- ## Assign users ## Foreword HTTP method : POST `v2/teams/{teamId}/users/batch/add` The `teamId` parameter allows you to define the team you need to update. | Parameter | Description | Format | | --------- | ----------- | ------ | | teamId | Team Id | String | ## Request body A maximum of 100 items is allowed per call. ```json { "users": [ { "id": "string" } ] } ``` ## Response `200 OK` ```json { "metadata": { "requestId": "string", "errors": 0, "successes": 0 }, "errors": [ { "code": "string", "message": "string", "index": 0 } ] } ``` --- ## Delete team ## Foreword HTTP method : DELETE `v2/teams/{teamId}` | Parameter | Description | Format | | --------- | ----------- | ------ | | teamId | Team Id | String | If the deleted team contains users, they are not deleted. They become users without access rights. ## Response `204` --- ## Delete user ## Foreword HTTP method : DELETE `v2/users/{userId}` | Parameter | Description | Format | | --------- | ----------- | ------ | | userId | User Id | String | ## Response `204` --- ## Get sites of a team ## Foreword HTTP method : GET `v2/teams/{teamId}/sites?page=2&size=10` | Parameter | Description | Format | | --------- | --------------------------- | ------ | | teamId | Team Id | String | | page | Results page | Number | | size | Number of elements per page | Number | Parameter `page` is mandatory. Parameter `size` is optional. It is the number of items returned per page. Default size = 50 and max size = 100\. Sorted alphabetically by sites name. ## Response `200 OK` `count` is the total number of elements. ```json { "metadata": { "requestId": "", "count": 0, "page": 0, "size": 0 }, "data": { "sites": [ { "name": "string", "id": 0, "closingDate": "string" }, { "name": "string", "id": 0, "closingDate": "string" } ] } } ``` --- ## Get teams ## Foreword HTTP method : GET `v2/teams?page=2&size=10` | Parameter | Description | Format | | --------- | --------------------------- | ------ | | page | Results page | Number | | size | Number of elements per page | Number | Parameter `page` is mandatory. Parameter `size` is optional. It is the number of items returned per page. Default size = 50 and max size = 100. ## Response `200 OK` `count` is the total number of elements. Sorted alphabetically by teams name. ```json { "metadata": { "requestId" :"", "count": 0, "page": 0, "size": 0 }, "data": { "teams": [ { "id": "", "name": "", "availableForSharing": true/false, "allUsers": true/false, "allSites": true/false, }, { "id": "", "name": "", "availableForSharing": true/false, "allUsers": true/false, "allSites": true/false, } ] } } ``` --- ## Get users ## Foreword HTTP method : GET `v2/users?page=2&size=10` | Parameter | Description | Format | | --------- | --------------------------- | ------ | | page | Results page | Number | | size | Number of elements per page | Number | Parameter `page` is mandatory. Parameter `size` is optional. It is the number of items returned per page. Default size = 50 and max size = 100\. This route returns the organization's active and suspended users. ## Response `200 OK` `count` is the total number of elements. Sorted alphabetically by email address. ```json { "metadata": { "requestId": "", "count": 0, "page": 0, "size": 0 }, "data": { "users": [ { "id": "string", "lastName": "string", "firstName": "string", "email": "string", "suspensionStartDate": "ISO string" }, { "id": "string", "lastName": "string", "firstName": "string", "email": "string", "suspensionStartDate": "ISO string" } ] } } ``` --- ## Get users of a team ## Foreword HTTP method : GET `v2/teams/{teamId}/users?page=2&size=10` | Parameter | Description | Format | | --------- | --------------------------- | ------ | | page | Results page | Number | | size | Number of elements per page | Number | | teamId | Team Id | String | Parameter `page` is mandatory. Parameter `size` is optional. It is the number of items returned per page. Default size = 50 and max size = 100\. This route returns the team's active and suspended users. ## Response `200 OK` `count` is the total number of elements. Sorted alphabetically by email address. ```json { "metadata": { "requestId": "", "count": 0, "page": 0, "size": 0 }, "data": { "users": [ { "id": "string", "lastName": "string", "firstName": "string", "email": "string", "suspensionStartDate": "ISO string" }, { "id": "string", "lastName": "string", "firstName": "string", "email": "string", "suspensionStartDate": "ISO string" } ] } } ``` --- ## Remove users ## Foreword HTTP method : POST `v2/teams/{teamId}/users/batch/remove` The `teamId` parameter allows you to define the team you need to update. | Parameter | Description | Format | | --------- | ----------- | ------ | | teamId | Team Id | String | ## Request body A maximum of 100 items is allowed per call. ```json { "users": [ { "id": "string" } ] } ``` ## Response `200 OK` ```json { "metadata": { "requestId": "string", "errors": 0, "successes": 0 }, "errors": [ { "code": "string", "message": "string", "index": 0 } ] } ``` --- ## Suspend user ## Foreword HTTP method : PATCH `v2/users/{userId}` The `userId` parameter allows you to define the user you need to update. | Parameter | Description | Format | | --------- | ----------- | ------ | | userId | User Id | String | ## Request body ```json { "suspensionStartDate": "2025-06-24T11:46:06.672Z" } ``` Suspend the user from the selected date. In order to suspend a user set the `suspensionStartDate` in the future or with the D day. To reactivate a suspended user, set the `suspensionStartDate` to `null`. ## Response `200 OK` ```json { "suspensionStartDate": "2025-06-24T11:46:06.672Z", "lastName": "string", "firstName": "string", "email": "string", "id": "string" } ``` --- ## Create team ## Foreword HTTP method : POST `v2/teams` ## Request body All fields are mandatory. Field length is 255 characters maximum. If the field `availableForSharing` is empty, the team is not available for sharing. By default the role of the team is set to "Document reader". No check on the uniqueness of information sent. ```json { "availableForSharing": true/false, "name": "string" } ``` ## Response `201 Created` ```json { "availableForSharing": true/false, "name": "string", "id": "string" } ``` --- ## Update User Suspension date ## Foreword HTTP method : PATCH `v2/users/{userId}` The `userId` parameter allows you to define the user you need to update. | Parameter | Description | Format | | --------- | ----------- | ------ | | userId | User Id | String | ## Request body ```json { "suspensionStartDate": "ISO String"|null } ``` Suspend the user from the selected date. In order to suspend a user set the `suspensionStartDate` in the future or with the D day. To reactivate a suspended user set the `suspensionStartDate` to `null`. ## Response `200 OK` ```json { "suspensionStartDate": "2025-06-24T11:46:06.672Z", "lastName": "string", "firstName": "string", "email": "string", "id": "string" } ``` --- ## Create user ## Foreword HTTP method : POST `v2/users` ## Request body Only the `email` field is mandatory. By default the culture of the user is English. If the user already exists we do not update his information. Each user can modify his `lastname` and `firstname` in the Profile application. ```json { "suspensionStartDate": "2025-06-24T08:08:36.771Z", "lastName": "string", "firstName": "string", "email": "string" } ``` ## Response `201 Created` ```json { "suspensionStartDate": "2025-06-24T08:08:36.771Z", "lastName": "string", "firstName": "string", "email": "string", "id": "string" } ``` --- ## Error codes (2) | API Code | Status Code | Error Message | | --------------------- | ----------- | ------------------------------------------------------------------------------------ | | INVALID_REQUEST | 400 | The request format is not valid | | INVALID_REQUEST | 400 | The value of the size parameter must be greater than or equal to 1. | | INVALID_REQUEST | 400 | The value of the size parameter must be less than or equal to 100 | | INVALID_REQUEST | 400 | The value of the page parameter must be greater than or equal to 1. | | INVALID_REQUEST | 400 | The size parameter must be an integer | | INVALID_REQUEST | 400 | The page parameter must be an integer | | INVALID_REQUEST | 400 | page : 'page' is required | | INVALID_REQUEST | 400 | You cannot add users to a team with fullUsers true | | INVALID_REQUEST | 400 | You cannot remove users from a team with fullUsers true | | INVALID_EMAIL | 400 | This email is not valid : email | | INVALID_FORMAT | 400 | user.suspensionStartDate : invalid ISO 8601 datetime format, i.e. YYYY-MM-DDTHH:mm:s | | INVALID_FORMAT | 400 | Page : page is required | | INVALID_FORMAT | 400 | The field format xxxx is not valid | | INVALID_FORMAT | 400 | page : invalid float number | | INVALID_FORMAT | 400 | size : invalid float number | | INVALID_FORMAT | 400 | Name too long | | INVALID_DATE | 400 | Invalid suspension start date format, please follow the ISO 8601 format | | INVALID_DATE | 400 | Suspension start date must be set for the current date or in the future | | INVALID_DATE | 400 | "suspensionStartDate" must be greater than or equal to 2025-06-20T16:57:00 | | USER_ALREADY_EXISTS | 400 | The email email already exists | | FORBIDDEN | 403 | User not allowed | | FORBIDDEN | 403 | The limit of xx users per organization has been reached | | NOT_FOUND | 404 | User 'user' not found | | NOT_FOUND | 404 | The team does not exist | | CONFLICT | 409 | This operation is not possible | | TOO_MANY_REQUESTS | 429 | You have exceeded the number of calls allowed. Please wait a moment and try again. | | UNKNOWN_ERROR | 500 | Unknown error | --- ## Terms & conditions (2) ## Foreword The Access Management API 2.0 is included in *Piano Analytics*. In order to ensure a stability in the usage, here are the terms & conditions: - 1 000 users by default per organization ; Please contact the support center in order to upgrade; if you exceed this limit, the 403 error code will be returned. Make sure to delete users who no longer connect or are suspended before calling the Support Center. - 1 000 teams by default per organization; Please contact the support center in order to upgrade; if you exceed this limit, the 403 error code will be returned. Make sure to delete all teams that are no longer useful before calling the Support Center. - 100 requests per minute per IP address; if you exceed the quota the 429 error code will be returned.