diff --git a/_config.yml b/_config.yml index 86c8bf39..502f727a 100644 --- a/_config.yml +++ b/_config.yml @@ -216,6 +216,7 @@ collections: output: true order: - developers-overview.md + - custom-store-integration.md - api.md - send-sms-with-api.md - tracking-events.md diff --git a/_developers/api.md b/_developers/api.md index 81190b17..c8c6bf26 100644 --- a/_developers/api.md +++ b/_developers/api.md @@ -3,10 +3,10 @@ languages: ["en", "es"] en: title: API reference - description: The complete reference of all available resources attributes, parameters and endpoints. + description: The complete reference for all available resources, attributes, parameters, and endpoints. es: title: Referencia de la API - description: Referencia completa de todos los recursos disponibles con explicación de atributos, parámetros y direcciones. + description: Referencia completa de todos los recursos, atributos, parámetros y endpoints disponibles. permalink: api permalink_es: api diff --git a/_developers/custom-store-integration.md b/_developers/custom-store-integration.md new file mode 100644 index 00000000..191ae51d --- /dev/null +++ b/_developers/custom-store-integration.md @@ -0,0 +1,19 @@ +--- +languages: ["en", "es"] + +en: + title: Integrate a custom store with Hellotext + description: Connect customer profiles, properties, products, historical orders, Hellotext.js, and server-side tracking in the right order. +es: + title: Integra una tienda propia con Hellotext + description: Conecta perfiles de clientes, propiedades, productos, pedidos históricos, Hellotext.js y seguimiento desde el servidor en el orden correcto. + +permalink: integrate-custom-store +permalink_es: integrar-tienda-personalizada + +layout: guide +topic: developers +popular: true +--- + +{% translate_file developers/custom-store-integration.md %} diff --git a/_developers/developers-overview.md b/_developers/developers-overview.md index 6a15fad9..e7b3068e 100644 --- a/_developers/developers-overview.md +++ b/_developers/developers-overview.md @@ -6,7 +6,7 @@ en: description: Learn where to start with API access, event tracking, SMS sending, and custom integrations. es: title: Resumen de desarrolladores y API - description: Aprende por dónde empezar con acceso API, tracking de eventos, envío de SMS e integraciones personalizadas. + description: Aprende por dónde empezar con acceso a la API, seguimiento de eventos, envío de SMS e integraciones personalizadas. permalink: developers-api-overview permalink_es: resumen-desarrolladores-api diff --git a/_developers/external-tracking.md b/_developers/external-tracking.md index d47ccbd5..45dfc331 100644 --- a/_developers/external-tracking.md +++ b/_developers/external-tracking.md @@ -3,10 +3,10 @@ languages: ["en", "es"] en: title: External tracking - description: How to track events from external systems such as databases, POS, or eCommerce platforms. + description: Send trusted customer, product, order, and custom events from your backend or external systems. es: title: Seguimiento de origen externo - description: Cómo rastrear eventos desde sistemas externos como bases de datos, POS o plataformas de comercio electrónico. + description: Registra eventos confiables de clientes, productos, pedidos y acciones personalizadas desde tu backend o sistemas externos. permalink: external-tracking permalink_es: seguimiento-externo @@ -16,4 +16,4 @@ topic: developers popular: true --- -{% translate_file developers/external-tracking.md %} \ No newline at end of file +{% translate_file developers/external-tracking.md %} diff --git a/_developers/send-sms-with-api.md b/_developers/send-sms-with-api.md index 4e183c9f..79c20795 100644 --- a/_developers/send-sms-with-api.md +++ b/_developers/send-sms-with-api.md @@ -3,10 +3,10 @@ languages: ["en", "es"] en: title: Send SMS with the API - description: Learn how to send SMS messages from your system using the Hellotext API. + description: Send individual SMS messages securely and verify their processing and delivery states. es: title: Enviar SMS con la API - description: Aprende a enviar mensajes SMS desde tu sistema usando la API de Hellotext. + description: Envía SMS individuales de forma segura y verifica sus estados de procesamiento y entrega. permalink: send-sms-with-api permalink_es: enviar-sms-con-api diff --git a/_developers/tracking-events.md b/_developers/tracking-events.md index 0cb38909..04e6e439 100644 --- a/_developers/tracking-events.md +++ b/_developers/tracking-events.md @@ -3,10 +3,10 @@ languages: ["en", "es"] en: title: Tracking events - description: Understand how to track customer activity from your site, store, or custom system. + description: Understand actions, events, objects, and the correct source for each customer signal. es: title: Seguimiento de eventos - description: Entiende cómo rastrear actividad de clientes desde tu sitio, tienda o sistema personalizado. + description: Comprende acciones, eventos, objetos y la fuente correcta para cada señal del cliente. permalink: tracking-events permalink_es: seguimiento-de-eventos diff --git a/_developers/tracking-on-campaigns-and-journeys.md b/_developers/tracking-on-campaigns-and-journeys.md index 9376f407..2e53ed9e 100644 --- a/_developers/tracking-on-campaigns-and-journeys.md +++ b/_developers/tracking-on-campaigns-and-journeys.md @@ -3,10 +3,10 @@ languages: ["en", "es"] en: title: Track campaign, route, and playbook links - description: Learn how to use Hellotext.js to track events from links in campaigns, routes, and playbooks. + description: Understand how tracked links preserve message, session, reporting, and attribution context after a click. es: title: Seguimiento de links en campañas, rutas y playbooks - description: Aprende a usar Hellotext.js para rastrear eventos desde links en campañas, rutas y playbooks. + description: Comprende cómo los links conservan el contexto del mensaje, la sesión, los reportes y la atribución después de un clic. permalink: tracking-on-campaigns-and-journeys permalink_es: seguimiento-en-campañas-y-rutas diff --git a/_developers/tracking-unidentified-customers.md b/_developers/tracking-unidentified-customers.md index f1f8d782..046d02f0 100644 --- a/_developers/tracking-unidentified-customers.md +++ b/_developers/tracking-unidentified-customers.md @@ -3,10 +3,10 @@ languages: ["en", "es"] en: title: Tracking unidentified customers - description: Track events from new visitors to your site who have not been identified yet. + description: Preserve anonymous browser activity and associate it safely with a known customer profile. es: title: Seguimiento de clientes no identificados - description: Realiza seguimiento de los eventos de los nuevos visitantes de tu sitio que aún no han sido identificados. + description: Conserva la actividad anónima del navegador y asóciala de forma segura con un perfil del cliente conocido. permalink: tracking-unidentified-customers permalink_es: seguimiento-de-clientes-no-identificados @@ -16,4 +16,4 @@ topic: developers popular: false --- -{% translate_file developers/tracking-unidentified-customers.md %} \ No newline at end of file +{% translate_file developers/tracking-unidentified-customers.md %} diff --git a/_i18n/en/analytics-reporting-attribution/tracked-links.md b/_i18n/en/analytics-reporting-attribution/tracked-links.md index cbd81020..afac60cf 100644 --- a/_i18n/en/analytics-reporting-attribution/tracked-links.md +++ b/_i18n/en/analytics-reporting-attribution/tracked-links.md @@ -7,7 +7,7 @@ and is located in the editor toolbar. Links have the following structure: `hello.link/XXXXXX` where `XXXXXX` is the link's unique identifier. -When these links are clicked, Hellotext redirects the customer to the URL specified when creating the link and attaches a `hellotext_session` identifier +When these links are clicked, Hellotext redirects the customer to the URL specified when creating the link and attaches a `hello_session` identifier to the URL. This identifier is used to identify the session and can be used to track actions performed by the customer as signals. You can look at our client-side JavaScript library that helps you with tracking related events. diff --git a/_i18n/en/developers/custom-store-integration.md b/_i18n/en/developers/custom-store-integration.md new file mode 100644 index 00000000..dc98b97f --- /dev/null +++ b/_i18n/en/developers/custom-store-integration.md @@ -0,0 +1,382 @@ +Use this guide when your store does not have a native Hellotext integration and your team needs to connect it through the API and Hellotext.js. + +The implementation has two parts: + +- **Your backend** uses a private authorization token to create and update customer profiles, properties, products, orders, and trusted server-side events. +- **Your storefront** uses the public Business ID with Hellotext.js to create visitor sessions and track browser activity such as page views, product views, and cart changes. + +> **Keep the credentials separate:** the API authorization token belongs only on your server. Never put it in browser code. The Business ID used by Hellotext.js is the public identifier intended for the storefront. + +This guide provides the recommended implementation order. Use the [API reference]({% link _developers/api.md %}) for the complete request and response contract of every endpoint. + +## Before you start + +Prepare: + +- Owner or Administrator access to the Hellotext business. +- Access to the store backend and storefront code. +- Stable customer, product, cart, and order identifiers from your system. +- The currency, product structure, and order states used by the store. +- A clear record of consent. Creating a customer profile does not prove that the customer consented to receive messages. + +Choose a consistent source name, such as `custom_store`, and reuse it for products, carts, orders, and browser identity. Do not change this value between requests. + +## 1. Create an API authorization token + +1. In Hellotext, open **Settings → Authorization Tokens**. +2. Select **Create new token** and give the token a name that identifies the integration. +3. Copy the token when Hellotext displays it. It cannot be displayed again. +4. Store it in your backend secret manager or environment as `HELLOTEXT_API_TOKEN`. + +Test the token from your server: + +```bash +curl --request GET \ + --url https://api.hellotext.com/v1/profiles \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" +``` + +A successful response confirms that the token belongs to the expected business. A `401` response usually means that the token is missing, invalid, or revoked. + +See [Hellotext API authentication](https://www.hellotext.com/api#authentication) for the authorization header format and possible responses. + +## 2. Create the property definitions you need + +Hellotext already includes first name and last name as standard customer profile data, as well as properties for phone, email, address, company, gender, and birthday. Use these built-in fields instead of recreating them as custom properties. + +Create any additional properties your customer profiles need to represent business-specific data, such as a loyalty identifier, preferred store, customer tier, size, or account type. + +Create each reusable property once: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/properties \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "name": "Customer ID", + "kind": "text", + "unique": true + }' +``` + +Save the returned property `id`. You will use that ID when assigning a value to a customer profile. Choose the correct `kind` before importing values, because it determines how Hellotext validates, displays, and segments the property. + +See [Create a property in the API](https://www.hellotext.com/api#create_a_property) for every supported type, parameter, and option. For more about global and customer-profile-specific properties, see [Custom properties and events]({% link _audience/custom-properties-and-events.md %}). + +## 3. Create or synchronize customer profiles + +Create a customer profile with the identifiers and attributes you already know: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/profiles \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "first_name": "Ana", + "last_name": "Silva", + "email[primary]": "ana@example.com", + "phone[mobile]": "+59899000001", + "property_by_id[PROPERTY_ID]": "customer-4821" + }' +``` + +The response includes the Hellotext customer profile `id`. Store it beside the customer record in your system and use it for later updates and server-side events. + +Hellotext can match an existing customer profile by phone or email when you create or update it. Even so, your integration should keep the returned Hellotext ID and update the existing customer profile instead of blindly creating a new one on every synchronization. + +Do not mark imported customer profiles as subscribed unless you have valid consent for the relevant channel. Customer profile creation, identity, and messaging permission are separate concerns. See [Create a customer profile in the API](https://www.hellotext.com/api#create_a_profile) for every available field and [Who can I message?]({% link _audience/consent-and-subscriber-status.md %}) for consent guidance. + +## 4. Synchronize the product catalog + +Create the products and variants that Hellotext needs for recommendations, product activity, carts, orders, and playbooks: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/products \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "name": "Everyday Sneakers", + "reference": "product-100", + "sku": "SKU-100", + "source": "custom_store", + "url": "https://shop.example.com/products/everyday-sneakers", + "image_url": "https://shop.example.com/images/everyday-sneakers.jpg", + "price": { + "amount": 89.90, + "currency": "USD" + }, + "categories": ["Shoes"], + "tags": ["Everyday"] + }' +``` + +Save the returned product `id`. Use that ID when tracking product views and when adding items to carts or orders. + +Keep `source`, `reference`, and SKU values stable. Update the existing product when its name, price, image, URL, categories, tags, variants, or other supported data changes. Do not create a new Hellotext product for every catalog sync. + +See [Create a product in the API](https://www.hellotext.com/api#create_a_product) for all supported product and variant data. + +## 5. Import historical orders + +Historical orders give Hellotext purchase context before the first live event arrives. Each imported order needs: + +- A stable order reference and source. +- The correct customer profile. +- Products and quantities. +- Total amount and currency. +- The original event time. + +First create the order and keep its returned `id`: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/orders \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "reference": "ORDER-1001", + "source": "custom_store", + "delivery": "deliver", + "total": { + "amount": 89.90, + "currency": "USD" + }, + "items": [ + { + "product": "PRODUCT_ID", + "quantity": 1, + "price": { + "amount": 89.90, + "currency": "USD" + } + } + ] + }' +``` + +Then record the order event against the customer profile. `tracked_at` is the original event time as a Unix timestamp: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "order.confirmed", + "profile": "PROFILE_ID", + "object": "ORDER_ID", + "amount": 89.90, + "currency": "USD", + "tracked_at": 1751328000 + }' +``` + +Use the event that reflects what really happened, such as `order.placed`, `order.confirmed`, `order.cancelled`, `order.shipped`, or `order.delivered`. Do not invent lifecycle events that your store cannot verify. + +Preserve original timestamps during the historical import. Otherwise, old purchases can look like current activity and distort segmentation, playbook eligibility, and reporting. + +See [Create an order](https://www.hellotext.com/api#create_an_order) and [track order events](https://www.hellotext.com/api#track_order_events) for all available options. + +## 6. Install Hellotext.js on the storefront + +Install the package with npm: + +```bash +npm install @hellotext/hellotext +``` + +Import and initialize it once when the storefront starts: + +```javascript +import Hellotext from '@hellotext/hellotext' + +Hellotext.initialize('HELLOTEXT_BUSINESS_ID') +``` + +The `HELLOTEXT_BUSINESS_ID` is the public identifier shown in the Hellotext business settings. It is not the private API authorization token. + +For a site without a JavaScript bundler, use the script build: + +```html + + +``` + +Use the [Hellotext.js repository](https://github.com/hellotext/hellotext.js) for the current package, framework, Forms, and Webchat instructions. + +## 7. Track browser activity + +Hellotext.js creates the visitor session and automatically tracks `page.viewed` with the current URL. You do not need to send that event manually. + +A page view does not identify which product the customer is viewing. On every product page, explicitly include the corresponding product. If you have already synchronized the catalog, use the ID returned by Hellotext: + +Track a known product view: + +```javascript +await Hellotext.track('product.viewed', { + object: 'PRODUCT_ID', +}) +``` + +If the Hellotext ID is not yet available in the storefront, you can send the data needed to create or find the product. Keep `reference` and `source` stable to prevent duplicates: + +```javascript +await Hellotext.track('product.viewed', { + object_parameters: { + name: 'Everyday Sneakers', + reference: 'product-100', + source: 'custom_store', + url: window.location.href, + image_url: 'https://shop.example.com/images/everyday-sneakers.jpg', + price: { + amount: 89.90, + currency: 'USD', + }, + }, +}) +``` + +Track a cart item with a stable cart reference: + +```javascript +const response = await Hellotext.track('cart.added', { + object_parameters: { + reference: 'CART-9001', + source: 'custom_store', + items: [ + { + product: 'PRODUCT_ID', + quantity: 1, + }, + ], + }, +}) + +if (response.failed) { + console.error(response.data) +} +``` + +Reuse the same cart reference for later `cart.added` and `cart.removed` activity. Track `cart.abandoned` only when your store has actually determined that the cart was abandoned. + +Hellotext.js can also track an order when the confirmation page is the only available integration point. You must explicitly include the order and its products: + +```javascript +await Hellotext.track('order.placed', { + amount: 89.90, + currency: 'USD', + object_parameters: { + reference: 'ORDER-1001', + source: 'custom_store', + items: [ + { + product: 'PRODUCT_ID', + quantity: 1, + }, + ], + }, +}) +``` + +Browser events are appropriate for browsing and cart behavior. Whenever possible, record trusted purchase and fulfillment milestones from the backend so customers cannot fabricate orders by calling browser code. Do not send the same order event from both the browser and the backend. + +See [Tracking events]({% link _developers/tracking-events.md %}) for automatic page views and [product events](https://www.hellotext.com/api#track_product_events), [cart events](https://www.hellotext.com/api#track_cart_events), and [order events](https://www.hellotext.com/api#track_order_events) for every supported action and parameter. + +## 8. Connect anonymous activity to the customer + +Hellotext.js starts with an anonymous visitor session. When the visitor logs in, registers, or completes checkout, connect that session to the Hellotext customer profile. + +The preferred method is server-to-server: + +1. Read `Hellotext.session` in the browser. +2. Send the session ID to your backend together with the authenticated customer. +3. Attach the session to the stored Hellotext customer profile ID using the private API token. + +```bash +curl --request PATCH \ + --url https://api.hellotext.com/v1/sessions/HELLOTEXT_SESSION_ID \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "profile": "PROFILE_ID" + }' +``` + +This moves the earlier anonymous activity into the known customer profile. + +For a custom store, do not use `identify()` with an invented `source` value. That method is reserved for sources supported by Hellotext.js when server-to-server identification is unavailable. If a compatible integration uses `identify()`, it must call `Hellotext.forget()` when the customer logs out. + +See [Attach a session in the API](https://www.hellotext.com/api#attach_session) for every parameter and [Tracking unidentified customers]({% link _developers/tracking-unidentified-customers.md %}) for the complete flow, the `identify()` alternative, and logout handling. + +## 9. Track trusted events from the backend + +Use `POST /v1/attribution/events` for activity that happens outside the browser or must be trusted, including: + +- Order placement and confirmation. +- Payment or purchase events. +- Cancellation, shipping, and delivery milestones. +- Physical-store or marketplace activity. +- Events created by jobs, webhooks, or internal systems. + +Send either the Hellotext customer profile ID when the customer is known or the Hellotext session ID when only the session is available. Include `tracked_at` when the event happened before the request was sent. + +For example, track `order.placed` when your backend confirms that the order was created: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "order.placed", + "profile": "PROFILE_ID", + "object": "ORDER_ID", + "amount": 89.90, + "currency": "USD" + }' +``` + +Reuse the same `ORDER_ID` for `order.confirmed`, `order.shipped`, `order.delivered`, or `order.cancelled` as the order changes state. Send only events your backend can verify. + +See [Tracking in the API](https://www.hellotext.com/api#tracking), [order events](https://www.hellotext.com/api#track_order_events), and [External tracking]({% link _developers/external-tracking.md %}) for every parameter and additional server-side examples. + +## 10. Verify the complete integration + +Before enabling playbooks or campaigns, test one recognizable customer from beginning to end: + +1. Create or update the customer profile and confirm its phone, email, and custom properties. +2. Confirm that the product and variant IDs match the store catalog. +3. Open the storefront and verify that Hellotext.js creates a session. +4. Track a product view and a cart update. +5. Identify the customer or attach the session from the backend. +6. Create a test order and record its real lifecycle event server-side. +7. Confirm that the events appear on the correct customer profile and use the expected timestamps. +8. Review playbook and reporting activity only after the underlying customer profile, product, cart, and order records are correct. + +If data is missing, use [Troubleshoot missing signals or activity]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}). + +## Go-live checklist + +- The private token exists only in backend secrets. +- The public Business ID is used by Hellotext.js. +- Customer, product, cart, and order mappings use stable IDs. +- Product updates do not create duplicate catalog records. +- Historical orders preserve their original timestamps and currencies. +- Browser tracking covers browsing and cart activity. +- Server-side tracking covers trusted order and fulfillment events. +- Anonymous sessions are attached when a customer becomes known. +- Logout calls `Hellotext.forget()` when browser identification is used. +- Subscription status is set only from valid consent evidence. + +## Related guides + +- [Developers and API overview]({% link _developers/developers-overview.md %}) +- [Tracking events]({% link _developers/tracking-events.md %}) +- [Custom properties and events]({% link _audience/custom-properties-and-events.md %}) +- [Verify your data and signals after setup]({% link _integrations/verify-data-and-signals.md %}) +- [Sales attribution]({% link _analytics-reporting-attribution/sales-attribution.md %}) diff --git a/_i18n/en/developers/developers-overview.md b/_i18n/en/developers/developers-overview.md index 449d15b6..37db0700 100644 --- a/_i18n/en/developers/developers-overview.md +++ b/_i18n/en/developers/developers-overview.md @@ -1,12 +1,21 @@ Use the developer guides when you need to connect Hellotext with your own site, backend, CRM, commerce platform, or internal tools. -Most developer work in Hellotext falls into four areas: +If you are connecting a custom store without a native integration, start with [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}). It puts profiles, properties, products, historical orders, Hellotext.js, identity, and server-side tracking in the correct implementation order. +Most developer work in Hellotext falls into five areas: + +- Integrating a custom store from end to end. - Reading the API reference. - Sending messages from your own system. - Tracking customer activity. - Connecting unidentified sessions to customer profiles. +## Custom store integration + +The custom-store guide is the practical starting point for a team that does not yet know which data belongs in the API, which activity belongs in Hellotext.js, or how the two sides connect. + +Start here: [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}). + ## API reference The API reference is the source of truth for available resources, attributes, parameters, and endpoints. diff --git a/_i18n/en/developers/external-tracking.md b/_i18n/en/developers/external-tracking.md index 800e4ebd..50825315 100644 --- a/_i18n/en/developers/external-tracking.md +++ b/_i18n/en/developers/external-tracking.md @@ -1,71 +1,209 @@ -Sometimes you may want to track events that happened outside the visitor browser. For example, you may want to track events on the server-side of your system, or at some time when the customer is not present. +Use this guide to send trusted events to Hellotext when they happen outside the browser, for example in your backend, POS, CRM, ERP, marketplace, logistics provider, jobs, or webhooks. -You can track events by sending a `POST` request directly to the API and passing either the profile identifier or the session identifier. +External tracking complements Hellotext.js. Use Hellotext.js for navigation and cart activity that happens in the storefront. Use the API from your backend for orders, payments, cancellations, shipments, deliveries, and other actions the server can verify. -The following examples use ruby's [**HTTParty**](https://github.com/jnunemaker/httparty) library. This may vary depending on the programming language, but the nature of the request remains the same. +If you are connecting a custom store from the beginning, start with [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) to implement customer profiles, catalog data, orders, Hellotext.js, and identity in the recommended order. -When making a request to the API make sure to authenticate by setting the `Authorization` bearer token as the example. You can create an authorization token from the Tokens section in the business Settings. +## Before you start -### Tracking by profile +Prepare: -You can track events directly to profiles by simply specifying the profile identifier when tracking the event. If the profile doesn't exist on Hellotext you must create it first. We recommend reading the [**API reference for creating a profile**](https://www.hellotext.com/api#create_a_profile). +- A private API authorization token stored only in your backend. +- The action name you want to track, such as `product.viewed`, `order.placed`, or an existing custom action. +- The Hellotext customer profile ID or a Hellotext session ID. +- The related object ID, such as a product or order, or the data needed to create it. +- Stable identifiers from the source system to prevent duplicate objects. -```ruby -HTTParty.post "https://api.hellotext.com/v1/attribution/events", - headers: { - "Authorization" => "Bearer ALK_eSMRuwJ2Al...", - "Content-Type" => "application/json" - }, - body: { - action: "product.purchased", - product: "vxqQJ3Yg", - profile: "PROFILE_ID" - }.to_json +Every example sends a `POST` request to: + +```text +https://api.hellotext.com/v1/attribution/events ``` -Replace the `PROFILE_ID` with the profile identifier of your customer. +Send the token through the `Authorization` header. See [API authentication](https://www.hellotext.com/api#authentication) to create and use the token correctly. -If the request was made correctly the API should respond with a HTTP Status code of `201` and a JSON response similar to this: +## 1. Choose the customer profile or session -```json -{ - "state": "ok" -} +Every event needs either `profile` or `session`. Do not use `profile_id` or `session_id` in this request body. + +### When the customer is known + +Use `profile` with the Hellotext customer profile ID. For example, track a view for a product that already exists in the catalog: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "product.viewed", + "profile": "PROFILE_ID", + "object": "PRODUCT_ID" + }' ``` -### Tracking by session +Keep the ID returned by Hellotext when you create the customer profile. If it does not exist yet, see [Create a customer profile](https://www.hellotext.com/api#create_a_profile). -This is perfectly possible by capturing the session identifier and keeping it on your system to use it later when tracking an event. +### When only the session is known -To obtain the current session, simply call `Hellotext.session`: +Hellotext.js exposes the current session after initialization: ```javascript -Hellotext.session -// Returns bBJn9vR15yPaYkWmR2QK0jopMeNxrA6l +const sessionId = Hellotext.session ``` -Perform the following request to the API: +Send that ID to your backend and use `session` when tracking the event: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "product.viewed", + "session": "HELLOTEXT_SESSION_ID", + "object": "PRODUCT_ID" + }' +``` + +You can send `profile` and `session` together when you want to associate that session context with the customer. The session must be unassigned or belong to the same customer profile. Hellotext rejects the event if the session already belongs to another profile. + +See [Tracking unidentified customers]({% link _developers/tracking-unidentified-customers.md %}) to learn how to retain and attach sessions. + +## 2. Associate the correct object + +Most built-in actions require a related object: + +- `object` identifies an object that already exists in Hellotext. +- `object_parameters` contains the data needed to create or find the object while the event is tracked. +Use `object` when you have synchronized the catalog or order and retained the ID returned by Hellotext. Use `object_parameters` when the source system has all the required information but the Hellotext ID is not yet available. -```ruby -HTTParty.post "https://api.hellotext.com/v1/attribution/events", - headers: { - "Authorization" => "Bearer ALK_eSMRuwJ2Al...", - "Content-Type" => "application/json" - }, - body: { - action: "product.purchased", - product_id: "vxqQJ3Yg", - session_id: "HELLOTEXT_SESSION_ID" - }.to_json +This example tracks a view and creates or finds the product through `reference` and `source`: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "product.viewed", + "profile": "PROFILE_ID", + "object_parameters": { + "name": "Everyday Sneakers", + "reference": "product-100", + "source": "custom_store", + "url": "https://shop.example.com/products/everyday-sneakers", + "price": { + "amount": 89.90, + "currency": "USD" + } + } + }' +``` + +Keep `reference` and `source` stable. Changing them between requests can create separate objects for the same product, cart, or order. + +See [product events](https://www.hellotext.com/api#track_product_events), [cart events](https://www.hellotext.com/api#track_cart_events), and [order events](https://www.hellotext.com/api#track_order_events) for the object and parameters required by each action. + +## 3. Track the order lifecycle + +To track several states for one order, create or synchronize the order first and retain its Hellotext ID. Then reuse that ID for every real lifecycle event: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "order.placed", + "profile": "PROFILE_ID", + "object": "ORDER_ID", + "amount": 89.90, + "currency": "USD" + }' ``` -You should replace the `HELLOTEXT_SESSION_ID` with the session identifier. +Reuse the same `ORDER_ID` to track only the changes your system can confirm: + +- `order.confirmed` when the business confirms the order. +- `order.shipped` when the order leaves for delivery. +- `order.delivered` when delivery is confirmed. +- `order.cancelled` when the order is cancelled. + +Do not track every state when the order is created. Send each event only when that change actually happens. See [Create an order](https://www.hellotext.com/api#create_an_order) for every available field. -If the request was made correctly the API should respond with a HTTP Status code of `201` and a JSON response similar to this: +## 4. Track custom actions + +Hellotext includes actions for products, carts, orders, forms, coupons, and other common objects. When none represents your business activity, create a custom action first and then use its name in `action`: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "appointment.completed", + "profile": "PROFILE_ID", + "tracked_at": "2026-08-07T12:30:00Z" + }' +``` + +A custom action can be tracked without a related object. If you send a custom object, you must also specify its type according to the API contract. + +See [Create an action](https://www.hellotext.com/api#create_an_action) before tracking the first custom event. + +## 5. Preserve timestamps and monetary values + +If the event happened before the request was sent, include `tracked_at` as an ISO 8601 date or Unix timestamp. If you omit it, Hellotext uses the time when the event is received. + +Use the original event time for historical imports, delayed jobs, and retried webhooks. This prevents old activity from appearing recent and affecting segmentation, playbook eligibility, or reporting. + +When the event has a monetary value, send `amount` and `currency` together: + +```json +{ + "amount": 89.90, + "currency": "USD" +} +``` + +If you include `currency`, `amount` is required. Use the ISO 4217 currency code and do not manually convert the value into the reporting currency. + +## 6. Interpret the response and handle errors + +A valid request responds with HTTP `200`: ```json { - "state": "ok" + "status": "received" } -``` \ No newline at end of file +``` + +This confirms that Hellotext received the event for processing. Always inspect the HTTP status and response body: + +- `401` means the token is missing, invalid, or revoked. +- `404` can mean the action does not exist for that business. +- `422` means parameters are missing or the customer profile, session, object, or object data is invalid. + +Record the status and error in your logs, but never log the token or complete customer personal data. + +## 7. Prevent duplicate events + +Every accepted request can create a new event, even when the same product or order is reused. Finding the same object through `reference` and `source` does not remove repeated events. + +- Store which source event has already been accepted by Hellotext in your own system. +- Do not retry `200` responses. +- Retry temporary errors with progressive backoff and retain the source event identifier in your own queue. +- Do not send the same event through Hellotext.js and the backend. +- Process repeated provider webhooks only once before calling Hellotext. + +See the complete [tracking API reference](https://www.hellotext.com/api#tracking) for every supported action, object, and parameter. + +## Related guides + +- [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) +- [Tracking events]({% link _developers/tracking-events.md %}) +- [Tracking unidentified customers]({% link _developers/tracking-unidentified-customers.md %}) +- [Custom properties and events]({% link _audience/custom-properties-and-events.md %}) +- [Troubleshoot missing signals or activity]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}) diff --git a/_i18n/en/developers/send-sms-with-api.md b/_i18n/en/developers/send-sms-with-api.md index 8ffcc2e7..be654021 100644 --- a/_i18n/en/developers/send-sms-with-api.md +++ b/_i18n/en/developers/send-sms-with-api.md @@ -1,46 +1,76 @@ -Sending SMS through the Hellotext API is a simple way to integrate reminders, confirmations, or notifications from your own system. +Use the Hellotext API when your system needs to trigger an individual SMS, such as a confirmation, reminder, or transactional notification. To send the same message to an audience, use a Hellotext campaign, where you can select recipients and review send performance. ## Before you start -To send SMS through the API you need to: +You need: -* Have an account and a business already created in Hellotext. -* Create an authorization token from *Settings* -> *Authorizations*. -* Have SMS balance available in your business. +- an active Hellotext business with SMS sending enabled; +- an authorization token for the business; +- a valid destination number or the identifier of a customer profile with a phone number; and +- permission to send the corresponding type of message. -If SMS balance is not enabled yet, please contact our team to activate it. +The token can act on the data of the business that created it. Store it only in your backend or a secret manager. Do not include it in Hellotext.js, browser code, or a distributed mobile application. -## Create the authorization token +## 1. Create an authorization token -Once you are inside your business, go to *Settings* -> *Authorizations*. +In Hellotext, open the business and go to **Settings → Authorizations**. Select **Create new token**, use a name that identifies the integration, and store the generated value. -Click *Create new token*, give it a name that helps you identify the integration, and copy the generated value. You will use it in the `Authorization` header of each request: +Send the token with every request: ```text Authorization: Bearer YOUR_TOKEN ``` -## Send an SMS +Each token belongs to one business. Use different tokens for different businesses or environments, and replace a token if it is no longer private. See the [API authentication section](https://www.hellotext.com/api#authentication) for the complete reference. -To send a message, make a `POST` request to `https://api.hellotext.com/v1/messages`. +## 2. Choose how to identify the recipient -Send these fields in the request body: +You can send the SMS in two ways: -* `body`: message content. -* `destination`: destination number in international format, for example `+573176655211`. -* `technology`: delivery technology. For SMS use `sms`. +- **With a phone number:** send `destination` in international E.164 format, for example `+14155552671`. Hellotext looks for a customer profile with that phone and creates one automatically if none exists. +- **With a customer profile:** send its identifier in `profile`. The profile must have an available phone number. If it has several and you need to choose a specific one, also include `destination`. -### cURL example +Creating or finding the customer profile during the send does not automatically subscribe it to promotional communications. Customer identity and consent are separate data. + +## 3. Send your first SMS + +Make a `POST` request to `https://api.hellotext.com/v1/messages` with: + +- `technology`: use `sms` to force the SMS channel; +- `body`: the message content; and +- `destination` or `profile`: the recipient. + +This example sends to a phone number and lets Hellotext find or create the customer profile: ```bash curl -X POST "https://api.hellotext.com/v1/messages" \ -H "Authorization: Bearer YOUR_TOKEN" \ - -F "body=Hello, this is an SMS sent through the Hellotext API." \ - -F "destination=+573176655211" \ - -F "technology=sms" + -H "Content-Type: application/json" \ + --data '{ + "technology": "sms", + "destination": "+14155552671", + "body": "Your order is ready for pickup." + }' ``` -If the request is accepted, the API will respond with a JSON similar to this: +If you already know the customer profile identifier, you can use it instead of the phone number: + +```bash +curl -X POST "https://api.hellotext.com/v1/messages" \ + -H "Authorization: Bearer YOUR_TOKEN" \ + -H "Content-Type: application/json" \ + --data '{ + "technology": "sms", + "profile": "PROFILE_ID", + "body": "Your order is ready for pickup." + }' +``` + +Hellotext automatically chooses an available SMS channel. Only send `origin` when you need to use a specific sender configured for the business. See [Send a Message in the API reference](https://www.hellotext.com/api#create_a_message) for every parameter. + +## 4. Interpret the response + +When the request is valid, the API responds with: ```json { @@ -48,56 +78,80 @@ If the request is accepted, the API will respond with a JSON similar to this: } ``` -### Postman example +This response confirms that Hellotext accepted the request and scheduled it for processing. It does not confirm that the mobile carrier delivered the SMS. + +The send is processed asynchronously. Later message states can include: -If you prefer to test it in Postman, configure: +- `pending`: created and waiting for processing; +- `routed`: sent to the external provider; +- `delivered`: confirmed as delivered; and +- `failed`: could not be delivered. -* Method: `POST` -* URL: `https://api.hellotext.com/v1/messages` -* Header: `Authorization: Bearer YOUR_TOKEN` -* Body: `form-data` +You can review the customer profile conversation in Inbox or query [the message list in the API](https://www.hellotext.com/api#list_all_messages). The reference also lets you retrieve a specific message once you know its identifier. -Then add these fields to the body. For example: +## 5. Test the complete flow -* `body`: `Hello, this is an SMS sent from Postman.` -* `destination`: `+573176655211` -* `technology`: `sms` +Before enabling the send in production: -You can also use this header as an example: +1. Send a message to a test number controlled by your team. +2. Confirm that the API responds with `status: received`. +3. Check that the SMS appears in the correct conversation and reaches the phone. +4. Review the final message state. +5. Test an invalid phone number and invalid token to verify how your integration records errors. -* Header `Authorization`: `Bearer YOUR_TOKEN` +Do not interpret a successful response as final delivery. Keep the result of each attempt and avoid automatically sending the same message again when a request has an uncertain outcome. The endpoint does not accept an idempotency key, so your system must prevent duplicates when retrying. -## Pricing, length, and encoding +## Messages with links -Sending rates depend on your configuration and destination. You can learn more in the [pricing section](https://www.hellotext.com/precios). +Do not paste a long URL directly if you want Hellotext to generate a tracked short link. Use this syntax inside `body`: -By default, SMS messages use `GSM-7 Latin` encoding and each message has a `160` character limit. +```text +Track your order here: {shortlink:https://shop.example.com/orders/123} +``` -If you go over that limit, Hellotext automatically concatenates the content into an additional message and the cost is billed as two SMS messages. +Hellotext replaces the instruction during processing. If the business uses its own short-link domain, see [Set up a custom domain for short links]({% link _integrations/custom-domain-for-short-links.md %}). To understand how the session is preserved after a click, read [Track campaign, route, and playbook links]({% link _developers/tracking-on-campaigns-and-journeys.md %}). -If the text includes characters that are not compatible with `GSM-7`, such as emojis, Hellotext will automatically try to use `UCS-2` encoding. This mode is available in Colombia. +## When to use a template -When a message uses `UCS-2`, the maximum length is reduced to `80` characters per message. +For reusable content, property-based personalization, or named dynamic links, you can send a template identifier instead of `body`. When you send `template`, Hellotext uses that template's content and ignores `body`. -## Add shortlinks inside the message +Templates with dynamic links require you to send their URLs under `template.shortlinks`. The [message sending reference](https://www.hellotext.com/api#create_a_message) contains the complete structure. -You can generate a short link directly inside the message text using the `{shortlink:URL}` syntax. +## Length, encoding, and cost -For example: +The character capacity of one SMS segment depends on its encoding: -```text -Learn more here {shortlink:https://www.tunegocio.com} -``` +- 7-bit GSM: up to 160 characters in a single segment; +- Latin-1: up to 140 characters in a single segment; and +- UCS-2: up to 70 characters in a single segment. + +Special characters and emoji can change the encoding. Long messages can be split into multiple billable SMS segments, and part of each segment is used to concatenate them. Do not estimate cost from character count alone without considering encoding. + +Pricing also depends on the destination country, plan, and included SMS messages. See [SMS pricing and number types]({% link _billing/sms-pricing-and-number-types.md %}) to estimate a send. + +## Consent and sending limits + +The API does not replace consent rules. Before sending: + +- verify that the customer can receive that type of communication; +- do not send promotional messages to profiles that are not subscribed or have opted out; +- include the appropriate opt-out mechanism when required; and +- follow the laws and sending hours that apply in the destination country. -Hellotext will replace that instruction with a short link when the message is sent. +See [Who can you message?]({% link _audience/consent-and-subscriber-status.md %}) to distinguish identity, verification, and subscription. [SMS sending limits for new businesses]({% link _troubleshooting-deliverability/sms-sending-limits-for-new-businesses.md %}) also apply to messages initiated through the API. -If you want to use your own short link domain, see the [custom domain for short links guide]({% link _integrations/custom-domain-for-short-links.md %}). +## Common errors -## Customer profiles +- **`401 Unauthorized`:** the token is missing, invalid, or has been replaced. +- **`422 Request Failed`:** check the phone number, `body`, `profile`, `technology`, and SMS availability for the business. Correct the request before retrying. +- **Server errors:** record the response and retry with progressive backoff. Protect the flow against duplicate sends. +- **The request was accepted, but the message fails:** check the message state, phone number, account limits, and channel availability. -You do not need to create a profile in advance to make a one-off send to a number using `destination`. +The [API errors section](https://www.hellotext.com/api#errors) explains the response format. -However, if you also want to keep customer profile history, segment audiences, or reuse that data in campaigns, playbooks, or routes, you can: +## Related guides -* Import customer profiles from the Hellotext interface. -* Create profiles programmatically with the [API reference for creating profiles](https://www.hellotext.com/api#create_a_profile). +- [Integrate a custom store]({% link _developers/custom-store-integration.md %}) +- [Hellotext API reference](https://www.hellotext.com/api) +- [Tracking events]({% link _developers/tracking-events.md %}) +- [Tracked links and short-link domains]({% link _analytics-reporting-attribution/tracked-links.md %}) diff --git a/_i18n/en/developers/tracking-events.md b/_i18n/en/developers/tracking-events.md index 67678e76..c14fdc2d 100644 --- a/_i18n/en/developers/tracking-events.md +++ b/_i18n/en/developers/tracking-events.md @@ -1,109 +1,166 @@ -Tracking events turns customer behavior into signals Hellotext can use across customer profiles, segments, attribution, playbooks, and the Inbox. Signals can come from your eCommerce site, physical store, custom backend, forms, conversations, or any other source that matters to your business. +Event tracking turns customer activity into signals that Hellotext can use in customer profiles, segments, attribution, playbooks, journeys, and Inbox. -Those signals help Hellotext decide when to trigger a playbook, update a segment, enrich a customer profile, support an agent, or attribute revenue to the right action. +Signals can come from an integration, Hellotext.js, your backend, a physical store, forms, conversations, or Hellotext's internal actions. You do not need to track every signal manually or implement every available event. -For the broader product concept, start with [What are signals?]({% link _journeys/what-are-signals.md %}). +For the general product concept, start with [What are signals?]({% link _journeys/what-are-signals.md %}). -If events are not appearing where expected, use [Troubleshoot missing signals or activity]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}) to check identity, action names, integrations, triggers, and reports. +## Signals, actions, events, and objects -## Understanding Actions +These terms describe different parts of the same flow: -Actions are the generic activities that your customers do. +- A **signal** is information Hellotext can interpret when making decisions. +- An **action** defines what happened, such as `product.viewed` or `order.delivered`. +- An **event** is one occurrence of that action for a customer or session at a specific time. +- An **object** provides related context, such as the product, cart, order, coupon, or form. -They are grouped by their kind of action and separated by a dot. +For example, this event says that one customer profile viewed a specific product: -For example: +```json +{ + "action": "product.viewed", + "profile": "PROFILE_ID", + "object": "PRODUCT_ID", + "tracked_at": "2026-08-07T12:30:00Z" +} +``` -### Cart actions +The action alone is not always enough. `product.viewed` needs the viewed product, and order actions need the corresponding order. -* `cart.abandoned` A cart was abandoned. -* `cart.added` Added an item to the cart. -* `cart.removed` Removed an item from the cart. +Most built-in actions use the `object.verb` format. `subscribed` and `unsubscribed` are current exceptions and must not be renamed by adding a prefix. -### Order actions +## Built-in actions for integrations -* `order.placed` Order has been placed. -* `order.confirmed` Order has been confirmed by you. -* `order.cancelled` Order has been cancelled either by you or your customer. -* `order.shipped` Order has been shipped to your customer. -* `order.delivered` Order has been delivered to your customer. +These are the actions an integration can normally track. Use only the actions that represent real activity in your system. -### Product actions +### Subscription -* `product.purchased` A product has been purchased. -* `product.viewed` A product page has been viewed. +- `subscribed`: the customer gave consent and subscribed through a compatible channel. +- `unsubscribed`: the customer withdrew consent or opted out. -### Coupon actions +Do not use `subscribed` simply because you created a customer profile. See [Who can I message?]({% link _audience/consent-and-subscriber-status.md %}). -* `coupon.redeemed` A coupon was redeemed by a customer. +### Pages and products -### Refund actions +- `page.viewed`: the customer viewed a page. +- `product.viewed`: the customer viewed a specific product. +- `product.purchased`: the customer purchased a product outside a more complete order lifecycle. -* `refund.requested` A customer requested a refund. -* `refund.received` A refund was issued by you to your customer. +Hellotext.js automatically tracks `page.viewed` with the current URL. A page view does not identify the product by itself, so `product.viewed` must explicitly include the corresponding product. -### Page views actions +If your store uses orders, prefer order actions instead of also tracking `product.purchased` for the same purchase. -* `page.viewed` A page was viewed by a customer. +### Carts and checkout -### App actions +- `cart.viewed`: the customer viewed their cart. +- `cart.added`: a product was added to the cart. +- `cart.removed`: a product was removed from the cart. +- `cart.abandoned`: the store determined that the cart was abandoned. +- `checkout.started`: the customer started checkout. -* `app.install` An app was installed. -* `app.remove` An app was removed. -* `app.spent` A customer spent on an app. +Do not send `cart.abandoned` simply because the customer left a page. Track it when your store or integration has actually determined that the cart was abandoned. -### Form actions +### Orders -* `form.completed` A form was completed by the customer. +- `order.placed`: the customer created the order. +- `order.confirmed`: the business confirmed the order. +- `order.cancelled`: the order was cancelled. +- `order.shipped`: the order left for delivery. +- `order.delivered`: delivery was confirmed. -### Custom actions +Track each change when it happens and reuse the same order object. Do not send every state together when the order is created. -You can create custom actions from **Settings → Actions → Custom** or through the API. For example: +### Coupons, refunds, and forms -* `signup_form.completed` -* `physical_store.paid` -* `event.attendance` +- `coupon.redeemed`: the customer redeemed a coupon. +- `refund.requested`: the customer requested a refund. +- `refund.received`: the business completed the refund. +- `form.completed`: the customer completed a form. -Learn more on the **[API Reference for Actions](https://www.hellotext.com/api#actions)**. +### Apps -A custom event with a positive monetary amount can be evaluated for attribution when Hellotext can identify the customer and find eligible source and timing evidence. Creating a custom action by itself does not make its revenue attributed. See [How we attribute sales]({% link _analytics-reporting-attribution/sales-attribution.md %}). +- `app.installed`: the customer installed an app. +- `app.removed`: the customer removed an app. +- `app.spent`: the customer made a purchase associated with an app. -## Understanding Events +The correct names are `app.installed` and `app.removed`. Do not use the old `app.install` or `app.remove` variants. -An event is the object that creates a relationship between an action and a customer profile at a particular time. +## Actions generated by Hellotext -It is created when you track an action from a customer and becomes part of the signal history Hellotext can use later. +Hellotext also creates internal signals for messages, conversations, segments, short links, customer profile changes, and playbook decisions. Some actions, such as `product.browse_abandoned`, `product.price_changed`, or `order.printed_label`, belong to internal product processes. -## Ways to track events +Do not reproduce those actions manually or send them from your integration unless they are explicitly listed as supported in the [tracking API reference](https://www.hellotext.com/api#tracking). Duplicating them can trigger automations or affect reporting incorrectly. -* Using one of the integrations like Mercado Libre. -* Using Javascript. -* Using the API. +## Custom actions -You can also use **New Event** on a customer profile to record one occurrence manually. This does not configure automatic tracking for future occurrences. +When no built-in action represents what happens in your business, create a custom action from **Settings → Actions → Custom** or through the API. -## Tracking with Integrations +Use a stable, descriptive name, for example: -### Mercado Libre +- `appointment.completed` +- `store_visit.completed` +- `membership.renewed` -If you sell on Mercado Libre you can track your customers' purchases automatically. +Do not generate a new name for each customer, order, or date. An action represents one reusable activity type, and each event represents one occurrence. -Simply connect your Mercado Libre account with just a few clicks and you will start tracking the following events immediately: +The custom action must exist before you track the first event. See [Create an action](https://www.hellotext.com/api#create_an_action). -* `order.confirmed` Order has been confirmed by you. -* `order.shipped` Order has been shipped to your customer. -* `order.cancelled` Order has been cancelled either by you or your customer. -* `refund.requested` A customer requested a refund. -* `refund.received` A refund was issued by you to your customer. +A custom event with a positive monetary amount can be evaluated for attribution when Hellotext identifies the customer and finds eligible source and timing evidence. Creating the action does not automatically turn its amount into attributed revenue. See [How we attribute sales]({% link _analytics-reporting-attribution/sales-attribution.md %}). -## Tracking events programmatically +## How events reach Hellotext -### Tracking with Javascript +### Integrations -To track client side events you can use the **[Hellotext.js](https://github.com/hellotext/hellotext.js)** javascript library. +eCommerce, channel, and other platform integrations can create customer profiles, objects, and events automatically. Review what each integration provides and do not send the same events again from your code. -Please refer to the Github repository at **[hellotext/hellotext.js](https://github.com/hellotext/hellotext.js)** to see the latest installation and configuration instructions. +See [Setup and integrations]({% link _integrations/setup-overview.md %}) and [Verify your data and signals after setup]({% link _integrations/verify-data-and-signals.md %}). -### Tracking using the API +### Hellotext.js -Learn more on **[API Reference for Tracking](https://www.hellotext.com/api#tracking)**. +Use Hellotext.js for activity that happens in the browser, such as page views, product views, and cart changes. The library includes the current session to preserve anonymous context. + +See the [Hellotext.js repository](https://github.com/hellotext/hellotext.js) for current instructions. + +### API + +Use the API from your backend for trusted events such as orders, payments, cancellations, shipments, deliveries, and external-system activity. + +- For a complete implementation, see [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}). +- To send events from the backend, see [External tracking]({% link _developers/external-tracking.md %}). +- To associate anonymous activity, see [Tracking unidentified customers]({% link _developers/tracking-unidentified-customers.md %}). + +### Manual tracking + +You can also use **New event** inside a customer profile to record one manual occurrence. This does not configure automatic tracking for future events. + +## Data each event should preserve + +Before implementing an action, define: + +- **Identity:** the known customer profile or anonymous session. +- **Object:** the related product, cart, order, or other object. +- **Time:** the actual event time through `tracked_at` when it is not happening in real time. +- **Value:** `amount` and `currency` when the action has a monetary value. +- **Source:** the integration or system that produced the activity. + +Use stable identifiers and do not send the same event from multiple sources. + +## Verify tracking + +Test with one recognizable customer first: + +1. Confirm that the event appears on the correct customer profile. +2. Check that the action uses the exact name. +3. Confirm that the related object is the expected product, cart, or order. +4. Check that the timestamp represents when the activity happened. +5. Confirm that the integration did not already create the same event automatically. +6. Review segments, playbooks, and reports only after validating the underlying data. + +If events do not appear where expected, use [Troubleshoot missing signals or activity]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}). + +## Related guides + +- [What are signals?]({% link _journeys/what-are-signals.md %}) +- [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) +- [External tracking]({% link _developers/external-tracking.md %}) +- [Custom properties and events]({% link _audience/custom-properties-and-events.md %}) +- [How we attribute sales]({% link _analytics-reporting-attribution/sales-attribution.md %}) diff --git a/_i18n/en/developers/tracking-on-campaigns-and-journeys.md b/_i18n/en/developers/tracking-on-campaigns-and-journeys.md index 8d10a119..dae98d35 100644 --- a/_i18n/en/developers/tracking-on-campaigns-and-journeys.md +++ b/_i18n/en/developers/tracking-on-campaigns-and-journeys.md @@ -1,72 +1,126 @@ -After sending a campaign, activating a route, or enabling a playbook, you will want to learn how customers engaged and behaved. Ideally, you also want to keep that behavior as signals Hellotext can reuse later. +Tracked links connect a click with the message that created it, the customer profile, a session, reporting, and later activity on your site. -This is the purpose of tracking links and events: connect each click back to a customer profile, session, report, and future decision. +Hellotext can create these links in campaign, journey, playbook, and Inbox messages. For the context to continue after the redirect, the destination site must preserve the session and track later activity correctly. -## Short links and sessions +## What Hellotext does when the customer clicks -A short link is simply a way to reduce the length of a URL to something that looks like `hello.link/3lsnvh`. +When you add a link with the editor tool, Hellotext generates a short URL such as `hello.link/XXXXXX` or uses the custom domain configured by the business. -This helps you overcome the 160-character limit of text messages, leaving more space for the message. On text messages, shorter links also feel more inviting. +When the customer clicks, Hellotext: -You can share shortened links in campaign, route, playbook, and Inbox messages. +1. Tracks the `short_link.clicked` action for the customer profile and corresponding message. +2. Updates the link click count and available reports. +3. Preserves the campaign, broadcast, journey, step, or playbook context that created the message. +4. Redirects the customer to the original URL. +5. Adds a session and UTM parameters to the destination URL. -When customers click on a short link they are redirected to the original URL. Hellotext attaches a GET parameter to the original URL called `hellotext_session` containing a session identifier uniquely generated for each click. +Hellotext filters previews it identifies as bots so they are not counted as customer clicks. Even so, a recorded click represents an interaction, not a purchase or guaranteed conversion. -Every time a customer clicks on a short link, an event is created and appears in the customer profile activity. Clicks can also be aggregated in campaign, route, or playbook reports when that report is available. +Do not send `short_link.clicked` manually from your integration. Hellotext creates it when processing the link click. -An eligible click can provide active attribution evidence and normally opens a seven-day window from the click. It is not the only attribution path: eligible delivery or other passive evidence can apply within the default 24-hour window. See [How we attribute sales]({% link _analytics-reporting-attribution/sales-attribution.md %}). +## Parameters received by the destination site -## Getting started tracking +The redirected URL can look like this: -If your site runs with any of the platforms we already offer integration support, you can connect it to start tracking events automatically. +```text +https://shop.example.com/products/everyday-sneakers?hello_session=SESSION_ID&utm_source=hellotext&utm_medium=sms&utm_campaign=CAMPAIGN_ID +``` -If your integration is not yet supported or if you have your own custom implementation, you can start tracking events by installing the [**Hellotext.js**](https://github.com/hellotext/hellotext.js) library. +The parameters have different purposes: -### Setup the library on your site +- `hello_session` preserves the session associated with the link and connects later activity. +- `utm_source` identifies the traffic source; its value is normally `hellotext`. +- `utm_medium` identifies the channel when available. +- `utm_campaign` identifies the campaign, journey, or playbook when applicable. -Begin by installing the library. +The current parameter is `hello_session`. Do not use or look for `hellotext_session`. -```bash -npm install @hellotext/hellotext -``` +If the original URL already contains parameters, Hellotext preserves them and adds its own. Do not remove `hello_session` or the UTM parameters in an intermediate redirect. -Import the library into your app. +## How the session continues on the site -```javascript -import Hellotext from "@hellotext/hellotext"; -``` +Hellotext.js reads `hello_session` from the URL, retains the session in the browser, and includes it with later activity. -Initialize the library passing the public `HELLOTEXT_BUSINESS_ID` identifier that represents the business. +Initialize Hellotext.js before your router or storefront code removes URL parameters. In a single-page application, preserve the query string during the initial load. -You can find it from the Business's settings page. +You can inspect the session after the library initializes: ```javascript -Hellotext.initialize("HELLOTEXT_BUSINESS_ID"); +if (Hellotext.isInitialized) { + console.log(Hellotext.session) +} ``` -## Tracking client-side events +Hellotext.js automatically tracks `page.viewed` with the current URL. If the page represents a product, also track `product.viewed` and explicitly include the product. The URL alone does not provide all catalog information. -Tracking events is straightforward and perhaps the simplest example is tracking a page view: +See [Tracking unidentified customers]({% link _developers/tracking-unidentified-customers.md %}) for the complete session and identity lifecycle. -```javascript -Hellotext.track("page.visited"); -``` +## Context by message source -Please refer to the [**library usage documentation**](https://github.com/hellotext/hellotext.js#usage) for a complete reference on all the actions and attributes available. +The same mechanism preserves different references depending on where the message was created: -## Tracking server-side events +- **Campaign:** the click is related to the campaign, broadcast, and sent message. +- **Journey:** the click is related to the journey, step, and executed message. +- **Playbook:** the click is related to the playbook and generated or sent message. +- **Inbox:** the click remains in customer and conversation activity even when there is no campaign or automation report. -Sometimes you may want to track events that happened outside the browser, for example you may want to track events directly on the server-side of your system, or at a time when the customer may not be present. +Do not manually reuse a personalized message link for other customers or sends. Add the destination through the editor link tool and let Hellotext generate the correct context for each message. -This is possible by capturing the session identifier and storing it on your system to use it later when you want to track an event associated with this session. +## How later events are connected -To obtain the current session, simply call `Hellotext.session`: +A click is only the beginning of the session. To understand what happened next, the site or backend must track the relevant actions: -```javascript -Hellotext.session -// Returns bBJn9vR15yPaYkWmR2QK0jopMeNxrA6l -``` +- Hellotext.js tracks navigation, product views, and cart changes. +- Your backend tracks trusted orders, payments, cancellations, shipments, and deliveries. +- When the customer becomes known, the session must be associated with the correct customer profile. + +If checkout happens on another domain or application, send the `Hellotext.session` ID to your backend before losing the context. You can then track the order with the corresponding customer profile or session. + +Do not send the same event from Hellotext.js and the backend. See [Tracking events]({% link _developers/tracking-events.md %}) and [External tracking]({% link _developers/external-tracking.md %}). + +## Clicks, reporting, and attribution + +Clicks can appear in customer profile activity and in campaign, journey, or playbook reports when that report is available. + +An eligible click can provide active attribution evidence and normally opens a seven-day window from the click. An eligible delivery or another passive signal can apply within the default 24-hour window. These windows can be configured by account. + +The click does not guarantee that a purchase will be attributed to that source. Hellotext also evaluates: + +- Whether the customer and order are identified correctly. +- Whether the purchase occurs inside the applicable window. +- Whether the campaign, journey, playbook, or delivery is eligible. +- Whether another valid source has higher precedence. + +See [How we attribute sales]({% link _analytics-reporting-attribution/sales-attribution.md %}) for complete windows, precedence, and examples. + +## Verify the implementation + +Test with a recognizable customer profile and message: + +1. Create a tracked link through the editor. +2. Send the test message and open the link as the customer would. +3. Confirm that the destination URL includes `hello_session` and the expected UTM parameters. +4. Verify that `Hellotext.session` matches the received session. +5. Confirm that the click appears in customer profile activity. +6. Review the campaign, journey, or playbook report when available. +7. Track a test product view, cart, or order and confirm that it preserves the correct customer and source. +8. Confirm that the same activity was not tracked twice. + +## Troubleshoot common problems + +- **The click appears, but later activity does not:** confirm that the site preserves `hello_session` until Hellotext.js initializes. +- **The session changes when the customer reaches the site:** review redirects, domains, cookies, and Hellotext.js initialization order. +- **The page view appears without a product:** track `product.viewed` with the corresponding product. +- **The click does not appear in the report:** verify that the link was created in the correct message and was not a preview detected as a bot. +- **The purchase is not attributed:** review identity, order, timestamp, window, and source precedence. + +If signals are missing, use [Troubleshoot missing signals or activity]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}). -You can then track events sending a `POST` request directly to the API. +## Related guides -Learn more: [**External tracking**]({% link _developers/external-tracking.md %}). +- [Tracked links]({% link _analytics-reporting-attribution/tracked-links.md %}) +- [Message editor overview]({% link _numbers/message-editor-overview.md %}) +- [Tracking unidentified customers]({% link _developers/tracking-unidentified-customers.md %}) +- [External tracking]({% link _developers/external-tracking.md %}) +- [How we attribute sales]({% link _analytics-reporting-attribution/sales-attribution.md %}) +- [Custom domain for short links]({% link _integrations/custom-domain-for-short-links.md %}) diff --git a/_i18n/en/developers/tracking-unidentified-customers.md b/_i18n/en/developers/tracking-unidentified-customers.md index d7f3fe40..d577fba5 100644 --- a/_i18n/en/developers/tracking-unidentified-customers.md +++ b/_i18n/en/developers/tracking-unidentified-customers.md @@ -1,71 +1,150 @@ -Sometimes you may want to start tracking events from new visitors to your site who have not been identified and can't be associated on Hellotext yet. +Hellotext can track a visitor's activity before knowing who they are. Hellotext.js creates or reuses an anonymous session and includes it with browser activity. When the visitor becomes a known customer, you can associate that session with their customer profile to preserve the complete history. -To help you start collecting events for them, the [**Hellotext.js**](https://github.com/hellotext/hellotext.js) library creates a new session identifier for every new visitor when it is not already set. +The session, customer profile, and consent are separate concepts: -You can store this session identifier and later attach it to the profile when it becomes known, for example when the visitor registers or logs into the site. +- The **session** connects activity from one browser. +- The **customer profile** brings together known identity, properties, conversations, and signals. +- **Consent** determines whether you can send messages through a channel. Identifying the customer does not automatically make them a subscriber. -Assuming you have the [**Hellotext.js**](https://github.com/hellotext/hellotext.js) already installed and configured, to obtain the current session, simply call the method `Hellotext.session`: +If you are connecting a custom store from the beginning, start with [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}). + +## 1. Get the anonymous session + +Hellotext.js looks for an existing session in the URL or browser. If none exists and automatic generation is enabled, it creates a new one. + +After Hellotext.js initializes, read the current session: ```javascript -Hellotext.session -// Returns bBJn9vR15yPaYkWmR2QK0jopMeNxrA6l +if (Hellotext.isInitialized) { + const sessionId = Hellotext.session +} ``` -Keep this value on your system as you will need to send it back using the API when the profile becomes known. +If the library has not finished initializing, `Hellotext.session` can be `undefined`. You can listen for the session to become available: + +```javascript +Hellotext.on('session-set', sessionId => { + console.log('Hellotext session:', sessionId) +}) +``` + +Hellotext.js automatically includes the session when it tracks activity. Store the ID in your backend only when you need to associate it with a known customer later. Never send the private API token to the browser. + +See [Sessions in Hellotext.js](https://github.com/hellotext/hellotext.js/blob/main/docs/sessions.md) for current initialization options and library events. -## Attach session to an existing profile +## 2. Identify the customer at the right moment -Once the visitor becomes known, for example after they log into your site, you should make an API request to associate the unidentified session with their customer profile. +Associate the session when your application can reliably recognize the customer, for example: -Once the session is associated, all tracked events associated with the session will become part of the customer profile. +- After a successful login. +- After registration is complete and the account has been created. +- During checkout, when the backend creates or finds a reliable customer profile. -The following example uses ruby's [**HTTParty**](https://github.com/jnunemaker/httparty) library. This may vary depending on the programming language, but the nature of the request remains the same. +Do not identify someone only because they entered an email address or phone number in a field that has not been confirmed. Do not mark the customer profile as subscribed unless you have valid consent for the relevant channel. -When making a request to the API make sure to authenticate by setting the `Authorization` header with the bearer token as the example. You can create an authorization token from the Tokens section in the business Settings. +In a single-page application, wait until the authentication state is known before associating the session. This prevents the first browser activity from being attributed to the wrong customer. -```ruby -HTTParty.post "https://api.hellotext.com/v1/sessions/HELLOTEXT_SESSION_ID", - headers: { - "Authorization" => "Bearer ALK_eSMRuwJ2Al...", - "Content-Type" => "application/json" - }, - body: { - profile: "PROFILE_ID" - }.to_json +## 3. Attach the session from the backend + +This is the recommended method for a custom store because the backend controls identity and keeps the API token private. + +1. Read `Hellotext.session` in the browser. +2. Send the session ID to your backend with the customer's authenticated request. +3. Resolve the customer through your application's authentication session. Do not trust a customer profile ID supplied directly by the browser. +4. Create or find the Hellotext customer profile and retain its ID. +5. Attach the session with the private API token. + +If the customer profile does not exist yet, create it first through [Create a customer profile](https://www.hellotext.com/api#create_a_profile). Creating the profile does not establish consent. + +Attach the existing session: + +```bash +curl --request PATCH \ + --url https://api.hellotext.com/v1/sessions/HELLOTEXT_SESSION_ID \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "profile": "PROFILE_ID" + }' ``` -Replace the `HELLOTEXT_SESSION_ID` in the URL with the session identifier and `PROFILE_ID` with the existing profile identifier. +A valid request responds with HTTP `200` and the updated session object, including the associated customer profile. Earlier anonymous activity becomes part of the customer history; some data can finish associating in the background. + +See [Attach a session](https://www.hellotext.com/api#attach_session) for the complete endpoint contract. -If the request was made correctly the API should respond with a HTTP Status code of `201` and a JSON response similar to this: +## 4. Use browser identification only when necessary -```json -{ - "id": "WBAkaqNz", - "type": "session", - "profile": "MzYwlE50", - "created_at": 1665684173, +Hellotext.js provides `identify()` for compatible integrations that can only obtain identity in the browser: + +```javascript +const response = await Hellotext.identify('user_123', { + source: 'shopify', + email: 'ana@example.com', + name: 'Ana Silva', +}) + +if (response.failed) { + console.error(response.data) } ``` -## Attach session to new profile +Use the stable customer identifier from the source platform as the first argument. The `source` value must correspond to a source supported by Hellotext.js. For a custom store, prefer attaching the session from the backend; do not invent a `source` value. -If the profile doesn't already exist on Hellotext, you need to create it first. +After successful identification, Hellotext.js retains the identity in the browser and includes it with later activity. You do not need to call `identify()` on every page when the customer and submitted data have not changed. -We recommend reading the [**API reference for creating a profile**](https://www.hellotext.com/api#create_a_profile) to learn how to specify customer attributes. You may want to create the profile with as many attributes as you have of your customer. +Do not include a subscription state unless your application has valid evidence of consent. -```ruby -HTTParty.post "https://api.hellotext.com/v1/profiles", - headers: { - "Authorization" => "Bearer ALK_eSMRuwJ2Al...", - "Content-Type" => "application/json" - }, - body: { - first_name: "John", - last_name: "Smith" - phone: "+59899000001" - }.to_json +## 5. Forget the identity on logout + +When the customer logs out of your application, call: + +```javascript +Hellotext.forget() ``` -The response will return the identifier of the profile. +This removes the identity persisted by `identify()` from the browser but keeps the Hellotext session active. It does not delete the customer profile, history, or consent, and it does not undo a previous backend attachment. + +If several accounts can use the same browser, your backend must verify every login transition. Do not attempt to move a session that already belongs to a different customer profile. + +## 6. Handle sessions that already have a customer + +A session can be attached to the same customer profile again, but it must not be reused for another customer. Before treating the attachment as successful, inspect the `profile` field in the response. + +If the session already belongs to another customer profile: + +- Do not reassign the earlier activity to the current customer. +- Stop the attachment process and investigate why the session was shared. +- Confirm that `Hellotext.forget()` runs on logout when using `identify()`. +- Review your application's session lifecycle before tracking more authenticated events. + +When you send `profile` and `session` together while tracking an event, both must belong to the same customer. See [External tracking]({% link _developers/external-tracking.md %}) for that validation. + +## 7. Verify the complete flow + +Test with one recognizable customer: + +1. Open the storefront while logged out and confirm that Hellotext.js has a session. +2. Track anonymous activity, such as a product view or cart update. +3. Log in or complete checkout. +4. Create or find the correct Hellotext customer profile. +5. Attach the session from the backend. +6. Confirm that the response contains the expected customer profile. +7. Verify that earlier activity and new events appear on that customer profile. +8. Log out and confirm that your application calls `Hellotext.forget()` if it used `identify()`. + +## Troubleshoot common problems + +- **The session is `undefined`:** wait for Hellotext.js to initialize or listen for `session-set`. +- **The API responds with `401`:** check the private token and `Authorization` header. +- **The API responds with `404`:** the session might not exist for that business or might not have been sent to Hellotext through browser activity yet. +- **The response shows another customer profile:** treat it as an identity conflict and stop tracking authenticated events with that session. +- **Earlier activity does not appear immediately:** attachment can finish in the background; allow it to process and check again. + +If signals are still missing, use [Troubleshoot missing signals or activity]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}). + +## Related guides -Use this profile identifier now to attach the session to following the instructions described on *Attach session to an existing profile*. \ No newline at end of file +- [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) +- [External tracking]({% link _developers/external-tracking.md %}) +- [Tracking events]({% link _developers/tracking-events.md %}) +- [Who can I message?]({% link _audience/consent-and-subscriber-status.md %}) diff --git a/_i18n/en/getting-started/implementation-paths.md b/_i18n/en/getting-started/implementation-paths.md index 778e416f..2dcec6c9 100644 --- a/_i18n/en/getting-started/implementation-paths.md +++ b/_i18n/en/getting-started/implementation-paths.md @@ -96,6 +96,7 @@ Use this path when your data source is custom, your checkout is not covered by a Start here: +- [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) - [Developers and API overview]({% link _developers/developers-overview.md %}) - [Tracking events]({% link _developers/tracking-events.md %}) - [Tracking unidentified customers]({% link _developers/tracking-unidentified-customers.md %}) diff --git a/_i18n/es.yml b/_i18n/es.yml index cd2ab502..d50d1a7c 100644 --- a/_i18n/es.yml +++ b/_i18n/es.yml @@ -16,7 +16,7 @@ campaigns: description: Planifica, envía y mide mensajes puntuales a audiencias seleccionadas. audience: title: Audiencia y segmentación - description: Organiza perfiles de cliente, crea segmentos y llega a los clientes correctos. + description: Organiza perfiles de clientes, crea segmentos y llega a los clientes correctos. analytics-reporting-attribution: title: Analítica, reportes y atribución description: Entiende rendimiento, reportes de campañas, ingresos atribuidos y reglas de medición. @@ -28,7 +28,7 @@ numbers: description: Configura SMS y WhatsApp antes de enviar o recibir mensajes de clientes. developers: title: Desarrolladores y API - description: Usa la API, Hellotext.js, eventos de tracking e integraciones personalizadas. + description: Usa la API, Hellotext.js, seguimiento de eventos e integraciones personalizadas. troubleshooting-deliverability: title: Solución de problemas y entregabilidad description: Resuelve problemas comunes de configuración, envíos, tracking y reportes. diff --git a/_i18n/es/analytics-reporting-attribution/tracked-links.md b/_i18n/es/analytics-reporting-attribution/tracked-links.md index 31b63a2d..7c534e02 100644 --- a/_i18n/es/analytics-reporting-attribution/tracked-links.md +++ b/_i18n/es/analytics-reporting-attribution/tracked-links.md @@ -7,7 +7,7 @@ y se encuentra en la barra de herramientas del editor. Los links tienen la siguiente estructura: `hello.link/XXXXXX` donde `XXXXXX` es el identificador único del link. -Cuando alguien hace clic, Hellotext redirige al cliente a la URL especificada al crear el link y adjunta un identificador `hellotext_session` +Cuando alguien hace clic, Hellotext redirige al cliente a la URL especificada al crear el link y adjunta un identificador `hello_session` a la URL. Este identificador se usa para identificar la sesión y puede usarse para rastrear acciones realizadas por el cliente como señales. Puedes ver nuestra librería de JavaScript para ayudarte con eventos relacionados al tracking. diff --git a/_i18n/es/developers/custom-store-integration.md b/_i18n/es/developers/custom-store-integration.md new file mode 100644 index 00000000..0cebe2f8 --- /dev/null +++ b/_i18n/es/developers/custom-store-integration.md @@ -0,0 +1,382 @@ +Usa esta guía cuando tu tienda no tenga una integración nativa con Hellotext y tu equipo necesite conectarla mediante la API y Hellotext.js. + +La implementación tiene dos partes: + +- **Tu backend** usa un token de autorización privado para crear y actualizar perfiles de clientes, propiedades, productos, pedidos y eventos confiables desde el servidor. +- **Tu tienda** usa el Business ID público con Hellotext.js para crear sesiones de visitantes y registrar actividad del navegador, como vistas de páginas, vistas de productos y cambios en el carrito. + +> **Mantén las credenciales separadas:** el token de autorización de la API pertenece únicamente al servidor. Nunca lo incluyas en el código del navegador. El Business ID que usa Hellotext.js es el identificador público destinado a la tienda. + +Esta guía presenta el orden de implementación recomendado. Usa la [referencia de la API]({% link _developers/api.md %}) para consultar el contrato completo de requests y respuestas de cada endpoint. + +## Antes de comenzar + +Prepara: + +- Acceso como Propietario o Administrador al negocio de Hellotext. +- Acceso al backend y al código de la tienda. +- Identificadores estables de clientes, productos, carritos y pedidos en tu sistema. +- La moneda, estructura de productos y estados de pedidos que usa la tienda. +- Un registro claro del consentimiento. Crear un perfil del cliente no demuestra que haya aceptado recibir mensajes. + +Elige un nombre de origen consistente, como `custom_store`, y reutilízalo para productos, carritos, pedidos e identidad en el navegador. No cambies este valor entre requests. + +## 1. Crea un token de autorización para la API + +1. En Hellotext, abre **Configuración → Tokens de autorización**. +2. Selecciona **Crear nuevo token** y asígnale un nombre que identifique la integración. +3. Copia el token cuando Hellotext lo muestre. No podrás volver a verlo. +4. Guárdalo en el gestor de secretos o entorno de tu backend como `HELLOTEXT_API_TOKEN`. + +Prueba el token desde tu servidor: + +```bash +curl --request GET \ + --url https://api.hellotext.com/v1/profiles \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" +``` + +Una respuesta exitosa confirma que el token pertenece al negocio esperado. Una respuesta `401` normalmente indica que el token falta, es inválido o fue revocado. + +Consulta [Autenticación en la API de Hellotext](https://www.hellotext.com/api#authentication) para ver el formato del encabezado y las respuestas posibles. + +## 2. Crea las definiciones de propiedades necesarias + +Hellotext ya incluye nombre y apellido como datos estándar del perfil del cliente, además de propiedades para teléfono, email, dirección, empresa, género y cumpleaños. Usa esos campos incorporados en lugar de volver a crearlos como propiedades personalizadas. + +Crea las propiedades adicionales que necesite el perfil del cliente para representar datos propios de tu negocio, como un identificador de fidelidad, tienda preferida, nivel del cliente, talle o tipo de cuenta. + +Crea cada propiedad reutilizable una sola vez: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/properties \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "name": "ID del cliente", + "kind": "text", + "unique": true + }' +``` + +Guarda el `id` devuelto para la propiedad. Usarás ese ID cuando asignes un valor a un perfil del cliente. Elige el `kind` correcto antes de importar valores, porque determina cómo Hellotext valida, muestra y segmenta la propiedad. + +Consulta [Crear una propiedad en la API](https://www.hellotext.com/api#create_a_property) para ver todos los tipos, parámetros y opciones disponibles. Para conocer más sobre propiedades globales y específicas de un perfil del cliente, consulta [Propiedades y eventos personalizados]({% link _audience/custom-properties-and-events.md %}). + +## 3. Crea o sincroniza perfiles de clientes + +Crea un perfil del cliente con los identificadores y atributos que ya conoces: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/profiles \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "first_name": "Ana", + "last_name": "Silva", + "email[primary]": "ana@example.com", + "phone[mobile]": "+59899000001", + "property_by_id[PROPERTY_ID]": "customer-4821" + }' +``` + +La respuesta incluye el `id` del perfil del cliente en Hellotext. Guárdalo junto al registro del cliente en tu sistema y úsalo para actualizaciones y eventos posteriores desde el servidor. + +Hellotext puede encontrar un perfil del cliente existente por teléfono o email cuando lo creas o actualizas. Aun así, tu integración debería conservar el ID devuelto por Hellotext y actualizar el perfil del cliente existente en lugar de crear uno nuevo en cada sincronización. + +No marques perfiles de clientes importados como suscritos salvo que tengas consentimiento válido para el canal correspondiente. La creación del perfil del cliente, la identidad y el permiso para enviar mensajes son conceptos separados. Consulta [Crear un perfil del cliente en la API](https://www.hellotext.com/api#create_a_profile) para ver todos los campos disponibles y [¿A quién puedo escribirle?]({% link _audience/consent-and-subscriber-status.md %}) para entender cómo manejar el consentimiento. + +## 4. Sincroniza el catálogo de productos + +Crea los productos y variantes que Hellotext necesita para recomendaciones, actividad de productos, carritos, pedidos y playbooks: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/products \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "name": "Championes Everyday", + "reference": "product-100", + "sku": "SKU-100", + "source": "custom_store", + "url": "https://shop.example.com/products/everyday-sneakers", + "image_url": "https://shop.example.com/images/everyday-sneakers.jpg", + "price": { + "amount": 89.90, + "currency": "USD" + }, + "categories": ["Calzado"], + "tags": ["Uso diario"] + }' +``` + +Guarda el `id` devuelto para el producto. Usa ese ID al registrar vistas del producto y al agregarlo a carritos o pedidos. + +Mantén estables los valores de `source`, `reference` y SKU. Actualiza el producto existente cuando cambien su nombre, precio, imagen, URL, categorías, etiquetas, variantes u otros datos compatibles. No crees un producto nuevo en Hellotext durante cada sincronización del catálogo. + +Consulta [Crear un producto en la API](https://www.hellotext.com/api#create_a_product) para ver todos los datos compatibles del producto y sus variantes. + +## 5. Importa pedidos históricos + +Los pedidos históricos le dan contexto de compra a Hellotext antes de que llegue el primer evento en vivo. Cada pedido importado necesita: + +- Una referencia y un origen estables. +- El perfil correcto del cliente. +- Productos y cantidades. +- Monto total y moneda. +- La fecha original del evento. + +Primero crea el pedido y conserva el `id` devuelto: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/orders \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "reference": "ORDER-1001", + "source": "custom_store", + "delivery": "deliver", + "total": { + "amount": 89.90, + "currency": "USD" + }, + "items": [ + { + "product": "PRODUCT_ID", + "quantity": 1, + "price": { + "amount": 89.90, + "currency": "USD" + } + } + ] + }' +``` + +Luego registra el evento del pedido en el perfil del cliente. `tracked_at` es la fecha original del evento expresada como timestamp Unix: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "order.confirmed", + "profile": "PROFILE_ID", + "object": "ORDER_ID", + "amount": 89.90, + "currency": "USD", + "tracked_at": 1751328000 + }' +``` + +Usa el evento que refleje lo que realmente ocurrió, como `order.placed`, `order.confirmed`, `order.cancelled`, `order.shipped` u `order.delivered`. No inventes estados del ciclo del pedido que tu tienda no pueda verificar. + +Conserva las fechas originales durante la importación histórica. De lo contrario, compras antiguas pueden parecer actividad actual y distorsionar segmentos, elegibilidad de playbooks y reportes. + +Consulta [Crear un pedido](https://www.hellotext.com/api#create_an_order) y [registrar eventos de pedidos](https://www.hellotext.com/api#track_order_events) para ver todas las opciones disponibles. + +## 6. Instala Hellotext.js en la tienda + +Instala el paquete con npm: + +```bash +npm install @hellotext/hellotext +``` + +Impórtalo e inicialízalo una sola vez cuando arranca la tienda: + +```javascript +import Hellotext from '@hellotext/hellotext' + +Hellotext.initialize('HELLOTEXT_BUSINESS_ID') +``` + +El `HELLOTEXT_BUSINESS_ID` es el identificador público que aparece en la configuración del negocio de Hellotext. No es el token privado de autorización de la API. + +Para un sitio sin bundler de JavaScript, usa el script compilado: + +```html + + +``` + +Usa el [repositorio de Hellotext.js](https://github.com/hellotext/hellotext.js) para consultar instrucciones vigentes del paquete, frameworks, Formularios y Webchat. + +## 7. Registra actividad del navegador + +Hellotext.js crea la sesión del visitante y registra automáticamente `page.viewed` con la URL actual. No necesitas enviar ese evento manualmente. + +La vista de página no identifica por sí sola qué producto está viendo el cliente. En cada página de producto, incluye explícitamente el producto correspondiente. Si ya sincronizaste el catálogo, usa el ID que devolvió Hellotext: + +Registra la vista de un producto conocido: + +```javascript +await Hellotext.track('product.viewed', { + object: 'PRODUCT_ID', +}) +``` + +Si todavía no tienes el ID de Hellotext disponible en la tienda, puedes enviar los datos necesarios para crear o encontrar el producto. Mantén estables `reference` y `source` para no generar duplicados: + +```javascript +await Hellotext.track('product.viewed', { + object_parameters: { + name: 'Championes Everyday', + reference: 'product-100', + source: 'custom_store', + url: window.location.href, + image_url: 'https://shop.example.com/images/everyday-sneakers.jpg', + price: { + amount: 89.90, + currency: 'USD', + }, + }, +}) +``` + +Registra un producto agregado al carrito usando una referencia estable para el carrito: + +```javascript +const response = await Hellotext.track('cart.added', { + object_parameters: { + reference: 'CART-9001', + source: 'custom_store', + items: [ + { + product: 'PRODUCT_ID', + quantity: 1, + }, + ], + }, +}) + +if (response.failed) { + console.error(response.data) +} +``` + +Reutiliza la misma referencia del carrito para actividad posterior de `cart.added` y `cart.removed`. Registra `cart.abandoned` únicamente cuando tu tienda haya determinado que el carrito fue abandonado. + +Hellotext.js también puede registrar un pedido cuando la página de confirmación sea el único punto de integración disponible. Debes incluir explícitamente el pedido y sus productos: + +```javascript +await Hellotext.track('order.placed', { + amount: 89.90, + currency: 'USD', + object_parameters: { + reference: 'ORDER-1001', + source: 'custom_store', + items: [ + { + product: 'PRODUCT_ID', + quantity: 1, + }, + ], + }, +}) +``` + +Los eventos del navegador son apropiados para navegación y actividad del carrito. Siempre que sea posible, registra desde el backend los hitos confiables de compra y entrega para que un cliente no pueda simular pedidos llamando código del navegador. No envíes el mismo evento de pedido desde el navegador y el backend. + +Consulta [Seguimiento de eventos]({% link _developers/tracking-events.md %}) para la vista automática de páginas y [eventos de productos](https://www.hellotext.com/api#track_product_events), [eventos de carritos](https://www.hellotext.com/api#track_cart_events) y [eventos de pedidos](https://www.hellotext.com/api#track_order_events) para ver las acciones y parámetros compatibles. + +## 8. Conecta la actividad anónima con el cliente + +Hellotext.js comienza con una sesión anónima del visitante. Cuando inicia sesión, se registra o completa el checkout, conecta esa sesión con el perfil del cliente en Hellotext. + +El método recomendado es server-to-server: + +1. Lee `Hellotext.session` en el navegador. +2. Envía el ID de la sesión a tu backend junto con el cliente autenticado. +3. Adjunta la sesión al ID almacenado del perfil del cliente en Hellotext usando el token privado de la API. + +```bash +curl --request PATCH \ + --url https://api.hellotext.com/v1/sessions/HELLOTEXT_SESSION_ID \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "profile": "PROFILE_ID" + }' +``` + +Esto incorpora la actividad anónima anterior al perfil del cliente conocido. + +Para una tienda propia, no uses `identify()` con un valor de `source` inventado. Ese método se reserva para fuentes compatibles con Hellotext.js cuando no existe una alternativa server-to-server. Si una integración compatible usa `identify()`, debe llamar a `Hellotext.forget()` cuando el cliente cierre sesión. + +Consulta [Adjuntar una sesión en la API](https://www.hellotext.com/api#attach_session) para ver todos los parámetros y [Seguimiento de clientes no identificados]({% link _developers/tracking-unidentified-customers.md %}) para conocer el proceso completo, la alternativa con `identify()` y el cierre de sesión. + +## 9. Registra eventos confiables desde el backend + +Usa `POST /v1/attribution/events` para actividad que ocurre fuera del navegador o que debe ser confiable, incluyendo: + +- Creación y confirmación de pedidos. +- Eventos de pago o compra. +- Cancelación, envío y entrega. +- Actividad de tiendas físicas o marketplaces. +- Eventos creados por jobs, webhooks o sistemas internos. + +Envía el ID del perfil del cliente en Hellotext cuando conozcas al cliente o el ID de la sesión cuando solo tengas esa sesión. Incluye `tracked_at` cuando el evento haya ocurrido antes de enviar la request. + +Por ejemplo, registra `order.placed` cuando tu backend confirme que el pedido fue creado: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "order.placed", + "profile": "PROFILE_ID", + "object": "ORDER_ID", + "amount": 89.90, + "currency": "USD" + }' +``` + +Reutiliza el mismo `ORDER_ID` para `order.confirmed`, `order.shipped`, `order.delivered` o `order.cancelled` a medida que el pedido cambia de estado. Envía únicamente los eventos que tu backend pueda verificar. + +Consulta [Seguimiento en la API](https://www.hellotext.com/api#tracking), [eventos de pedidos](https://www.hellotext.com/api#track_order_events) y [Seguimiento de origen externo]({% link _developers/external-tracking.md %}) para ver todos los parámetros y más ejemplos desde el servidor. + +## 10. Verifica la integración completa + +Antes de habilitar playbooks o campañas, prueba un cliente reconocible de principio a fin: + +1. Crea o actualiza el perfil del cliente y confirma su teléfono, email y propiedades personalizadas. +2. Confirma que los IDs de productos y variantes correspondan con el catálogo de la tienda. +3. Abre la tienda y verifica que Hellotext.js cree una sesión. +4. Registra una vista de producto y una actualización del carrito. +5. Identifica al cliente o adjunta la sesión desde el backend. +6. Crea un pedido de prueba y registra su evento real desde el servidor. +7. Confirma que los eventos aparezcan en el perfil del cliente correcto y usen las fechas esperadas. +8. Revisa la actividad de playbooks y reportes únicamente cuando los perfiles de clientes, productos, carritos y pedidos sean correctos. + +Si faltan datos, usa [Soluciona señales o actividad faltante]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}). + +## Checklist antes de publicar + +- El token privado existe únicamente en los secretos del backend. +- Hellotext.js usa el Business ID público. +- Los mapeos de clientes, productos, carritos y pedidos usan IDs estables. +- Las actualizaciones de productos no crean registros duplicados en el catálogo. +- Los pedidos históricos conservan sus fechas y monedas originales. +- El seguimiento del navegador cubre navegación y actividad del carrito. +- El seguimiento desde el servidor cubre pedidos y eventos confiables de entrega. +- Las sesiones anónimas se adjuntan cuando se conoce al cliente. +- El cierre de sesión llama a `Hellotext.forget()` cuando se usa identificación en el navegador. +- El estado de suscripción se establece únicamente a partir de evidencia válida de consentimiento. + +## Guías relacionadas + +- [Resumen de desarrolladores y API]({% link _developers/developers-overview.md %}) +- [Seguimiento de eventos]({% link _developers/tracking-events.md %}) +- [Propiedades y eventos personalizados]({% link _audience/custom-properties-and-events.md %}) +- [Verifica tus datos y señales después de configurar]({% link _integrations/verify-data-and-signals.md %}) +- [Atribución de ventas]({% link _analytics-reporting-attribution/sales-attribution.md %}) diff --git a/_i18n/es/developers/developers-overview.md b/_i18n/es/developers/developers-overview.md index fd701e30..e7355228 100644 --- a/_i18n/es/developers/developers-overview.md +++ b/_i18n/es/developers/developers-overview.md @@ -1,11 +1,20 @@ Usa las guías para desarrolladores cuando necesites conectar Hellotext con tu sitio, backend, CRM, plataforma de comercio o herramientas internas. -La mayoría del trabajo técnico con Hellotext cae en cuatro áreas: +Si vas a conectar una tienda propia sin una integración nativa, comienza con [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}). Presenta perfiles, propiedades, productos, pedidos históricos, Hellotext.js, identidad y seguimiento desde el servidor en el orden de implementación correcto. +La mayoría del trabajo técnico con Hellotext cae en cinco áreas: + +- Integrar una tienda propia de principio a fin. - Leer la referencia de la API. - Enviar mensajes desde tu propio sistema. -- Rastrear actividad de clientes. -- Conectar sesiones no identificadas con perfiles de cliente. +- Registrar actividad de clientes. +- Conectar sesiones no identificadas con perfiles de clientes. + +## Integración de una tienda propia + +La guía para tiendas propias es el punto de partida práctico para un equipo que todavía no sabe qué datos debe enviar mediante la API, qué actividad debe registrar con Hellotext.js o cómo se conectan ambos lados. + +Empieza aquí: [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}). ## Referencia de la API @@ -31,17 +40,17 @@ Usa la API de mensajes cuando tu propio sistema necesite enviar recordatorios, c Sigue leyendo: [Enviar SMS con la API]({% link _developers/send-sms-with-api.md %}). -## Rastrea actividad de clientes +## Registra actividad de clientes -Usa tracking cuando quieres que Hellotext entienda acciones desde tu sitio, tienda, backend o integración personalizada. +Usa el seguimiento de eventos cuando quieres que Hellotext entienda acciones desde tu sitio, tienda, backend o integración personalizada. Los eventos rastreados pueden ayudarte a segmentar audiencias, activar playbooks o rutas, atribuir ingresos y darle más contexto al equipo del Inbox. Sigue leyendo: [Seguimiento de eventos]({% link _developers/tracking-events.md %}). -## Conecta sesiones del navegador con perfiles de cliente +## Conecta sesiones del navegador con perfiles de clientes -Hellotext.js puede crear una sesión para visitantes no identificados. Cuando el visitante se identifica, puedes adjuntar esa sesión a un perfil de cliente para conservar la actividad anterior. +Hellotext.js puede crear una sesión para visitantes no identificados. Cuando el visitante se identifica, puedes adjuntar esa sesión a un perfil del cliente para conservar la actividad anterior. Sigue leyendo: [Seguimiento de clientes no identificados]({% link _developers/tracking-unidentified-customers.md %}). diff --git a/_i18n/es/developers/external-tracking.md b/_i18n/es/developers/external-tracking.md index fdc2d8e2..8338c60c 100644 --- a/_i18n/es/developers/external-tracking.md +++ b/_i18n/es/developers/external-tracking.md @@ -1,71 +1,209 @@ -A veces, es posible que desees realizar un seguimiento de los eventos que ocurrieron fuera del navegador del visitante. Por ejemplo, realizar un seguimiento de los eventos en el lado del servidor de tu sistema o en algún momento en que el cliente no esté presente. +Usa esta guía para registrar en Hellotext eventos confiables que ocurren fuera del navegador, por ejemplo en tu backend, POS, CRM, ERP, marketplace, operador logístico, jobs o webhooks. -Puedes rastrear eventos enviando una solicitud 'POST' directamente a la API y pasando el identificador de perfil o el identificador de sesión. +El tracking externo complementa Hellotext.js. Usa Hellotext.js para la navegación y la actividad del carrito que ocurre en la tienda. Usa la API desde el backend para pedidos, pagos, cancelaciones, envíos, entregas y otras acciones que el servidor pueda verificar. -Los siguientes ejemplos usan la librería [**HTTParty**](https://github.com/jnunemaker/httparty) de Ruby. Esto puede variar según el lenguaje de programación, pero la naturaleza de la solicitud sigue siendo la misma. +Si estás conectando una tienda propia desde cero, comienza con [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) para implementar perfiles de clientes, catálogo, pedidos, Hellotext.js e identidad en el orden recomendado. -Al realizar una petición a la API, asegúrate de autenticarte configurando el encabezado "Authorization" con el token como el ejemplo a continuación. Puedes crear un token de autorización desde la sección de tokens en la configuración comercial. +## Antes de comenzar -### Seguimiento por perfil +Prepara: -Puedes realizar seguimientos de eventos directamente a los perfiles simplemente especificando el identificador del perfil al rastrear el evento. Si el perfil no existe en Hellotext, primero debes crearlo. Recomendamos leer la [**referencia de la API para crear un perfil**](https://www.hellotext.com/api#create_a_profile). +- Un token privado de autorización de la API guardado únicamente en el backend. +- El nombre de la acción que quieres registrar, como `product.viewed`, `order.placed` o una acción personalizada existente. +- El ID del perfil del cliente en Hellotext o el ID de una sesión de Hellotext. +- El ID del objeto relacionado, como un producto o pedido, o los datos necesarios para crearlo. +- Identificadores estables del sistema de origen para evitar objetos duplicados. -```ruby -HTTParty.post "https://api.hellotext.com/v1/attribution/events", - headers: { - "Authorization" => "Bearer ALK_eSMRuwJ2Al...", - "Content-Type" => "application/json" - }, - body: { - action: "product.purchased", - product: "vxqQJ3Yg", - profile: "PROFILE_ID" - }.to_json +Todos los ejemplos envían un `POST` a: + +```text +https://api.hellotext.com/v1/attribution/events ``` -Reemplaza `PROFILE_ID` con el identificador de perfil de tu cliente. +El token se envía mediante el encabezado `Authorization`. Consulta [Autenticación en la API](https://www.hellotext.com/api#authentication) para crear y usar el token correctamente. -Si la solicitud se realizó correctamente, la API debería responder con un código de estado HTTP de `201` y una respuesta JSON similar a esta: +## 1. Elige el perfil del cliente o la sesión -```json -{ - "state": "ok" -} +Cada evento necesita un `profile` o una `session`. No uses `profile_id` ni `session_id` en el cuerpo de esta request. + +### Cuando conoces al cliente + +Usa `profile` con el ID del perfil del cliente en Hellotext. Por ejemplo, registra la vista de un producto que ya existe en el catálogo: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "product.viewed", + "profile": "PROFILE_ID", + "object": "PRODUCT_ID" + }' ``` -### Seguimiento por sesión +Conserva el ID que devuelve Hellotext cuando creas el perfil del cliente. Si todavía no existe, consulta [Crear un perfil del cliente](https://www.hellotext.com/api#create_a_profile). -Esto es perfectamente posible capturando el identificador de sesión y guardándolo en tu sistema para usarlo más tarde al rastrear un evento. +### Cuando solo conoces la sesión -Para obtener la sesión actual, simplemente llama a `Hellotext.session`: +Hellotext.js expone la sesión actual después de inicializarse: ```javascript -Hellotext.session -// Returns bBJn9vR15yPaYkWmR2QK0jopMeNxrA6l +const sessionId = Hellotext.session +``` + +Envía ese ID a tu backend y usa `session` al registrar el evento: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "product.viewed", + "session": "HELLOTEXT_SESSION_ID", + "object": "PRODUCT_ID" + }' +``` + +Puedes enviar `profile` y `session` juntos cuando quieras asociar el contexto de esa sesión al cliente. La sesión debe estar sin asignar o pertenecer al mismo perfil del cliente. Si ya pertenece a otro perfil, Hellotext rechazará el evento. + +Consulta [Seguimiento de clientes no identificados]({% link _developers/tracking-unidentified-customers.md %}) para ver cómo conservar y adjuntar sesiones. + +## 2. Asocia el objeto correcto + +La mayoría de las acciones incorporadas necesitan un objeto relacionado: + +- `object` identifica un objeto que ya existe en Hellotext. +- `object_parameters` contiene los datos necesarios para crear o encontrar el objeto mientras se registra el evento. + +Usa `object` cuando ya sincronizaste el catálogo o el pedido y conservaste el ID devuelto por Hellotext. Usa `object_parameters` cuando el sistema de origen tenga toda la información necesaria pero todavía no dispongas del ID de Hellotext. + +Este ejemplo registra una vista y crea o encuentra el producto mediante `reference` y `source`: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "product.viewed", + "profile": "PROFILE_ID", + "object_parameters": { + "name": "Championes Everyday", + "reference": "product-100", + "source": "custom_store", + "url": "https://shop.example.com/products/everyday-sneakers", + "price": { + "amount": 89.90, + "currency": "USD" + } + } + }' +``` + +Mantén `reference` y `source` estables. Cambiarlos entre requests puede crear objetos separados para el mismo producto, carrito o pedido. + +Consulta [eventos de productos](https://www.hellotext.com/api#track_product_events), [eventos de carritos](https://www.hellotext.com/api#track_cart_events) y [eventos de pedidos](https://www.hellotext.com/api#track_order_events) para ver qué objeto y parámetros requiere cada acción. + +## 3. Registra el ciclo de los pedidos + +Para registrar varios estados de un pedido, crea o sincroniza el pedido primero y conserva su ID de Hellotext. Después reutiliza ese ID en cada evento real del ciclo: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "order.placed", + "profile": "PROFILE_ID", + "object": "ORDER_ID", + "amount": 89.90, + "currency": "USD" + }' +``` + +Reutiliza el mismo `ORDER_ID` para registrar únicamente los cambios que tu sistema pueda confirmar: + +- `order.confirmed` cuando el negocio confirma el pedido. +- `order.shipped` cuando el pedido sale para su entrega. +- `order.delivered` cuando se confirma la entrega. +- `order.cancelled` cuando el pedido se cancela. + +No registres todos los estados al crear el pedido. Cada evento debe enviarse cuando ese cambio ocurra realmente. Consulta [Crear un pedido](https://www.hellotext.com/api#create_an_order) para ver todos los campos disponibles. + +## 4. Registra acciones personalizadas + +Hellotext incluye acciones para productos, carritos, pedidos, formularios, cupones y otros objetos comunes. Cuando ninguna representa la actividad de tu negocio, crea primero una acción personalizada y luego usa su nombre en `action`: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/events \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "action": "appointment.completed", + "profile": "PROFILE_ID", + "tracked_at": "2026-08-07T12:30:00Z" + }' ``` -Realiza la siguiente solicitud a la API: - -```ruby -HTTParty.post "https://api.hellotext.com/v1/attribution/events", - headers: { - "Authorization" => "Bearer ALK_eSMRuwJ2Al...", - "Content-Type" => "application/json" - }, - body: { - action: "product.purchased", - product_id: "vxqQJ3Yg", - session_id: "HELLOTEXT_SESSION_ID" - }.to_json +Una acción personalizada puede registrarse sin un objeto relacionado. Si envías un objeto personalizado, debes indicar también su tipo según el contrato de la API. + +Consulta [Crear una acción](https://www.hellotext.com/api#create_an_action) antes de registrar el primer evento personalizado. + +## 5. Conserva la fecha y los valores monetarios + +Si el evento ocurrió antes de enviar la request, incluye `tracked_at` con una fecha ISO 8601 o un timestamp Unix. Si lo omites, Hellotext usa el momento en que recibe el evento. + +Usa la fecha original para importaciones históricas, jobs demorados y webhooks reintentados. Esto evita que actividad antigua aparezca como reciente y altere segmentos, elegibilidad de playbooks o reportes. + +Cuando el evento tenga un valor monetario, envía `amount` y `currency` juntos: + +```json +{ + "amount": 89.90, + "currency": "USD" +} ``` -Reemplaza `HELLOTEXT_SESSION_ID` con el identificador de sesión. +Si incluyes `currency`, `amount` es obligatorio. Usa el código ISO 4217 de la moneda y no conviertas manualmente el valor a la moneda de reportes. -Si la solicitud se realizó correctamente, la API debería responder con un código de estado HTTP de `201` y una respuesta JSON similar a esta: +## 6. Interpreta la respuesta y maneja errores +Una request válida responde con HTTP `200`: ```json { - "state": "ok" + "status": "received" } -``` \ No newline at end of file +``` + +Esto confirma que Hellotext recibió el evento para procesarlo. Revisa siempre el código HTTP y el cuerpo de la respuesta: + +- `401` indica que el token falta, es inválido o fue revocado. +- `404` puede indicar que la acción no existe para ese negocio. +- `422` indica que faltan parámetros o que el perfil del cliente, la sesión, el objeto o sus datos no son válidos. + +Registra el código y el error en tus logs, pero nunca guardes el token ni datos personales completos del cliente. + +## 7. Evita eventos duplicados + +Cada request aceptada puede crear un evento nuevo, aunque reutilices el mismo producto o pedido. Encontrar el mismo objeto por `reference` y `source` no elimina eventos repetidos. + +- Guarda en tu sistema qué evento de origen ya fue aceptado por Hellotext. +- No reintentes respuestas `200`. +- Reintenta errores temporales con espera progresiva y conserva el identificador del evento de origen en tu propia cola. +- No envíes el mismo evento desde Hellotext.js y desde el backend. +- Procesa una sola vez los webhooks repetidos del proveedor antes de llamar a Hellotext. + +Consulta la [referencia completa de tracking](https://www.hellotext.com/api#tracking) para ver todas las acciones, objetos y parámetros compatibles. + +## Guías relacionadas + +- [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) +- [Seguimiento de eventos]({% link _developers/tracking-events.md %}) +- [Seguimiento de clientes no identificados]({% link _developers/tracking-unidentified-customers.md %}) +- [Propiedades y eventos personalizados]({% link _audience/custom-properties-and-events.md %}) +- [Soluciona señales o actividad faltante]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}) diff --git a/_i18n/es/developers/send-sms-with-api.md b/_i18n/es/developers/send-sms-with-api.md index f8303ac1..9af7ff47 100644 --- a/_i18n/es/developers/send-sms-with-api.md +++ b/_i18n/es/developers/send-sms-with-api.md @@ -1,46 +1,76 @@ -Enviar mensajes por SMS usando la API de Hellotext es una forma simple de integrar recordatorios, confirmaciones o notificaciones desde tu propio sistema. +Usa la API de Hellotext cuando tu sistema necesite activar un SMS individual, por ejemplo una confirmación, un recordatorio o una notificación transaccional. Para enviar un mismo mensaje a una audiencia, usa una campaña de Hellotext, donde puedes seleccionar destinatarios y revisar el rendimiento del envío. ## Antes de empezar -Para enviar SMS por la API necesitas: +Necesitas: -* Tener una cuenta y un negocio creados en Hellotext. -* Crear un token de autorización desde *Settings* -> *Autorizaciones*. -* Tener saldo disponible para SMS en tu negocio. +- un negocio activo en Hellotext con envíos SMS habilitados; +- un token de autorización del negocio; +- un número de destino válido o el identificador de un perfil del cliente que tenga teléfono; y +- permiso para enviar el tipo de mensaje correspondiente. -Si todavía no tienes saldo habilitado para SMS, ponte en contacto con nuestro equipo para activarlo. +El token permite actuar sobre los datos del negocio que lo creó. Guárdalo únicamente en el backend o en un administrador de secretos. No lo incluyas en Hellotext.js, en código del navegador ni en una aplicación móvil distribuida. -## Crear el token de autorización +## 1. Crea un token de autorización -Una vez dentro de tu negocio, ve a *Settings* -> *Autorizaciones*. +En Hellotext, abre el negocio y ve a **Ajustes → Autorizaciones**. Selecciona **Crear nuevo token**, usa un nombre que identifique la integración y guarda el valor generado. -Haz clic en *Crear nuevo token*, asígnale un nombre que te permita identificar la integración y copia el valor generado. Lo usarás en el header `Authorization` de cada request: +Envía el token en cada solicitud: ```text Authorization: Bearer TU_TOKEN ``` -## Enviar un SMS +Cada token pertenece a un solo negocio. Usa tokens diferentes para negocios o entornos diferentes y reemplázalos si dejan de ser privados. Consulta la sección de [autenticación de la API](https://www.hellotext.com/api#authentication) para ver la referencia completa. -Para enviar un mensaje, realiza un `POST` a `https://api.hellotext.com/v1/messages`. +## 2. Elige cómo identificar al destinatario -Envía estos campos en el cuerpo del request: +Puedes enviar el SMS de dos maneras: -* `body`: contenido del mensaje. -* `destination`: número de destino en formato internacional, por ejemplo `+573176655211`. -* `technology`: tecnología del envío. Para SMS usa `sms`. +- **Con un número:** envía `destination` en formato internacional E.164, por ejemplo `+59899123456`. Hellotext busca un perfil del cliente con ese teléfono y, si no existe, crea uno automáticamente. +- **Con un perfil del cliente:** envía su identificador en `profile`. El perfil debe tener un teléfono disponible. Si tiene varios y necesitas elegir uno específico, agrega también `destination`. -### Ejemplo con cURL +Crear o encontrar el perfil del cliente durante el envío no lo suscribe automáticamente a comunicaciones promocionales. La identidad del cliente y su consentimiento son datos diferentes. + +## 3. Envía el primer SMS + +Realiza un `POST` a `https://api.hellotext.com/v1/messages` con: + +- `technology`: usa `sms` para forzar el canal SMS; +- `body`: el contenido del mensaje; y +- `destination` o `profile`: el destinatario. + +Este ejemplo envía a un número y permite que Hellotext encuentre o cree el perfil del cliente: ```bash curl -X POST "https://api.hellotext.com/v1/messages" \ -H "Authorization: Bearer TU_TOKEN" \ - -F "body=Hola, este es un SMS enviado desde la API de Hellotext." \ - -F "destination=+573176655211" \ - -F "technology=sms" + -H "Content-Type: application/json" \ + --data '{ + "technology": "sms", + "destination": "+59899123456", + "body": "Tu pedido ya está listo para retirar." + }' ``` -Si la solicitud fue aceptada, la API responderá con un JSON similar a este: +Si ya conoces el identificador del perfil del cliente, puedes usarlo en lugar del número: + +```bash +curl -X POST "https://api.hellotext.com/v1/messages" \ + -H "Authorization: Bearer TU_TOKEN" \ + -H "Content-Type: application/json" \ + --data '{ + "technology": "sms", + "profile": "ID_DEL_PERFIL", + "body": "Tu pedido ya está listo para retirar." + }' +``` + +Hellotext elige automáticamente un canal SMS disponible. Solo envía `origin` cuando necesites usar un remitente específico configurado para el negocio. Revisa [Enviar un mensaje en la referencia de la API](https://www.hellotext.com/api#create_a_message) para conocer todos los parámetros. + +## 4. Interpreta la respuesta + +Cuando la solicitud es válida, la API responde: ```json { @@ -48,56 +78,80 @@ Si la solicitud fue aceptada, la API responderá con un JSON similar a este: } ``` -### Ejemplo en Postman +Esta respuesta confirma que Hellotext aceptó la solicitud y programó su procesamiento. No confirma que el operador móvil haya entregado el SMS. + +El envío se procesa de manera asíncrona. Sus estados posteriores pueden incluir: -Si prefieres probarlo en Postman, configura: +- `pending`: creado y pendiente de procesamiento; +- `routed`: enviado al proveedor externo; +- `delivered`: confirmado como entregado; y +- `failed`: no pudo entregarse. -* Método: `POST` -* URL: `https://api.hellotext.com/v1/messages` -* Header: `Authorization: Bearer TU_TOKEN` -* Body: `form-data` +Puedes revisar la conversación del perfil del cliente en Inbox o consultar [la lista de mensajes en la API](https://www.hellotext.com/api#list_all_messages). La referencia también permite recuperar un mensaje específico una vez que conoces su identificador. -Luego agrega estos campos al body. Por ejemplo: +## 5. Prueba el flujo completo -* `body`: `Hola, este es un SMS enviado desde Postman.` -* `destination`: `+573176655211` -* `technology`: `sms` +Antes de habilitar el envío en producción: -También puedes usar este header como ejemplo: +1. Envía un mensaje a un número de prueba controlado por tu equipo. +2. Confirma que la API responda con `status: received`. +3. Comprueba que el SMS aparezca en la conversación correcta y llegue al teléfono. +4. Revisa el estado final del mensaje. +5. Prueba un número inválido y un token inválido para verificar cómo registra errores tu integración. -* Header `Authorization`: `Bearer TU_TOKEN` +No interpretes una respuesta exitosa como entrega final. Conserva el resultado de cada intento y evita volver a enviar el mismo mensaje automáticamente si una solicitud quedó en un estado incierto. El endpoint no recibe una clave de idempotencia, por lo que tu sistema debe prevenir duplicados al reintentar. -## Tarifas, longitud y encoding +## Mensajes con links -Las tarifas de envío dependen de tu configuración y del destino. Puedes consultar más información en la sección de [precios](https://www.hellotext.com/precios). +No pegues una URL extensa directamente si quieres que Hellotext genere un link corto rastreado. Usa esta sintaxis dentro de `body`: -Por defecto, los SMS usan encoding `GSM-7 Latin` y cada mensaje tiene un límite de `160` caracteres. +```text +Sigue tu pedido aquí: {shortlink:https://shop.example.com/orders/123} +``` -Si excedes ese límite, Hellotext concatena automáticamente el contenido en un mensaje adicional y el costo se cobra como dos SMS. +Hellotext reemplaza la instrucción durante el procesamiento. Si el negocio usa un dominio propio para links cortos, consulta [Configurar un dominio personalizado para links cortos]({% link _integrations/custom-domain-for-short-links.md %}). Para entender cómo se conserva la sesión después del clic, revisa [Seguimiento de links en campañas, rutas y playbooks]({% link _developers/tracking-on-campaigns-and-journeys.md %}). -Si el texto incluye caracteres no compatibles con `GSM-7`, por ejemplo emojis, Hellotext intentará utilizar encoding `UCS-2` automáticamente. Esta modalidad está disponible en Colombia. +## Cuándo usar una plantilla -Cuando el mensaje usa `UCS-2`, el largo máximo se reduce a `80` caracteres por mensaje. +Para contenido reutilizable, personalización mediante propiedades o links dinámicos con nombres, puedes enviar el identificador de una plantilla en lugar de `body`. Cuando envías `template`, Hellotext usa el contenido de esa plantilla e ignora `body`. -## Agregar shortlinks dentro del mensaje +Las plantillas con links dinámicos requieren que envíes sus URLs dentro de `template.shortlinks`. La [referencia para enviar mensajes](https://www.hellotext.com/api#create_a_message) contiene la estructura completa. -Puedes generar un enlace corto directamente dentro del texto del mensaje usando la sintaxis `{shortlink:URL}`. +## Longitud, codificación y costo -Por ejemplo: +La cantidad de caracteres de un segmento SMS depende de su codificación: -```text -Conoce más acá {shortlink:https://www.tunegocio.com} -``` +- GSM de 7 bits: hasta 160 caracteres por segmento simple; +- Latin-1: hasta 140 caracteres por segmento simple; y +- UCS-2: hasta 70 caracteres por segmento simple. + +Caracteres especiales y emojis pueden cambiar la codificación. Los mensajes largos pueden dividirse en varios segmentos SMS facturables, y parte del espacio se usa para concatenarlos. Por eso no calcules el costo únicamente contando caracteres sin considerar la codificación. + +El precio también depende del país de destino, el plan y los SMS incluidos. Consulta [Precios y tipos de números SMS]({% link _billing/sms-pricing-and-number-types.md %}) para estimar el envío. + +## Consentimiento y límites de envío + +La API no reemplaza las reglas de consentimiento. Antes de enviar: + +- verifica que el cliente pueda recibir ese tipo de comunicación; +- no envíes mensajes promocionales a perfiles no suscritos o que cancelaron la suscripción; +- incluye el mecanismo de baja correspondiente cuando sea necesario; y +- respeta las leyes y horarios aplicables al país de destino. -Hellotext reemplazará esa instrucción por un enlace corto al momento de enviar el mensaje. +Consulta [A quién puedes enviar mensajes]({% link _audience/consent-and-subscriber-status.md %}) para diferenciar identidad, verificación y suscripción. Los [límites SMS para negocios nuevos]({% link _troubleshooting-deliverability/sms-sending-limits-for-new-businesses.md %}) también aplican a mensajes iniciados mediante la API. -Si quieres usar tu propio dominio para enlaces cortos, consulta la guía de [dominio personalizado para enlaces cortos]({% link _integrations/custom-domain-for-short-links.md %}). +## Errores frecuentes -## Perfiles de cliente +- **`401 Unauthorized`:** el token falta, no es válido o fue reemplazado. +- **`422 Request Failed`:** revisa el número, `body`, `profile`, `technology` y la disponibilidad de SMS para el negocio. Corrige la solicitud antes de reintentar. +- **Errores del servidor:** registra la respuesta y reintenta con espera progresiva. Protege el flujo contra envíos duplicados. +- **La solicitud fue aceptada, pero el mensaje falla:** revisa el estado del mensaje, el teléfono, los límites de la cuenta y la disponibilidad del canal. -No necesitas crear un perfil previamente para hacer un envío puntual a un número usando `destination`. +La sección de [errores de la API](https://www.hellotext.com/api#errors) explica el formato de cada respuesta. -Sin embargo, si además quieres mantener el historial del perfil de cliente, segmentar audiencias o reutilizar esos datos en campañas, playbooks o rutas, puedes: +## Guías relacionadas -* Importar perfiles de cliente desde la interfaz de Hellotext. -* Crear perfiles programáticamente con la [referencia de la API para crear perfiles](https://www.hellotext.com/api#create_a_profile). +- [Integrar una tienda personalizada]({% link _developers/custom-store-integration.md %}) +- [Referencia de la API de Hellotext](https://www.hellotext.com/api) +- [Seguimiento de eventos]({% link _developers/tracking-events.md %}) +- [Links rastreados y dominios de links cortos]({% link _analytics-reporting-attribution/tracked-links.md %}) diff --git a/_i18n/es/developers/tracking-events.md b/_i18n/es/developers/tracking-events.md index e0d8b875..213fdeb8 100644 --- a/_i18n/es/developers/tracking-events.md +++ b/_i18n/es/developers/tracking-events.md @@ -1,109 +1,166 @@ -El seguimiento de eventos convierte el comportamiento de tus clientes en señales que Hellotext puede usar en perfiles de cliente, segmentos, atribución, playbooks y el Inbox. Las señales pueden venir de tu eCommerce, tienda física, backend propio, formularios, conversaciones o cualquier otra fuente importante para tu negocio. +El seguimiento de eventos convierte la actividad de tus clientes en señales que Hellotext puede usar en perfiles de clientes, segmentos, atribución, playbooks, rutas e Inbox. -Esas señales ayudan a Hellotext a decidir cuándo activar un playbook, actualizar un segmento, enriquecer un perfil de cliente, asistir a un agente o atribuir ingresos a la acción correcta. +Las señales pueden venir de una integración, Hellotext.js, tu backend, una tienda física, formularios, conversaciones o acciones internas de Hellotext. No necesitas registrar manualmente todas las señales ni implementar todos los eventos disponibles. -Para el concepto general del producto, empieza por [Qué son las señales]({% link _journeys/what-are-signals.md %}). +Para entender el concepto general del producto, comienza con [Qué son las señales]({% link _journeys/what-are-signals.md %}). -Si los eventos no aparecen donde esperas, usa [Soluciona señales o actividad faltante]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}) para revisar identidad, nombres de acciones, integraciones, disparadores y reportes. +## Señales, acciones, eventos y objetos -## Comprendiendo las acciones +Estos términos describen partes diferentes del mismo flujo: -Las acciones son las actividades genéricas que realizan tus clientes. +- Una **señal** es información que Hellotext puede interpretar para tomar decisiones. +- Una **acción** define qué ocurrió, por ejemplo `product.viewed` u `order.delivered`. +- Un **evento** es una ocurrencia de esa acción para un cliente o sesión en un momento determinado. +- Un **objeto** aporta el contexto relacionado, como el producto, carrito, pedido, cupón o formulario. -Están agrupadas por su tipo de acción y separadas por un punto. +Por ejemplo, este evento indica que un perfil del cliente vio un producto concreto: -Por ejemplo: +```json +{ + "action": "product.viewed", + "profile": "PROFILE_ID", + "object": "PRODUCT_ID", + "tracked_at": "2026-08-07T12:30:00Z" +} +``` -### Acciones del carrito +La acción por sí sola no siempre es suficiente. `product.viewed` necesita el producto visto y las acciones de pedidos necesitan el pedido correspondiente. -* `cart.abandoned` Un carro fue abandonado. -* `cart.added` Se agregó un artículo al carrito. -* `cart.removed` Se eliminó un artículo del carrito. +La mayoría de las acciones incorporadas siguen el formato `objeto.verbo`. `subscribed` y `unsubscribed` son excepciones vigentes y no deben renombrarse agregando un prefijo. -### Acciones de pedidos +## Acciones incorporadas para integraciones -* `order.placed` Se ha realizado el pedido. -* `order.confirmed` Confirmaste el pedido. -* `order.cancelled` El pedido ha sido cancelado por ti o tu cliente. -* `order.shipped` El pedido ha sido enviado a tu cliente. -* `order.delivered` El pedido ha sido entregado a tu cliente. +Estas son las acciones que una integración normalmente puede registrar. Usa solamente las que representen actividad real de tu sistema. -### Acciones del producto +### Suscripción -* `product.purchased` Se ha comprado un producto. -* `product.viewed` Se ha visto una página de producto. +- `subscribed`: el cliente dio su consentimiento y quedó suscrito mediante un canal compatible. +- `unsubscribed`: el cliente retiró su consentimiento o se dio de baja. -### Acciones de cupones +No uses `subscribed` solamente porque creaste un perfil del cliente. Consulta [¿A quién puedo escribirle?]({% link _audience/consent-and-subscriber-status.md %}). -* `coupon.redeemed` Un cliente canjeó un cupón. +### Páginas y productos -### Acciones de reembolso +- `page.viewed`: el cliente vio una página. +- `product.viewed`: el cliente vio un producto específico. +- `product.purchased`: el cliente compró un producto fuera de un ciclo de pedido más completo. -* `refund.requested` Un cliente solicitó un reembolso. -* `refund.received` Realizaste un reembolso a su cliente. +Hellotext.js registra automáticamente `page.viewed` con la URL actual. Una vista de página no identifica por sí sola el producto, por lo que `product.viewed` debe incluir explícitamente el producto correspondiente. -### Acciones de vistas de página +Si tu tienda trabaja con pedidos, prefiere las acciones del pedido en lugar de registrar también `product.purchased` para la misma compra. -* `page.viewed` Una página fue vista por un cliente. +### Carritos y checkout -### Acciones de la aplicación +- `cart.viewed`: el cliente vio su carrito. +- `cart.added`: se agregó un producto al carrito. +- `cart.removed`: se quitó un producto del carrito. +- `cart.abandoned`: la tienda determinó que el carrito fue abandonado. +- `checkout.started`: el cliente comenzó el checkout. -* `app.install` Se instaló una aplicación. -* `app.remove` Se eliminó una aplicación. -* `app.spent` Un cliente gastó en una aplicación. +No envíes `cart.abandoned` solamente porque el cliente salió de una página. Regístralo cuando tu tienda o integración haya determinado realmente el abandono. -### Acciones de formulario +### Pedidos -* `form.completed` El cliente completó un formulario. +- `order.placed`: el cliente creó el pedido. +- `order.confirmed`: el negocio confirmó el pedido. +- `order.cancelled`: el pedido fue cancelado. +- `order.shipped`: el pedido salió para su entrega. +- `order.delivered`: se confirmó la entrega. -### Acciones personalizadas +Cada cambio debe registrarse cuando ocurra y reutilizar el mismo objeto de pedido. No envíes todos los estados juntos al crear el pedido. -Puedes crear acciones personalizadas desde **Ajustes → Acciones → Personalizado** o mediante la API. Por ejemplo: +### Cupones, reembolsos y formularios -* `formulario_de_registro.completado` -* `tienda_fisica.pago` -* `evento.asistio` +- `coupon.redeemed`: el cliente canjeó un cupón. +- `refund.requested`: el cliente solicitó un reembolso. +- `refund.received`: el negocio completó el reembolso. +- `form.completed`: el cliente completó un formulario. -Obtén más información en **[Referencia de API para acciones](https://www.hellotext.com/api#actions)**. +### Aplicaciones -Un evento personalizado con un monto monetario positivo puede evaluarse para atribución cuando Hellotext puede identificar al cliente y encontrar evidencia elegible de origen y tiempo. Crear una acción personalizada por sí solo no convierte sus ingresos en ingresos atribuidos. Consulta [Cómo atribuimos las ventas]({% link _analytics-reporting-attribution/sales-attribution.md %}). +- `app.installed`: el cliente instaló una aplicación. +- `app.removed`: el cliente eliminó una aplicación. +- `app.spent`: el cliente realizó un gasto asociado con una aplicación. -## Comprendiendo los eventos +Los nombres correctos son `app.installed` y `app.removed`. No uses las variantes antiguas `app.install` o `app.remove`. -Un evento es el objeto que crea una relación entre una acción y un perfil de cliente en un momento determinado. +## Acciones generadas por Hellotext -Se crea cuando rastreas una acción de un cliente y pasa a formar parte del historial de señales que Hellotext puede usar después. +Hellotext también crea señales internas para mensajes, conversaciones, segmentos, enlaces cortos, cambios del perfil del cliente y decisiones de playbooks. Algunas acciones, como `product.browse_abandoned`, `product.price_changed` u `order.printed_label`, pertenecen a procesos internos del producto. -## Maneras de rastrear eventos +No reproduzcas esas acciones manualmente ni las envíes desde tu integración salvo que aparezcan explícitamente como compatibles en la [referencia de tracking](https://www.hellotext.com/api#tracking). Duplicarlas puede activar automatizaciones o alterar reportes de forma incorrecta. -* Usando una de las integraciones como Mercado Libre. -* Utilizando la librería de Javascript. -* Mediante la API. +## Acciones personalizadas -También puedes usar **Nuevo Evento** en un perfil de cliente para registrar una ocurrencia manualmente. Esto no configura el tracking automático de ocurrencias futuras. +Cuando ninguna acción incorporada representa lo que ocurre en tu negocio, crea una acción personalizada desde **Configuración → Acciones → Personalizado** o mediante la API. -## Seguimiento con integraciones +Usa un nombre estable y descriptivo, por ejemplo: -### Mercado Libre +- `appointment.completed` +- `store_visit.completed` +- `membership.renewed` -Si vendes en Mercado Libre, puedes rastrear las compras de tus clientes automáticamente. +No generes un nombre nuevo por cliente, pedido o fecha. Una acción representa un tipo reutilizable de actividad y cada evento representa una ocurrencia. -Simplemente conecta tu cuenta de Mercado Libre en pocos clics y comenzarás a rastrear los siguientes eventos de inmediato: +La acción personalizada debe existir antes de registrar el primer evento. Consulta [Crear una acción](https://www.hellotext.com/api#create_an_action). -* `order.confirmed` Has confirmado el pedido. -* `order.shipped` El pedido ha sido enviado a tu cliente. -* `order.cancelled` El pedido ha sido cancelado por ti o tu cliente. -* `refund.requested` Un cliente solicitó un reembolso. -* `refund.received` Realizaste un reembolso a su cliente. +Un evento personalizado con un monto monetario positivo puede evaluarse para atribución cuando Hellotext identifica al cliente y encuentra evidencia elegible de origen y tiempo. Crear la acción no convierte automáticamente su monto en ingresos atribuidos. Consulta [Cómo atribuimos las ventas]({% link _analytics-reporting-attribution/sales-attribution.md %}). -## Seguimiento de eventos programáticamente +## Cómo llegan los eventos a Hellotext -### Seguimiento con Javascript +### Integraciones -Para realizar un seguimiento de los eventos del lado del cliente, puedes usar la librería de Javascript **[Hellotext.js](https://github.com/hellotext/hellotext.js)**. +Las integraciones de eCommerce, canales y otras plataformas pueden crear perfiles de clientes, objetos y eventos automáticamente. Revisa qué datos aporta cada integración y no vuelvas a enviar los mismos eventos desde tu código. -Consulta el repositorio de Github en **[hellotext/hellotext.js](https://github.com/hellotext/hellotext.js)** para ver las últimas instrucciones de instalación y configuración. +Consulta [Configuración e integraciones]({% link _integrations/setup-overview.md %}) y [Verifica tus datos y señales después de configurar]({% link _integrations/verify-data-and-signals.md %}). -### Seguimiento mediante la API +### Hellotext.js -Obtén más información en **[Referencia de API para seguimiento](https://www.hellotext.com/api#tracking)**. +Usa Hellotext.js para la actividad que ocurre en el navegador, como vistas de páginas, vistas de productos y cambios en el carrito. La librería incluye la sesión actual para conservar el contexto anónimo. + +Consulta el [repositorio de Hellotext.js](https://github.com/hellotext/hellotext.js) para ver las instrucciones vigentes. + +### API + +Usa la API desde el backend para eventos confiables como pedidos, pagos, cancelaciones, envíos, entregas y actividad de sistemas externos. + +- Para una implementación completa, consulta [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}). +- Para enviar eventos desde el backend, consulta [Seguimiento de origen externo]({% link _developers/external-tracking.md %}). +- Para asociar actividad anónima, consulta [Seguimiento de clientes no identificados]({% link _developers/tracking-unidentified-customers.md %}). + +### Registro manual + +También puedes usar **Nuevo evento** dentro de un perfil del cliente para registrar una ocurrencia manual. Esto no configura el tracking automático de eventos futuros. + +## Datos que debe conservar cada evento + +Antes de implementar una acción, define: + +- **Identidad:** el perfil del cliente conocido o la sesión anónima. +- **Objeto:** el producto, carrito, pedido u otro objeto relacionado. +- **Fecha:** el momento real del evento mediante `tracked_at` cuando no ocurre en tiempo real. +- **Valor:** `amount` y `currency` cuando la acción tiene un valor monetario. +- **Origen:** la integración o sistema que produjo la actividad. + +Usa identificadores estables y no envíes el mismo evento desde varias fuentes. + +## Verifica el tracking + +Prueba primero con un cliente reconocible: + +1. Confirma que el evento aparezca en el perfil del cliente correcto. +2. Revisa que la acción use el nombre exacto. +3. Confirma que el objeto relacionado sea el producto, carrito o pedido esperado. +4. Revisa que la fecha represente cuándo ocurrió la actividad. +5. Comprueba que la integración no haya creado el mismo evento automáticamente. +6. Revisa segmentos, playbooks y reportes solamente después de validar los datos base. + +Si los eventos no aparecen donde esperas, usa [Soluciona señales o actividad faltante]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}). + +## Guías relacionadas + +- [Qué son las señales]({% link _journeys/what-are-signals.md %}) +- [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) +- [Seguimiento de origen externo]({% link _developers/external-tracking.md %}) +- [Propiedades y eventos personalizados]({% link _audience/custom-properties-and-events.md %}) +- [Cómo atribuimos las ventas]({% link _analytics-reporting-attribution/sales-attribution.md %}) diff --git a/_i18n/es/developers/tracking-on-campaigns-and-journeys.md b/_i18n/es/developers/tracking-on-campaigns-and-journeys.md index 9cde13ed..7648c0f0 100644 --- a/_i18n/es/developers/tracking-on-campaigns-and-journeys.md +++ b/_i18n/es/developers/tracking-on-campaigns-and-journeys.md @@ -1,72 +1,126 @@ -Después de enviar una campaña, activar una ruta o habilitar un playbook, querrás entender cómo interactuaron y se comportaron los clientes. Idealmente, también querrás conservar ese comportamiento como señales que Hellotext pueda reutilizar después. +Los links con tracking permiten conectar un clic con el mensaje que lo originó, el perfil del cliente, una sesión, los reportes y la actividad que ocurre después en tu sitio. -Ese es el propósito del tracking de links y eventos: conectar cada click con un perfil de cliente, una sesión, un reporte y una decisión futura. +Hellotext puede crear estos links en mensajes de campañas, rutas, playbooks e Inbox. Para que el contexto continúe después de la redirección, el sitio de destino debe conservar la sesión y registrar correctamente la actividad posterior. -## Enlaces cortos y sesiones +## Qué hace Hellotext cuando el cliente hace clic -Un enlace corto es simplemente una forma de reducir la longitud de una URL a algo parecido a `hello.link/3lsnvh`. +Cuando agregas un link con la herramienta del editor, Hellotext genera una URL corta como `hello.link/XXXXXX` o usa el dominio personalizado configurado por el negocio. -Esto te ayuda a superar el límite de 160 caracteres de los mensajes de texto, dejando más espacio para el mensaje. Los cortos también se sienten más atractivos. +Cuando el cliente hace clic, Hellotext: -Puedes compartir enlaces cortos en mensajes de campañas, rutas, playbooks e Inbox. +1. Registra la acción `short_link.clicked` para el perfil del cliente y el mensaje correspondiente. +2. Actualiza la cantidad de clics del link y los reportes disponibles. +3. Conserva el contexto de la campaña, broadcast, ruta, paso o playbook que originó el mensaje. +4. Redirige al cliente a la URL original. +5. Agrega una sesión y parámetros UTM a la URL de destino. -Cuando los clientes hacen clic en un enlace corto, son redirigidos a la URL original. Hellotext adjunta un parámetro GET a la URL original llamado `hellotext_session` que contiene un identificador de sesión generado de forma única con cada clic. +Hellotext filtra las previews que identifica como bots para que no se contabilicen como clics de clientes. Aun así, un clic registrado representa una interacción, no una compra ni una conversión garantizada. -Cada vez que un cliente hace clic en un enlace corto, se crea un evento y aparece en la actividad del perfil de cliente. Los clics también pueden agregarse a reportes de campañas, rutas o playbooks cuando ese reporte está disponible. +No envíes `short_link.clicked` manualmente desde tu integración. Hellotext lo crea cuando procesa el clic del link. -Un clic elegible puede aportar evidencia activa de atribución y normalmente abre una ventana de siete días desde el clic. No es el único camino de atribución: una entrega elegible u otra evidencia pasiva puede aplicar dentro de la ventana predeterminada de 24 horas. Consulta [Cómo atribuimos las ventas]({% link _analytics-reporting-attribution/sales-attribution.md %}). +## Parámetros que recibe el sitio de destino -## Primeros pasos de seguimiento +La URL redirigida puede verse así: -Si tu sitio funciona con alguna de las plataformas que ya ofrecemos soporte de integración, puedes conectarlo para comenzar a rastrear eventos automáticamente. +```text +https://shop.example.com/products/everyday-sneakers?hello_session=SESSION_ID&utm_source=hellotext&utm_medium=sms&utm_campaign=CAMPAIGN_ID +``` -Si tu integración aún no es compatible o si tienes tu propia implementación personalizada, puedes comenzar a rastrear eventos instalando la librería [**Hellotext.js**](https://github.com/hellotext/hellotext.js). +Los parámetros tienen funciones diferentes: -### Configura la librería en tu sitio +- `hello_session` conserva la sesión asociada con el link y permite conectar actividad posterior. +- `utm_source` identifica el origen del tráfico; normalmente su valor es `hellotext`. +- `utm_medium` identifica el canal cuando está disponible. +- `utm_campaign` identifica la campaña, ruta o playbook cuando corresponde. -Comienza instalando la librería. +El parámetro vigente es `hello_session`. No uses ni busques `hellotext_session`. -```bash -npm install @hellotext/hellotext -``` +Si la URL original ya contiene parámetros, Hellotext los conserva y agrega los suyos. No elimines `hello_session` ni los parámetros UTM en una redirección intermedia. -Importa la librería en tu aplicación. +## Cómo continúa la sesión en el sitio -```javascript -import Hellotext from "@hellotext/hellotext"; -``` +Hellotext.js lee `hello_session` desde la URL, conserva la sesión en el navegador y la incluye en la actividad posterior. -Inicializa la librería pasando el identificador público `HELLOTEXT_BUSINESS_ID` que representa la empresa. +Inicializa Hellotext.js antes de que tu router o código de la tienda elimine los parámetros de la URL. En una aplicación de una sola página, conserva el query string durante la carga inicial. -Puedes encontrarlo en la página de configuración de la empresa. +Puedes comprobar la sesión después de inicializar la librería: ```javascript -Hellotext.initialize("HELLOTEXT_BUSINESS_ID"); +if (Hellotext.isInitialized) { + console.log(Hellotext.session) +} ``` -## Seguimiento de eventos del lado del cliente +Hellotext.js registra automáticamente `page.viewed` con la URL actual. Si la página representa un producto, registra también `product.viewed` e incluye explícitamente el producto. La URL por sí sola no aporta toda la información del catálogo. -El seguimiento de eventos es sencillo y quizás el ejemplo más simple es el seguimiento de una vista de página: +Consulta [Seguimiento de clientes no identificados]({% link _developers/tracking-unidentified-customers.md %}) para conocer el ciclo completo de la sesión y la identidad. -```javascript -Hellotext.track("page.visited"); -``` +## Contexto según el origen del mensaje -Consulta la [**documentación de uso de la biblioteca**](https://github.com/hellotext/hellotext.js#usage) para obtener una referencia completa sobre todas las acciones y atributos disponibles. +El mismo mecanismo conserva diferentes referencias según dónde se creó el mensaje: -## Seguimiento de eventos del lado del servidor +- **Campaña:** el clic se relaciona con la campaña, el broadcast y el mensaje enviado. +- **Ruta:** el clic se relaciona con la ruta, el paso y el mensaje que se ejecutó. +- **Playbook:** el clic se relaciona con el playbook y el mensaje generado o enviado. +- **Inbox:** el clic queda en la actividad del cliente y la conversación, aunque no tenga un reporte de campaña o automatización. -A veces, es posible que desees realizar un seguimiento de los eventos que ocurrieron fuera del navegador, por ejemplo, es posible que desees realizar un seguimiento de los eventos directamente en el lado del servidor de tu sistema, o en un momento en el que el cliente no esté presente. +No reutilices manualmente el link personalizado de un mensaje para otros clientes o envíos. Agrega el destino mediante la herramienta de links del editor y permite que Hellotext genere el contexto correcto para cada mensaje. -Esto es posible capturando el identificador de sesión y almacenándolo en tu sistema para usarlo más tarde cuando quieras rastrear un evento asociado a esta sesión. +## Cómo se conectan los eventos posteriores -Para obtener la sesión actual, simplemente llama a `Hellotext.session`: +Un clic es solo el inicio de la sesión. Para entender qué ocurrió después, el sitio o backend debe registrar las acciones relevantes: -```javascript -Hellotext.session -// Returns bBJn9vR15yPaYkWmR2QK0jopMeNxrA6l -``` +- Hellotext.js registra navegación, vistas de productos y cambios del carrito. +- Tu backend registra pedidos, pagos, cancelaciones, envíos y entregas confiables. +- Cuando se conoce al cliente, la sesión debe asociarse con el perfil del cliente correcto. + +Si el checkout ocurre en otro dominio o aplicación, envía el ID de `Hellotext.session` a tu backend antes de perder el contexto. Después puedes registrar el pedido con el perfil del cliente o la sesión correspondiente. + +No envíes el mismo evento desde Hellotext.js y desde el backend. Consulta [Seguimiento de eventos]({% link _developers/tracking-events.md %}) y [Seguimiento de origen externo]({% link _developers/external-tracking.md %}). + +## Clics, reportes y atribución + +Los clics pueden aparecer en la actividad del perfil del cliente y en reportes de campañas, rutas o playbooks cuando ese reporte está disponible. + +Un clic elegible puede aportar evidencia activa de atribución y normalmente abre una ventana de siete días desde el clic. Una entrega elegible u otra señal pasiva puede aplicar dentro de la ventana predeterminada de 24 horas. Estas ventanas pueden configurarse por cuenta. + +El clic no garantiza que una compra se atribuya a ese origen. Hellotext también evalúa: + +- Que el cliente y el pedido estén identificados correctamente. +- Que la compra ocurra dentro de la ventana aplicable. +- Que la campaña, ruta, playbook o entrega sean elegibles. +- Que no exista otra fuente válida con mayor precedencia. + +Consulta [Cómo atribuimos las ventas]({% link _analytics-reporting-attribution/sales-attribution.md %}) para conocer las ventanas, la precedencia y los ejemplos completos. + +## Verifica la implementación + +Prueba con un perfil del cliente y un mensaje reconocibles: + +1. Crea un link con tracking mediante el editor. +2. Envía el mensaje de prueba y abre el link como lo haría el cliente. +3. Confirma que la URL de destino incluya `hello_session` y los parámetros UTM esperados. +4. Verifica que `Hellotext.session` coincida con la sesión recibida. +5. Confirma que el clic aparezca en la actividad del perfil del cliente. +6. Revisa el reporte de la campaña, ruta o playbook cuando esté disponible. +7. Registra una vista de producto, carrito o pedido de prueba y confirma que conserve el cliente y el origen correctos. +8. Comprueba que la misma actividad no se haya registrado dos veces. + +## Soluciona problemas comunes + +- **El clic aparece, pero la actividad posterior no:** confirma que el sitio conserve `hello_session` hasta que Hellotext.js se inicialice. +- **La sesión cambia al llegar al sitio:** revisa redirects, dominios, cookies y el orden de inicialización de Hellotext.js. +- **La vista de página aparece sin producto:** registra `product.viewed` con el producto correspondiente. +- **El clic no aparece en el reporte:** verifica que el link haya sido creado en el mensaje correcto y que no haya sido una preview detectada como bot. +- **La compra no se atribuye:** revisa identidad, pedido, fecha, ventana y precedencia de fuentes. + +Si faltan señales, usa [Soluciona señales o actividad faltante]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}). -Luego puedes rastrear eventos enviando una solicitud `POST` directamente a la API. +## Guías relacionadas -Más información: [**Seguimiento externo**]({% link _developers/external-tracking.md %}). +- [Links con tracking]({% link _analytics-reporting-attribution/tracked-links.md %}) +- [Resumen del editor de mensajes]({% link _numbers/message-editor-overview.md %}) +- [Seguimiento de clientes no identificados]({% link _developers/tracking-unidentified-customers.md %}) +- [Seguimiento de origen externo]({% link _developers/external-tracking.md %}) +- [Cómo atribuimos las ventas]({% link _analytics-reporting-attribution/sales-attribution.md %}) +- [Dominio personalizado para links cortos]({% link _integrations/custom-domain-for-short-links.md %}) diff --git a/_i18n/es/developers/tracking-unidentified-customers.md b/_i18n/es/developers/tracking-unidentified-customers.md index 1a0850dc..ab3bff73 100644 --- a/_i18n/es/developers/tracking-unidentified-customers.md +++ b/_i18n/es/developers/tracking-unidentified-customers.md @@ -1,71 +1,150 @@ -En ocasiones, es posible que desees comenzar a realizar un seguimiento de los eventos de los nuevos visitantes que llegan a tu sitio y que no han sido identificados y por lo tanto aún no pueden asociarse en Hellotext. +Hellotext puede registrar la actividad de un visitante antes de saber quién es. Hellotext.js crea o reutiliza una sesión anónima y la incluye en la actividad del navegador. Cuando el visitante se convierte en un cliente conocido, puedes asociar esa sesión con el perfil del cliente para conservar el historial completo. -Para ayudarte a realizar seguimientos de eventos en estos casos, la librería [**Hellotext.js**](https://github.com/hellotext/hellotext.js) crea un nuevo identificador de sesión para cada nuevo visitante mientras que no haya una sesión existente. +La sesión, el perfil del cliente y el consentimiento son conceptos diferentes: -Puedes guardar este identificador de sesión y luego adjuntarlo al perfil cuando lo sepas, por ejemplo, cuando el visitante se registra o inicia sesión en el sitio. +- La **sesión** conecta la actividad de un navegador. +- El **perfil del cliente** reúne identidad, propiedades, conversaciones y señales conocidas. +- El **consentimiento** determina si puedes enviar mensajes por un canal. Identificar al cliente no lo convierte automáticamente en suscriptor. -Suponiendo que tienes [**Hellotext.js**](https://github.com/hellotext/hellotext.js) ya instalada y configurada, para obtener la sesión actual, simplemente llama al método `Hellotext.session`: +Si estás conectando una tienda propia desde cero, comienza con [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}). + +## 1. Obtén la sesión anónima + +Hellotext.js busca una sesión existente en la URL o en el navegador. Si no encuentra una y la generación automática está habilitada, crea una nueva. + +Después de inicializar Hellotext.js, lee la sesión actual: ```javascript -Hellotext.session -// Returns bBJn9vR15yPaYkWmR2QK0jopMeNxrA6l +if (Hellotext.isInitialized) { + const sessionId = Hellotext.session +} ``` -Guarda este valor en tu implementación, ya que deberás devolverlo mediante la API cuando se conozca el perfil. +Si la librería todavía no terminó de inicializarse, `Hellotext.session` puede ser `undefined`. Puedes escuchar el momento en que la sesión queda disponible: + +```javascript +Hellotext.on('session-set', sessionId => { + console.log('Hellotext session:', sessionId) +}) +``` + +Hellotext.js incluye la sesión automáticamente cuando registra actividad. Guarda el ID en tu backend únicamente cuando necesites asociarlo más adelante con un cliente conocido. Nunca envíes el token privado de la API al navegador. + +Consulta [Sesiones en Hellotext.js](https://github.com/hellotext/hellotext.js/blob/main/docs/sessions.md) para ver las opciones vigentes de inicialización y eventos de la librería. -## Adjuntar sesión a un perfil existente +## 2. Identifica al cliente en el momento correcto -Una vez que se conoce al visitante, por ejemplo, después de que inicia sesión en su sitio, debes realizar una petición a la API para asociar la sesión no identificada a su perfil de cliente. +Asocia la sesión cuando tu aplicación ya pueda reconocer de forma confiable al cliente, por ejemplo: -Una vez que se asocia la sesión, todos los eventos rastreados asociados a la sesión pasarán a formar parte del perfil del cliente. +- Después de que inicia sesión correctamente. +- Después de completar el registro y crear su cuenta. +- Durante el checkout, cuando el backend crea o encuentra un perfil del cliente confiable. -El siguiente ejemplo usa la librería [**HTTParty**](https://github.com/jnunemaker/httparty) de Ruby. Esto puede variar según el lenguaje de programación, pero la naturaleza de la petición sigue siendo la misma. +No identifiques a una persona solamente porque escribió un email o teléfono en un campo que todavía no fue confirmado. Tampoco marques el perfil del cliente como suscrito salvo que tengas consentimiento válido para el canal correspondiente. -Al realizar una petición a la API, asegúrate de autenticarte configurando el encabezado "Authorization" con el token como el ejemplo a continuación. Puedes crear un token de autorización desde la sección de tokens en la configuración comercial. +En una aplicación de una sola página, espera a conocer el estado de autenticación antes de asociar la sesión. Esto evita atribuir la primera actividad del navegador al cliente equivocado. -```ruby -HTTParty.post "https://api.hellotext.com/v1/sessions/HELLOTEXT_SESSION_ID", - headers: { - "Authorization" => "Bearer ALK_eSMRuwJ2Al...", - "Content-Type" => "application/json" - }, - body: { - profile: "PROFILE_ID" - }.to_json +## 3. Adjunta la sesión desde el backend + +Este es el método recomendado para una tienda propia porque el backend controla la identidad y mantiene privado el token de la API. + +1. Lee `Hellotext.session` en el navegador. +2. Envía el ID de la sesión a tu backend junto con la request autenticada del cliente. +3. Resuelve el cliente usando la sesión de autenticación de tu aplicación. No confíes en un ID de perfil del cliente enviado directamente por el navegador. +4. Crea o encuentra el perfil del cliente en Hellotext y conserva su ID. +5. Adjunta la sesión con el token privado de la API. + +Si el perfil del cliente todavía no existe, créalo primero mediante [Crear un perfil del cliente](https://www.hellotext.com/api#create_a_profile). Crear el perfil no establece consentimiento. + +Adjunta la sesión existente: + +```bash +curl --request PATCH \ + --url https://api.hellotext.com/v1/sessions/HELLOTEXT_SESSION_ID \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "profile": "PROFILE_ID" + }' ``` -Reemplaza `HELLOTEXT_SESSION_ID` en la URL con el identificador de sesión y `PROFILE_ID` con el identificador de perfil existente. +Una request válida responde con HTTP `200` y el objeto de la sesión actualizado, incluyendo el perfil del cliente asociado. La actividad anónima anterior pasa a formar parte del historial del cliente; algunos datos pueden terminar de asociarse en segundo plano. + +Consulta [Adjuntar una sesión](https://www.hellotext.com/api#attach_session) para ver el contrato completo del endpoint. -Si la solicitud se realizó correctamente, la API debería responder con un código de estado HTTP de `201` y una respuesta JSON similar a esta: +## 4. Usa la identificación en el navegador solo cuando sea necesario -```json -{ - "id": "WBAkaqNz", - "type": "session", - "profile": "MzYwlE50", - "created_at": 1665684173, +Hellotext.js ofrece `identify()` para integraciones compatibles que solo pueden obtener la identidad en el navegador: + +```javascript +const response = await Hellotext.identify('user_123', { + source: 'shopify', + email: 'ana@example.com', + name: 'Ana Silva', +}) + +if (response.failed) { + console.error(response.data) } ``` -## Adjuntar sesión al nuevo perfil +Usa como primer argumento el identificador estable del cliente en la plataforma de origen. El valor de `source` debe corresponder a una fuente compatible con Hellotext.js. Para una tienda propia, prefiere adjuntar la sesión desde el backend; no inventes un valor de `source`. -Si el perfil aún no existe en Hellotext, primero debes crearlo. +Cuando la identificación tiene éxito, Hellotext.js conserva la identidad en el navegador y la incluye en la actividad posterior. No necesitas llamar a `identify()` en cada página si el cliente y los datos enviados no cambiaron. -Recomendamos leer la [**referencia de la API para crear un perfil**](https://www.hellotext.com/api#create_a_profile) para aprender a especificar los atributos del cliente. Siempre recomendamos crear el perfil con tantos atributos como tengas de tu cliente. +No incluyas un estado de suscripción salvo que tu aplicación tenga evidencia válida del consentimiento. -```ruby -HTTParty.post "https://api.hellotext.com/v1/profiles", - headers: { - "Authorization" => "Bearer ALK_eSMRuwJ2Al...", - "Content-Type" => "application/json" - }, - body: { - first_name: "John", - last_name: "Smith" - phone: "+59899000001" - }.to_json +## 5. Olvida la identidad al cerrar sesión + +Cuando el cliente cierre sesión en tu aplicación, llama a: + +```javascript +Hellotext.forget() ``` -La respuesta devolverá el identificador del perfil. +Esto elimina del navegador la identidad persistida por `identify()`, pero mantiene activa la sesión de Hellotext. No elimina el perfil del cliente, su historial ni su consentimiento, y tampoco deshace una asociación realizada previamente desde el backend. + +Si varias cuentas pueden usar el mismo navegador, tu backend debe comprobar cada transición de login. No intentes mover una sesión que ya pertenece a un perfil del cliente diferente. + +## 6. Maneja sesiones que ya tienen un cliente + +Una sesión puede adjuntarse nuevamente al mismo perfil del cliente, pero no debe reutilizarse para otro cliente. Antes de considerar exitosa la asociación, comprueba el campo `profile` de la respuesta. + +Si la sesión ya pertenece a otro perfil del cliente: + +- No reasignes la actividad anterior al cliente actual. +- Detén el proceso de asociación y revisa por qué se compartió la sesión. +- Confirma que `Hellotext.forget()` se ejecute al cerrar sesión cuando uses `identify()`. +- Revisa el ciclo de sesiones de tu aplicación antes de registrar más eventos autenticados. + +Cuando envías `profile` y `session` juntos al registrar un evento, ambos deben pertenecer al mismo cliente. Consulta [Seguimiento de origen externo]({% link _developers/external-tracking.md %}) para ver esa validación. + +## 7. Verifica el flujo completo + +Prueba con un cliente reconocible: + +1. Abre la tienda sin iniciar sesión y confirma que Hellotext.js tenga una sesión. +2. Registra actividad anónima, como una vista de producto o una actualización del carrito. +3. Inicia sesión o completa el checkout. +4. Crea o encuentra el perfil del cliente correcto en Hellotext. +5. Adjunta la sesión desde el backend. +6. Confirma que la respuesta contenga el perfil del cliente esperado. +7. Verifica que la actividad anterior y los eventos nuevos aparezcan en ese perfil del cliente. +8. Cierra sesión y confirma que tu aplicación llame a `Hellotext.forget()` si usó `identify()`. + +## Soluciona problemas comunes + +- **La sesión es `undefined`:** espera a que Hellotext.js se inicialice o escucha `session-set`. +- **La API responde `401`:** revisa el token privado y el encabezado `Authorization`. +- **La API responde `404`:** la sesión puede no existir para ese negocio o todavía no haber sido enviada a Hellotext mediante actividad del navegador. +- **La respuesta muestra otro perfil del cliente:** trata el caso como un conflicto de identidad y no continúes registrando eventos autenticados con esa sesión. +- **La actividad anterior no aparece inmediatamente:** la asociación puede completarse en segundo plano; espera el procesamiento y vuelve a revisar. + +Si continúan faltando señales, usa [Soluciona señales o actividad faltante]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}). + +## Guías relacionadas -Utiliza este identificador de perfil ahora para adjuntar la sesión siguiendo las instrucciones descritas en *Adjuntar sesión a un perfil existente*. \ No newline at end of file +- [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) +- [Seguimiento de origen externo]({% link _developers/external-tracking.md %}) +- [Seguimiento de eventos]({% link _developers/tracking-events.md %}) +- [¿A quién puedo escribirle?]({% link _audience/consent-and-subscriber-status.md %}) diff --git a/_i18n/es/getting-started/implementation-paths.md b/_i18n/es/getting-started/implementation-paths.md index cb7f6bd1..66911a9a 100644 --- a/_i18n/es/getting-started/implementation-paths.md +++ b/_i18n/es/getting-started/implementation-paths.md @@ -90,18 +90,19 @@ Empieza aquí: Si tu experiencia de WhatsApp depende de recomendaciones de producto o contexto de órdenes, conecta la plataforma de comercio antes o junto con WhatsApp. -## Camino custom o API +## Camino personalizado o por API -Usa este camino cuando tu fuente de datos es custom, tu checkout no está cubierto por una integración estándar o tu equipo necesita enviar eventos directamente. +Usa este camino cuando tu fuente de datos es personalizada, tu checkout no está cubierto por una integración estándar o tu equipo necesita enviar eventos directamente. Empieza aquí: +- [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) - [Resumen de desarrolladores y API]({% link _developers/developers-overview.md %}) - [Seguimiento de eventos]({% link _developers/tracking-events.md %}) - [Seguimiento de clientes no identificados]({% link _developers/tracking-unidentified-customers.md %}) - [Seguimiento externo]({% link _developers/external-tracking.md %}) -Para implementaciones custom, define el primer objetivo de negocio antes de implementar todos los eventos. Recuperación de carrito, recuperación de navegación, primera compra, derivación a soporte y atribución necesitan datos distintos. +Para implementaciones personalizadas, define el primer objetivo de negocio antes de implementar todos los eventos. Recuperación de carrito, recuperación de navegación, primera compra, derivación a soporte y atribución necesitan datos distintos. ## Qué hacer después de configurar