From 588df800e2e9d98a8397901b46068e5587906a96 Mon Sep 17 00:00:00 2001 From: Martin Caetano Date: Fri, 7 Aug 2026 13:56:16 -0300 Subject: [PATCH 1/2] Add practical API integration guides --- _config.yml | 4 + _developers/coupons-with-api.md | 19 ++ _developers/orders-with-api.md | 19 ++ .../products-and-inventory-with-api.md | 19 ++ .../troubleshoot-custom-integration.md | 19 ++ _i18n/en/developers/coupons-with-api.md | 129 ++++++++++++ .../en/developers/custom-store-integration.md | 8 +- _i18n/en/developers/developers-overview.md | 9 + _i18n/en/developers/external-tracking.md | 3 + _i18n/en/developers/orders-with-api.md | 174 ++++++++++++++++ .../products-and-inventory-with-api.md | 163 +++++++++++++++ .../troubleshoot-custom-integration.md | 193 ++++++++++++++++++ _i18n/es/developers/coupons-with-api.md | 129 ++++++++++++ .../es/developers/custom-store-integration.md | 8 +- _i18n/es/developers/developers-overview.md | 9 + _i18n/es/developers/external-tracking.md | 3 + _i18n/es/developers/orders-with-api.md | 174 ++++++++++++++++ .../products-and-inventory-with-api.md | 163 +++++++++++++++ .../troubleshoot-custom-integration.md | 193 ++++++++++++++++++ 19 files changed, 1436 insertions(+), 2 deletions(-) create mode 100644 _developers/coupons-with-api.md create mode 100644 _developers/orders-with-api.md create mode 100644 _developers/products-and-inventory-with-api.md create mode 100644 _developers/troubleshoot-custom-integration.md create mode 100644 _i18n/en/developers/coupons-with-api.md create mode 100644 _i18n/en/developers/orders-with-api.md create mode 100644 _i18n/en/developers/products-and-inventory-with-api.md create mode 100644 _i18n/en/developers/troubleshoot-custom-integration.md create mode 100644 _i18n/es/developers/coupons-with-api.md create mode 100644 _i18n/es/developers/orders-with-api.md create mode 100644 _i18n/es/developers/products-and-inventory-with-api.md create mode 100644 _i18n/es/developers/troubleshoot-custom-integration.md diff --git a/_config.yml b/_config.yml index e5aab6ee..36d96ee9 100644 --- a/_config.yml +++ b/_config.yml @@ -218,6 +218,10 @@ collections: - developers-overview.md - custom-store-integration.md - api.md + - products-and-inventory-with-api.md + - orders-with-api.md + - coupons-with-api.md + - troubleshoot-custom-integration.md - send-sms-with-api.md - tracking-events.md - custom-actions.md diff --git a/_developers/coupons-with-api.md b/_developers/coupons-with-api.md new file mode 100644 index 00000000..8c5e9bec --- /dev/null +++ b/_developers/coupons-with-api.md @@ -0,0 +1,19 @@ +--- +languages: ["en", "es"] + +en: + title: Create and track coupons with the API + description: Represent an existing store coupon in Hellotext and record confirmed redemptions without duplicating them. +es: + title: Crea y registra cupones con la API + description: Representa en Hellotext un cupón existente de la tienda y registra canjes confirmados sin duplicarlos. + +permalink: coupons-with-api +permalink_es: cupones-con-api + +layout: guide +topic: developers +popular: true +--- + +{% translate_file developers/coupons-with-api.md %} diff --git a/_developers/orders-with-api.md b/_developers/orders-with-api.md new file mode 100644 index 00000000..3c69fafc --- /dev/null +++ b/_developers/orders-with-api.md @@ -0,0 +1,19 @@ +--- +languages: ["en", "es"] + +en: + title: Create and track orders with the API + description: Synchronize an order once, connect it to the customer profile, and record each real lifecycle milestone. +es: + title: Crea y registra pedidos con la API + description: Sincroniza un pedido una sola vez, conéctalo con el perfil del cliente y registra cada hito real de su ciclo. + +permalink: orders-with-api +permalink_es: pedidos-con-api + +layout: guide +topic: developers +popular: true +--- + +{% translate_file developers/orders-with-api.md %} diff --git a/_developers/products-and-inventory-with-api.md b/_developers/products-and-inventory-with-api.md new file mode 100644 index 00000000..f6a5597e --- /dev/null +++ b/_developers/products-and-inventory-with-api.md @@ -0,0 +1,19 @@ +--- +languages: ["en", "es"] + +en: + title: Sync products and understand inventory availability + description: Keep products and variants synchronized through the API and understand how Hellotext obtains live availability. +es: + title: Sincroniza productos y entiende la disponibilidad de inventario + description: Mantén productos y variantes sincronizados mediante la API y entiende cómo obtiene Hellotext la disponibilidad en tiempo real. + +permalink: products-and-inventory-with-api +permalink_es: productos-inventario-con-api + +layout: guide +topic: developers +popular: true +--- + +{% translate_file developers/products-and-inventory-with-api.md %} diff --git a/_developers/troubleshoot-custom-integration.md b/_developers/troubleshoot-custom-integration.md new file mode 100644 index 00000000..31a0d4df --- /dev/null +++ b/_developers/troubleshoot-custom-integration.md @@ -0,0 +1,19 @@ +--- +languages: ["en", "es"] + +en: + title: Troubleshoot a custom integration + description: Diagnose authentication, validation, identity, duplicate data, delayed events, and safe retry problems. +es: + title: Soluciona una integración propia + description: Diagnostica problemas de autenticación, validación, identidad, datos duplicados, eventos demorados y reintentos seguros. + +permalink: troubleshoot-custom-integration +permalink_es: solucionar-integracion-personalizada + +layout: guide +topic: developers +popular: true +--- + +{% translate_file developers/troubleshoot-custom-integration.md %} diff --git a/_i18n/en/developers/coupons-with-api.md b/_i18n/en/developers/coupons-with-api.md new file mode 100644 index 00000000..070a3f23 --- /dev/null +++ b/_i18n/en/developers/coupons-with-api.md @@ -0,0 +1,129 @@ +A coupon object lets Hellotext reference a code, its description, and the destination where the customer can redeem it. A coupon event records that a customer actually redeemed that code. + +Creating a coupon in Hellotext does not create the discount in your eCommerce platform and does not enforce its eligibility, expiration, usage limit, or single-use rules. Create and validate the promotion in the system that owns checkout first. + +Use the [Coupons API reference](https://www.hellotext.com/api#coupons) for the complete contract. + +## Before you start + +Prepare: + +- A private API authorization token. +- A coupon code that already works in the eCommerce platform. +- A public destination URL where the customer can redeem it. +- A short description that can be used in a message. +- A stable external reference when the source system has one. +- The customer profile and purchase data needed to confirm redemption. + +## 1. Create the discount in the commerce system + +Before creating the Hellotext coupon object, confirm in the system that owns checkout: + +- Which products or customers are eligible. +- The discount amount or percentage. +- Start and expiration dates. +- Whether the code is single-use or reusable. +- Whether it can be combined with another promotion. +- The final destination URL. + +Hellotext can deliver and track the coupon context, but the commerce system decides whether checkout accepts it. + +## 2. Create the coupon object in Hellotext + +Create the matching coupon: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/coupons \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "code": "WELCOME10", + "description": "Get 10% off your first order", + "destination_url": "https://shop.example.com/discount/WELCOME10", + "reference": "promotion-2026-welcome" + }' +``` + +The code is case-sensitive and must be unique. Keep the description under the supported limit and make the destination URL publicly reachable. + +Save the returned coupon `id`. See [Create a coupon](https://www.hellotext.com/api#create_a_coupon) for every supported field. + +## 3. Update the same coupon when its presentation changes + +Use `PATCH /v1/coupons/:id` when the description or destination URL changes. Keep the same Hellotext coupon ID while it still represents the same promotion. + +Do not rotate an expired code into an unrelated promotion just to reuse its record. Create a new coupon when the offer has a different commercial identity, eligibility, or code. + +Because checkout rules live in the commerce system, updating the Hellotext object does not change those rules. + +## 4. Use the coupon in a compatible message or playbook + +After the coupon exists, it can be selected where Hellotext exposes coupon support, such as compatible captures, messages, routes, or playbooks. + +Before launch, test the complete customer experience: + +1. The message shows the intended code and description. +2. The destination opens the correct store and offer. +3. Checkout accepts the code for an eligible customer. +4. Expiration and reuse behavior match the commerce configuration. + +Do not promise free shipping, bundles, or another benefit unless that exact offer exists in the commerce system. + +## 5. Record a confirmed redemption + +Send `coupon.redeemed` only after the commerce system confirms that the customer used the coupon: + +```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": "coupon.redeemed", + "profile": "PROFILE_ID", + "object": "COUPON_ID", + "amount": 89.90, + "currency": "USD", + "tracked_at": 1786104000 + }' +``` + +Use the monetary value associated with the confirmed redemption according to your reporting implementation. Keep `amount` and `currency` together, and preserve the original event time. + +Do not send `coupon.redeemed` when the coupon is displayed, delivered, clicked, or copied. Those actions do not prove that checkout accepted it. + +See [Track coupon events](https://www.hellotext.com/api#track_coupon_events). + +## 6. Prevent duplicate redemption events + +The coupon object can be reused across many customers, but each confirmed redemption is a separate event. + +- Give each commerce redemption a stable internal ID. +- Process the same checkout notification only once. +- Mark it as sent after Hellotext responds with `status: received`. +- Do not send the same redemption from browser and backend code. +- Preserve the same customer profile and coupon ID on retries. + +The commerce platform remains responsible for preventing a code from being redeemed more times than its rules allow. Hellotext should receive the final confirmed outcome. + +## 7. Verify the complete flow + +Use one test coupon and one recognizable customer: + +- The code works in the store before it is added to Hellotext. +- The Hellotext coupon opens the correct destination. +- A compatible message displays the expected offer. +- An unsuccessful checkout does not create `coupon.redeemed`. +- A successful checkout creates one redemption event on the correct customer profile. +- Amount, currency, and timestamp reflect the real transaction. + +If the coupon request fails or a redemption event does not appear, use [Troubleshoot a custom integration]({% link _developers/troubleshoot-custom-integration.md %}). + +## Related guides + +- [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 %}) +- [Forms]({% link _captures/forms.md %}) +- [Website Popup]({% link _captures/website-popup.md %}) diff --git a/_i18n/en/developers/custom-store-integration.md b/_i18n/en/developers/custom-store-integration.md index dc98b97f..33eee3e1 100644 --- a/_i18n/en/developers/custom-store-integration.md +++ b/_i18n/en/developers/custom-store-integration.md @@ -119,6 +119,8 @@ Keep `source`, `reference`, and SKU values stable. Update the existing product w See [Create a product in the API](https://www.hellotext.com/api#create_a_product) for all supported product and variant data. +The public product endpoint does not currently expose stock quantity or live availability. Do not add inventory values to `metadata` and assume that inventory-aware playbooks will use them. Read [Sync products and understand inventory availability]({% link _developers/products-and-inventory-with-api.md %}) before enabling a workflow that depends on stock. + ## 5. Import historical orders Historical orders give Hellotext purchase context before the first live event arrives. Each imported order needs: @@ -178,7 +180,7 @@ Use the event that reflects what really happened, such as `order.placed`, `order 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. +See [Create and track orders with the API]({% link _developers/orders-with-api.md %}), [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 @@ -376,6 +378,10 @@ If data is missing, use [Troubleshoot missing signals or activity]({% link _trou ## Related guides - [Developers and API overview]({% link _developers/developers-overview.md %}) +- [Sync products and understand inventory availability]({% link _developers/products-and-inventory-with-api.md %}) +- [Create and track orders with the API]({% link _developers/orders-with-api.md %}) +- [Create and track coupons with the API]({% link _developers/coupons-with-api.md %}) +- [Troubleshoot a custom integration]({% link _developers/troubleshoot-custom-integration.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 %}) diff --git a/_i18n/en/developers/developers-overview.md b/_i18n/en/developers/developers-overview.md index f76cd0b1..36bf5fbc 100644 --- a/_i18n/en/developers/developers-overview.md +++ b/_i18n/en/developers/developers-overview.md @@ -23,6 +23,15 @@ The API reference is the source of truth for available resources, attributes, pa Open the [Hellotext API reference](https://www.hellotext.com/api). +## API implementation recipes + +Use the practical API guides when you need to move from the endpoint contract to a complete integration flow: + +- [Sync products and understand inventory availability]({% link _developers/products-and-inventory-with-api.md %}) +- [Create and track orders with the API]({% link _developers/orders-with-api.md %}) +- [Create and track coupons with the API]({% link _developers/coupons-with-api.md %}) +- [Troubleshoot a custom integration]({% link _developers/troubleshoot-custom-integration.md %}) + ## Authentication API requests use bearer tokens. diff --git a/_i18n/en/developers/external-tracking.md b/_i18n/en/developers/external-tracking.md index 50825315..b8b0caa3 100644 --- a/_i18n/en/developers/external-tracking.md +++ b/_i18n/en/developers/external-tracking.md @@ -203,6 +203,9 @@ See the complete [tracking API reference](https://www.hellotext.com/api#tracking ## Related guides - [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) +- [Create and track orders with the API]({% link _developers/orders-with-api.md %}) +- [Create and track coupons with the API]({% link _developers/coupons-with-api.md %}) +- [Troubleshoot a custom integration]({% link _developers/troubleshoot-custom-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 %}) diff --git a/_i18n/en/developers/orders-with-api.md b/_i18n/en/developers/orders-with-api.md new file mode 100644 index 00000000..1019b408 --- /dev/null +++ b/_i18n/en/developers/orders-with-api.md @@ -0,0 +1,174 @@ +An order in Hellotext has two complementary parts: + +- The **order object** stores the commercial snapshot: reference, source, products, quantities, prices, delivery method, and other order data. +- An **order event** connects that order to a customer profile at a real moment in its lifecycle, such as placement, confirmation, shipment, delivery, or cancellation. + +Creating the order object alone does not record a purchase for a customer. Create or find the order, keep its Hellotext ID, and then send the lifecycle event with that order and the correct customer profile. + +Use the [API reference](https://www.hellotext.com/api#orders) for the complete contract. This guide explains the recommended integration flow. + +## Before you start + +Prepare: + +- A private API authorization token stored only on your backend. +- The Hellotext ID of the customer profile associated with the order. +- Stable product or variant identifiers already synchronized with Hellotext. +- A stable order `reference` from your system. +- One consistent `source`, such as `custom_store`, for every order from the integration. +- The original event dates, amounts, and ISO 4217 currency codes. + +If products are not synchronized yet, start with [Sync products and understand inventory availability]({% link _developers/products-and-inventory-with-api.md %}). + +## 1. Create the order object + +Create the order after your backend has accepted it. Include the final line-item snapshot known at that moment: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/orders \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "name": "Order #1001", + "reference": "ORDER-1001", + "source": "custom_store", + "delivery": "deliver", + "payment_method": "Visa", + "sales_channel": "Website", + "items": [ + { + "product": "PRODUCT_ID", + "quantity": 2, + "price": { + "amount": 44.95, + "currency": "USD" + } + } + ], + "metadata": { + "warehouse": "main" + } + }' +``` + +Each item requires a product or variant identifier. The API accepts its Hellotext ID, reference, or SKU. When an item price is omitted, Hellotext uses the current product price; include the item price when the order must preserve the amount charged at checkout. + +Hellotext calculates the order total from its items when the total is not supplied by a compatible tracking flow. Save the returned order `id` in your system as `hellotext_order_id`. + +See [Create an order](https://www.hellotext.com/api#create_an_order) for every supported field. + +## 2. Record the first real lifecycle event + +After creating the order, connect it to the customer profile with the first state your backend can confirm: + +```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", + "tracked_at": 1786104000 + }' +``` + +Use `tracked_at` when the event happened before the request was sent. It should represent the source-system event time, not the retry time. + +A valid request responds with: + +```json +{ + "status": "received" +} +``` + +This means the event was accepted for processing. It can take a short time to appear in the customer profile and reports. + +## 3. Send each later state when it happens + +Reuse the same order ID and customer profile for every verified transition: + +- `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. + +For example: + +```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.shipped", + "profile": "PROFILE_ID", + "object": "ORDER_ID", + "tracked_at": 1786190400 + }' +``` + +Do not send all states when the order is created. Do not infer shipment or delivery from elapsed time. Each event should come from a transition your system can verify. + +See [Track order events](https://www.hellotext.com/api#track_order_events) for the current supported actions and parameters. + +## 4. Correct order data separately from its lifecycle + +Updating an order object changes its stored attributes; it does not create a lifecycle event. + +Use `PATCH /v1/attribution/orders/:id` to correct fields such as delivery method, payment method, sales channel, metadata, or custom properties. Use the order-item endpoints when products, quantities, or charged prices need correction. + +Send a new event only when a real lifecycle change occurred. For example, correcting the payment method does not justify sending `order.confirmed` again. + +See [Update an order](https://www.hellotext.com/api#update_an_order) and the [order-item reference](https://www.hellotext.com/api#order_items). + +## 5. Import historical orders without making them look new + +Historical orders help Hellotext understand prior customer and product activity. For each imported order: + +1. Create the order with its original reference, source, products, quantities, and charged prices. +2. Record only the lifecycle state that your historical data can verify. +3. Set `tracked_at` to the original event timestamp. +4. Preserve the original amount and currency. + +Do not use the import date as `tracked_at`. Otherwise old purchases can appear as current behavior and affect segments, playbook decisions, and reporting. + +## 6. Prevent duplicate orders and events + +The API does not expose an idempotency-key parameter. Your integration must keep its own delivery state. + +- Keep `source` and `reference` stable for the lifetime of the order. +- Store the Hellotext order ID returned by the first successful creation. +- Give each source lifecycle transition a stable internal event ID. +- Mark that source event as delivered only after Hellotext returns `status: received`. +- Do not send the same order event from Hellotext.js and your backend. +- If a create request times out, reconcile the order before sending another `POST`; the original request may have completed. + +Hellotext avoids storing the same lifecycle action repeatedly for one order, but your integration should still prevent duplicate submissions and preserve a reliable source log. + +## 7. Verify one order end to end + +Before importing a complete order history: + +1. Create one recognizable test customer profile. +2. Create or retrieve its products and variants. +3. Create one order and save the returned ID. +4. Send one real order event. +5. Confirm the event appears on the correct customer profile. +6. Confirm products, quantities, amount, currency, and original timestamp. +7. Send a later state and verify that the same order is reused. + +If the request fails or the event does not appear, use [Troubleshoot a custom integration]({% link _developers/troubleshoot-custom-integration.md %}). + +## Related guides + +- [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) +- [Sync products and understand inventory availability]({% link _developers/products-and-inventory-with-api.md %}) +- [External tracking]({% link _developers/external-tracking.md %}) +- [Tracking events]({% link _developers/tracking-events.md %}) +- [Sales attribution]({% link _analytics-reporting-attribution/sales-attribution.md %}) diff --git a/_i18n/en/developers/products-and-inventory-with-api.md b/_i18n/en/developers/products-and-inventory-with-api.md new file mode 100644 index 00000000..66886a3f --- /dev/null +++ b/_i18n/en/developers/products-and-inventory-with-api.md @@ -0,0 +1,163 @@ +Products and variants give Hellotext the catalog context it needs to understand product views, carts, orders, recommendations, and product-related playbooks. + +The public Products API synchronizes catalog records. Live stock quantity and availability are a separate concern: the current public product endpoint does not expose a dedicated inventory quantity or availability field. + +Use the [API reference](https://www.hellotext.com/api#products) for the complete product and variant contracts. This guide explains how to keep identity stable and how inventory availability differs from catalog synchronization. + +## Before you start + +Prepare: + +- A private API authorization token stored on your backend. +- A stable source name, such as `custom_store`. +- Permanent product and variant references from your commerce system. +- Unique SKUs where your catalog uses them. +- Public product URLs and image URLs. +- Prices and ISO 4217 currency codes. +- Categories, collections, tags, brand, and descriptions useful for discovery and recommendations. + +Decide which record is the parent product and which records are purchasable variants before the first sync. Do not change that model between imports. + +## 1. Choose stable product identity + +Use these fields consistently: + +- `source`: the system that owns the catalog, such as `custom_store`. +- `reference`: the permanent product or variant identifier in that source. +- `sku`: the commerce SKU when one exists. + +Do not use a product name, URL, price, or position in an import as its identity. Those values can change. + +Hellotext can retrieve and update products by ID, reference, or SKU. Store the returned Hellotext ID anyway; it is the safest identifier for later events and order items. + +## 2. Create a product and its variants + +Create the parent product with the variants known at that time: + +```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", + "source": "custom_store", + "brand": "Acme", + "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"], + "collection": ["Everyday"], + "tags": ["Comfort"], + "variants": [ + { + "name": "Everyday Sneakers / Black / 42", + "reference": "variant-100-black-42", + "sku": "SKU-100-BLK-42", + "price": { + "amount": 89.90, + "currency": "USD" + } + } + ] + }' +``` + +The product `name` is required. Use a publicly accessible image URL because Hellotext needs to download the image. + +Save the returned product and variant IDs. See [Create a product](https://www.hellotext.com/api#create_a_product) for every supported field. + +## 3. Update the existing record when catalog data changes + +Do not create a new product because its price, name, image, URL, categories, or tags changed. + +Update the existing product by its Hellotext ID, reference, or SKU: + +```bash +curl --request PATCH \ + --url https://api.hellotext.com/v1/attribution/products/product-100 \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "price": { + "amount": 79.90, + "currency": "USD" + }, + "tags": ["Comfort", "Sale"] + }' +``` + +Keep the original `source` and `reference`. Use the dedicated variant endpoints to create or update individual variants rather than recreating the parent product. + +See [Update a product](https://www.hellotext.com/api#update_a_product) and [Product variants](https://www.hellotext.com/api#product_variants). + +## 4. Understand the inventory boundary + +The public Products API currently does not include a supported field for: + +- Current stock quantity. +- Available-to-sell quantity. +- In-stock or out-of-stock state. +- Inventory location balances. + +Do not add values such as `stock`, `quantity`, or `available` to `metadata` or custom properties and assume that Hellotext will use them for inventory-aware playbooks. Metadata does not become a supported inventory signal automatically. + +Compatible commerce and ERP integrations can let Hellotext check availability directly from the source. If a custom store needs Back-in-Stock Pounce, low-stock urgency, or another workflow that depends on live availability, connect a compatible inventory source or confirm the supported ingestion path with Hellotext before launch. + +Do not delete a product merely because it is temporarily out of stock. Deletion is for a product that should no longer remain in the active Hellotext catalog. + +## 5. Track product activity with the product ID + +Hellotext.js automatically records the page URL, but it cannot infer which catalog product the page represents. Send `product.viewed` explicitly: + +```javascript +await Hellotext.track('product.viewed', { + object: 'PRODUCT_ID', +}) +``` + +Use the variant ID when the customer selected a specific variant and that detail matters to the event. + +For carts and orders, reuse the same product or variant IDs. Do not create separate product records for browser activity, cart items, and order items. + +See [Tracking events]({% link _developers/tracking-events.md %}) and the [product event reference](https://www.hellotext.com/api#track_product_events). + +## 6. Design a safe catalog synchronization + +A reliable sync should: + +1. Read changed products from the source system. +2. Match them through the stored Hellotext ID or stable source reference. +3. Create only products that do not exist. +4. Patch changed fields on existing products. +5. Create or update variants independently. +6. Retain a mapping between source IDs and Hellotext IDs. +7. Log validation errors without logging the authorization token. + +For large catalogs, process bounded batches and preserve your cursor or checkpoint. A failed batch should resume without recreating the products that already succeeded. + +## 7. Verify catalog quality + +Test a parent product with at least one variant: + +- The source and reference match your commerce system. +- SKUs are unique and assigned to the correct variants. +- The name, URL, image, brand, categories, collection, and tags are useful. +- Price and currency match the storefront. +- A product view resolves to the same product. +- A test order uses the same product or variant ID. +- An inventory-dependent playbook is not enabled until live availability has a supported source. + +If duplicates or validation errors appear, use [Troubleshoot a custom integration]({% link _developers/troubleshoot-custom-integration.md %}). + +## Related guides + +- [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) +- [Create and track orders with the API]({% link _developers/orders-with-api.md %}) +- [Tracking events]({% link _developers/tracking-events.md %}) +- [Verify your data and signals after setup]({% link _integrations/verify-data-and-signals.md %}) +- [Back-in-Stock Pounce playbook]({% link _journeys/back-in-stock-pounce.md %}) diff --git a/_i18n/en/developers/troubleshoot-custom-integration.md b/_i18n/en/developers/troubleshoot-custom-integration.md new file mode 100644 index 00000000..c729d86c --- /dev/null +++ b/_i18n/en/developers/troubleshoot-custom-integration.md @@ -0,0 +1,193 @@ +Use this guide when a custom API or Hellotext.js integration returns errors, creates duplicate records, or sends events that do not appear where expected. + +Start with one recognizable customer and one request. Confirm each layer before testing a complete import or enabling playbooks. + +## 1. Confirm the API token and business + +Test the token from the backend: + +```bash +curl --request GET \ + --url https://api.hellotext.com/v1/profiles?limit=1 \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" +``` + +Check that: + +- The header uses `Authorization: Bearer TOKEN`. +- The token has not been revoked. +- It belongs to the intended Hellotext business. +- It is loaded only in the backend environment. +- The business has access to the requested API operation. + +Never paste the token into browser code, screenshots, tickets, or application logs. + +## 2. Read the HTTP status before the response body + +Hellotext uses standard HTTP status codes. Handle each category differently: + +| Status | Meaning | What to do | +| --- | --- | --- | +| `400` | The request is malformed or a required parameter is missing. | Compare the body and content type with the API reference. | +| `401` | The token is missing, invalid, or revoked. | Replace or correct the token; do not retry unchanged. | +| `403` | The business or token cannot perform the operation, commonly because API access is unavailable for the current plan state. | Review business access and subscription status. | +| `404` | The resource, action, or business-scoped identifier was not found. | Confirm the ID and that it belongs to the same business as the token. | +| `422` | The request reached the endpoint but one or more values failed validation. | Read every returned error and correct the named parameter. | +| `500`, `502`, `503`, `504` | Hellotext or an upstream service had a temporary server problem. | Retry safely with progressive backoff. | + +Validation responses include an `error` object or an `errors` collection with fields such as `type`, `message`, and `parameter`. Do not make decisions from the English message alone; retain the status and structured error type in your logs. + +See [API errors](https://www.hellotext.com/api#errors). + +## 3. Reduce the request to the smallest valid example + +When a large payload fails: + +1. Keep the same endpoint and credentials. +2. Send only the documented required fields. +3. Confirm the smallest request succeeds. +4. Add optional fields back one group at a time. +5. Compare the first failing field with its API contract. + +Common `422` causes include: + +- Missing required names or delivery values. +- An unsupported enum value. +- A product, order, coupon, action, property, or customer profile ID from another business. +- A duplicate unique reference, code, or SKU. +- A custom property that was not defined before assigning its value. +- Sending `currency` without `amount` on an event. +- An invalid `tracked_at` value. + +## 4. Separate resource creation from event tracking + +A resource and an event answer different questions: + +- A product, order, coupon, or custom object describes **what** the activity involved. +- An event describes **what happened, to which customer, and when**. + +If an order exists but no purchase appears on the customer profile, verify the event request. If an event fails because its object is missing, verify resource synchronization first. + +For tracked events, confirm: + +- The action name is exact and exists for the business. +- Either `profile` or `session` resolves correctly. +- `object` belongs to the expected resource type. +- `tracked_at` represents the original event time. +- `amount` and `currency` are both present when monetary value is sent. + +## 5. Interpret a received event correctly + +A valid tracking request returns HTTP `200` with: + +```json +{ + "status": "received" +} +``` + +This confirms receipt for processing, not that every downstream profile, segment, playbook, and report has refreshed immediately. + +If the event still does not appear after a reasonable processing interval: + +1. Confirm the token and customer profile belong to the same business. +2. Confirm the action and object type match. +3. Check whether the event was sent with an old `tracked_at` value. +4. Confirm the same event was not already created by a native integration. +5. Inspect the customer profile activity before checking playbook or report results. + +Use [Troubleshoot missing signals or activity]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}) for the product-facing checks after the API request is valid. + +## 6. Find the cause of duplicate records + +Duplicates usually begin when identity changes between requests. + +For customer profiles: + +- Store the returned Hellotext profile ID. +- Normalize phone and email values before synchronization. +- Update the existing customer profile instead of creating one on every job. + +For products and orders: + +- Keep `source` constant. +- Keep `reference` constant. +- Keep SKUs stable and unique where used. +- Store the returned Hellotext ID. +- Do not let separate browser and backend implementations create parallel objects. + +For events: + +- Give each source event a stable internal ID. +- Keep an outbox or delivery record in your own system. +- Do not resend a request that already returned `status: received`. +- Deduplicate repeated source notifications before calling Hellotext. + +## 7. Retry without creating uncertain duplicates + +Safe retry behavior depends on the result: + +- Do not retry `400`, `401`, `403`, `404`, or `422` unchanged. +- Retry temporary network and `5xx` failures with progressive backoff and a maximum attempt count. +- Add random delay when several workers can retry together. +- Stop retrying permanent validation errors and send them to a review queue. + +A timeout is an unknown result: the server may have completed the request before the connection ended. Before repeating a resource-creation `POST`, reconcile your stored Hellotext ID, source reference, or recent API results. + +The API does not expose a general idempotency-key parameter. Your integration must preserve its own source-event identifier and delivery state. + +## 8. Log enough context without exposing secrets + +For each API call, keep: + +- Method and endpoint path. +- HTTP status. +- Structured error type and parameter. +- Source-system record or event ID. +- Hellotext resource ID when known. +- Request start time and duration. +- Attempt number. + +Redact: + +- Authorization tokens. +- Full phone numbers and email addresses. +- Message contents when they contain customer data. +- Complete request bodies containing personal or payment information. + +## 9. Run an end-to-end diagnostic + +Use this sequence to isolate the failing layer: + +1. Authenticate with a one-record profile request. +2. Create or retrieve one customer profile. +3. Create or retrieve one product. +4. Track one product view against that customer profile. +5. Create one order using the same product. +6. Track one real order event. +7. Confirm the event on the customer profile. +8. Only then check segments, playbooks, and reports. + +If the first failing step is clear, fix it before continuing. Later layers cannot compensate for an invalid resource or event. + +## 10. Contact Hellotext with a reproducible example + +If the documented request still fails, provide: + +- Hellotext business or workspace identifier. +- Endpoint and HTTP method. +- Date, time, and timezone of the request. +- HTTP status and sanitized response body. +- Sanitized source reference and Hellotext resource ID. +- Whether the failure is consistent or intermittent. +- The smallest payload that reproduces the problem, without the token or unnecessary personal data. + +See [Contact Hellotext support]({% link _troubleshooting-deliverability/contact-hellotext-support.md %}). + +## Related guides + +- [Integrate a custom store with Hellotext]({% link _developers/custom-store-integration.md %}) +- [Sync products and understand inventory availability]({% link _developers/products-and-inventory-with-api.md %}) +- [Create and track orders with the API]({% link _developers/orders-with-api.md %}) +- [Create and track coupons with the API]({% link _developers/coupons-with-api.md %}) +- [External tracking]({% link _developers/external-tracking.md %}) diff --git a/_i18n/es/developers/coupons-with-api.md b/_i18n/es/developers/coupons-with-api.md new file mode 100644 index 00000000..4a532788 --- /dev/null +++ b/_i18n/es/developers/coupons-with-api.md @@ -0,0 +1,129 @@ +Un objeto de cupón permite que Hellotext haga referencia a un código, su descripción y el destino donde el cliente puede canjearlo. Un evento de cupón registra que un cliente realmente canjeó ese código. + +Crear un cupón en Hellotext no crea el descuento en tu plataforma de eCommerce ni controla su elegibilidad, vencimiento, límite de uso o reglas de uso único. Primero crea y valida la promoción en el sistema que controla el checkout. + +Usa la [referencia de la API de cupones](https://www.hellotext.com/api#coupons) para consultar el contrato completo. + +## Antes de comenzar + +Prepara: + +- Un token privado de autorización para la API. +- Un código de cupón que ya funcione en la plataforma de eCommerce. +- Una URL pública donde el cliente pueda canjearlo. +- Una descripción breve que pueda utilizarse en un mensaje. +- Una referencia externa estable cuando el sistema de origen tenga una. +- El perfil del cliente y los datos de compra necesarios para confirmar el canje. + +## 1. Crea el descuento en el sistema de comercio + +Antes de crear el objeto del cupón en Hellotext, confirma en el sistema que controla el checkout: + +- Qué productos o clientes pueden usarlo. +- El monto o porcentaje de descuento. +- Las fechas de inicio y vencimiento. +- Si el código es de un solo uso o reutilizable. +- Si puede combinarse con otra promoción. +- La URL de destino final. + +Hellotext puede entregar y registrar el contexto del cupón, pero el sistema de comercio decide si el checkout lo acepta. + +## 2. Crea el objeto del cupón en Hellotext + +Crea el cupón correspondiente: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/coupons \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "code": "WELCOME10", + "description": "Obtén 10% de descuento en tu primera compra", + "destination_url": "https://shop.example.com/discount/WELCOME10", + "reference": "promotion-2026-welcome" + }' +``` + +El código distingue mayúsculas de minúsculas y debe ser único. Mantén la descripción dentro del límite compatible y asegúrate de que la URL de destino sea accesible públicamente. + +Guarda el `id` devuelto para el cupón. Consulta [Crear un cupón](https://www.hellotext.com/api#create_a_coupon) para ver todos los campos compatibles. + +## 3. Actualiza el mismo cupón cuando cambie su presentación + +Usa `PATCH /v1/coupons/:id` cuando cambie la descripción o la URL de destino. Conserva el mismo ID del cupón en Hellotext mientras siga representando la misma promoción. + +No conviertas un código vencido en una promoción sin relación solamente para reutilizar el registro. Crea un cupón nuevo cuando la oferta tenga otra identidad comercial, elegibilidad o código. + +Como las reglas del checkout viven en el sistema de comercio, actualizar el objeto en Hellotext no modifica esas reglas. + +## 4. Usa el cupón en un mensaje o playbook compatible + +Una vez que el cupón existe, puedes seleccionarlo donde Hellotext ofrezca soporte para cupones, como capturas, mensajes, rutas o playbooks compatibles. + +Antes del lanzamiento, prueba toda la experiencia del cliente: + +1. El mensaje muestra el código y la descripción esperados. +2. El destino abre la tienda y la oferta correctas. +3. El checkout acepta el código para un cliente elegible. +4. El vencimiento y la reutilización coinciden con la configuración del sistema de comercio. + +No prometas envío gratis, bundles u otro beneficio salvo que esa oferta exacta exista en el sistema de comercio. + +## 5. Registra un canje confirmado + +Envía `coupon.redeemed` únicamente después de que el sistema de comercio confirme que el cliente usó el cupón: + +```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": "coupon.redeemed", + "profile": "PROFILE_ID", + "object": "COUPON_ID", + "amount": 89.90, + "currency": "USD", + "tracked_at": 1786104000 + }' +``` + +Usa el valor monetario asociado con el canje confirmado según tu implementación de reportes. Envía `amount` y `currency` juntos y conserva la fecha original del evento. + +No envíes `coupon.redeemed` cuando el cupón se muestra, entrega, abre o copia. Esas acciones no demuestran que el checkout lo haya aceptado. + +Consulta [Registrar eventos de cupones](https://www.hellotext.com/api#track_coupon_events). + +## 6. Evita eventos de canje duplicados + +El objeto del cupón puede reutilizarse entre muchos clientes, pero cada canje confirmado es un evento separado. + +- Asigna un ID interno estable a cada canje del sistema de comercio. +- Procesa una sola vez la misma notificación del checkout. +- Márcala como enviada después de que Hellotext responda con `status: received`. +- No envíes el mismo canje desde el navegador y el backend. +- Conserva el mismo perfil del cliente e ID del cupón en los reintentos. + +La plataforma de comercio sigue siendo responsable de impedir que un código se canjee más veces de lo permitido por sus reglas. Hellotext debe recibir el resultado final confirmado. + +## 7. Verifica el flujo completo + +Usa un cupón de prueba y un cliente fácil de reconocer: + +- El código funciona en la tienda antes de agregarlo a Hellotext. +- El cupón de Hellotext abre el destino correcto. +- Un mensaje compatible muestra la oferta esperada. +- Un checkout sin éxito no crea `coupon.redeemed`. +- Un checkout exitoso crea un solo evento de canje en el perfil correcto del cliente. +- El monto, la moneda y la fecha reflejan la transacción real. + +Si falla la request del cupón o no aparece el evento de canje, usa [Soluciona una integración propia]({% link _developers/troubleshoot-custom-integration.md %}). + +## Guías relacionadas + +- [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 %}) +- [Formularios]({% link _captures/forms.md %}) +- [Popup de Sitio Web]({% link _captures/website-popup.md %}) diff --git a/_i18n/es/developers/custom-store-integration.md b/_i18n/es/developers/custom-store-integration.md index 0cebe2f8..9a7219d9 100644 --- a/_i18n/es/developers/custom-store-integration.md +++ b/_i18n/es/developers/custom-store-integration.md @@ -119,6 +119,8 @@ Mantén estables los valores de `source`, `reference` y SKU. Actualiza el produc 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. +El endpoint público de productos no expone actualmente la cantidad de stock ni la disponibilidad en tiempo real. No agregues valores de inventario dentro de `metadata` esperando que los usen los playbooks que dependen del stock. Lee [Sincroniza productos y entiende la disponibilidad de inventario]({% link _developers/products-and-inventory-with-api.md %}) antes de habilitar un flujo que dependa del inventario. + ## 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: @@ -178,7 +180,7 @@ Usa el evento que refleje lo que realmente ocurrió, como `order.placed`, `order 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. +Consulta [Crea y registra pedidos con la API]({% link _developers/orders-with-api.md %}), [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 @@ -376,6 +378,10 @@ Si faltan datos, usa [Soluciona señales o actividad faltante]({% link _troubles ## Guías relacionadas - [Resumen de desarrolladores y API]({% link _developers/developers-overview.md %}) +- [Sincroniza productos y entiende la disponibilidad de inventario]({% link _developers/products-and-inventory-with-api.md %}) +- [Crea y registra pedidos con la API]({% link _developers/orders-with-api.md %}) +- [Crea y registra cupones con la API]({% link _developers/coupons-with-api.md %}) +- [Soluciona una integración propia]({% link _developers/troubleshoot-custom-integration.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 %}) diff --git a/_i18n/es/developers/developers-overview.md b/_i18n/es/developers/developers-overview.md index 4dfbaa2d..17873173 100644 --- a/_i18n/es/developers/developers-overview.md +++ b/_i18n/es/developers/developers-overview.md @@ -23,6 +23,15 @@ La referencia de la API es la fuente de verdad para recursos, atributos, paráme Abre la [referencia de la API de Hellotext](https://www.hellotext.com/api). +## Recetas de implementación con la API + +Usa las guías prácticas de la API cuando necesites pasar del contrato de un endpoint a un flujo de integración completo: + +- [Sincroniza productos y entiende la disponibilidad de inventario]({% link _developers/products-and-inventory-with-api.md %}) +- [Crea y registra pedidos con la API]({% link _developers/orders-with-api.md %}) +- [Crea y registra cupones con la API]({% link _developers/coupons-with-api.md %}) +- [Soluciona una integración propia]({% link _developers/troubleshoot-custom-integration.md %}) + ## Autenticación Las requests a la API usan bearer tokens. diff --git a/_i18n/es/developers/external-tracking.md b/_i18n/es/developers/external-tracking.md index 8338c60c..ee327d5a 100644 --- a/_i18n/es/developers/external-tracking.md +++ b/_i18n/es/developers/external-tracking.md @@ -203,6 +203,9 @@ Consulta la [referencia completa de tracking](https://www.hellotext.com/api#trac ## Guías relacionadas - [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) +- [Crea y registra pedidos con la API]({% link _developers/orders-with-api.md %}) +- [Crea y registra cupones con la API]({% link _developers/coupons-with-api.md %}) +- [Soluciona una integración propia]({% link _developers/troubleshoot-custom-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 %}) diff --git a/_i18n/es/developers/orders-with-api.md b/_i18n/es/developers/orders-with-api.md new file mode 100644 index 00000000..9a4c4270 --- /dev/null +++ b/_i18n/es/developers/orders-with-api.md @@ -0,0 +1,174 @@ +Un pedido en Hellotext tiene dos partes complementarias: + +- El **objeto del pedido** guarda la representación comercial: referencia, origen, productos, cantidades, precios, modalidad de entrega y otros datos del pedido. +- Un **evento del pedido** conecta ese pedido con un perfil del cliente en un momento real de su ciclo, como creación, confirmación, envío, entrega o cancelación. + +Crear solamente el objeto del pedido no registra una compra para un cliente. Crea o encuentra el pedido, conserva su ID de Hellotext y luego envía el evento del ciclo con ese pedido y el perfil correcto del cliente. + +Usa la [referencia de la API](https://www.hellotext.com/api#orders) para consultar el contrato completo. Esta guía explica el flujo de integración recomendado. + +## Antes de comenzar + +Prepara: + +- Un token privado de autorización para la API guardado únicamente en tu backend. +- El ID en Hellotext del perfil del cliente asociado con el pedido. +- Identificadores estables de productos o variantes ya sincronizados con Hellotext. +- Una `reference` estable para el pedido en tu sistema. +- Un mismo `source`, como `custom_store`, para todos los pedidos de la integración. +- Las fechas originales de los eventos, los montos y los códigos de moneda ISO 4217. + +Si todavía no sincronizaste los productos, comienza con [Sincroniza productos y entiende la disponibilidad de inventario]({% link _developers/products-and-inventory-with-api.md %}). + +## 1. Crea el objeto del pedido + +Crea el pedido después de que tu backend lo haya aceptado. Incluye la representación final de los artículos conocida en ese momento: + +```bash +curl --request POST \ + --url https://api.hellotext.com/v1/attribution/orders \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "name": "Pedido #1001", + "reference": "ORDER-1001", + "source": "custom_store", + "delivery": "deliver", + "payment_method": "Visa", + "sales_channel": "Website", + "items": [ + { + "product": "PRODUCT_ID", + "quantity": 2, + "price": { + "amount": 44.95, + "currency": "USD" + } + } + ], + "metadata": { + "warehouse": "main" + } + }' +``` + +Cada artículo requiere el identificador de un producto o variante. La API acepta su ID de Hellotext, referencia o SKU. Cuando omites el precio del artículo, Hellotext usa el precio actual del producto; incluye el precio cuando el pedido deba conservar el monto cobrado en el checkout. + +Hellotext calcula el total del pedido a partir de sus artículos cuando un flujo de tracking compatible no envía el total. Guarda el `id` devuelto para el pedido en tu sistema como `hellotext_order_id`. + +Consulta [Crear un pedido](https://www.hellotext.com/api#create_an_order) para ver todos los campos compatibles. + +## 2. Registra el primer evento real del ciclo + +Después de crear el pedido, conéctalo con el perfil del cliente usando el primer estado que tu backend pueda confirmar: + +```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", + "tracked_at": 1786104000 + }' +``` + +Usa `tracked_at` cuando el evento haya ocurrido antes de enviar la request. Debe representar la fecha del evento en el sistema de origen, no la fecha del reintento. + +Una request válida responde con: + +```json +{ + "status": "received" +} +``` + +Esto significa que el evento fue aceptado para su procesamiento. Puede demorar un poco en aparecer en el perfil del cliente y en los reportes. + +## 3. Envía cada estado posterior cuando ocurra + +Reutiliza el mismo ID del pedido y perfil del cliente para cada transición confirmada: + +- `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. + +Por ejemplo: + +```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.shipped", + "profile": "PROFILE_ID", + "object": "ORDER_ID", + "tracked_at": 1786190400 + }' +``` + +No envíes todos los estados al crear el pedido. No deduzcas el envío o la entrega solamente por el tiempo transcurrido. Cada evento debe provenir de una transición que tu sistema pueda verificar. + +Consulta [Registrar eventos de pedidos](https://www.hellotext.com/api#track_order_events) para ver las acciones y parámetros compatibles actualmente. + +## 4. Corrige los datos del pedido por separado de su ciclo + +Actualizar el objeto de un pedido modifica sus atributos almacenados; no crea un evento del ciclo. + +Usa `PATCH /v1/attribution/orders/:id` para corregir campos como modalidad de entrega, método de pago, canal de venta, metadata o propiedades personalizadas. Usa los endpoints de artículos del pedido cuando necesites corregir productos, cantidades o precios cobrados. + +Envía un evento nuevo únicamente cuando haya ocurrido un cambio real del ciclo. Por ejemplo, corregir el método de pago no justifica volver a enviar `order.confirmed`. + +Consulta [Actualizar un pedido](https://www.hellotext.com/api#update_an_order) y la [referencia de artículos de pedidos](https://www.hellotext.com/api#order_items). + +## 5. Importa pedidos históricos sin hacerlos parecer recientes + +Los pedidos históricos ayudan a Hellotext a entender actividad previa de clientes y productos. Para cada pedido importado: + +1. Crea el pedido con su referencia, origen, productos, cantidades y precios cobrados originales. +2. Registra únicamente el estado del ciclo que tus datos históricos puedan verificar. +3. Establece `tracked_at` con la fecha original del evento. +4. Conserva el monto y la moneda originales. + +No uses la fecha de importación como `tracked_at`. De lo contrario, compras antiguas pueden parecer comportamiento actual y afectar segmentos, decisiones de playbooks y reportes. + +## 6. Evita pedidos y eventos duplicados + +La API no expone un parámetro general de idempotencia. Tu integración debe conservar su propio estado de entrega. + +- Mantén `source` y `reference` estables durante toda la vida del pedido. +- Guarda el ID de Hellotext devuelto por la primera creación exitosa. +- Asigna un ID interno estable a cada transición del ciclo en el sistema de origen. +- Marca ese evento de origen como entregado únicamente después de que Hellotext responda con `status: received`. +- No envíes el mismo evento de pedido desde Hellotext.js y desde tu backend. +- Si vence el tiempo de una request de creación, reconcilia el pedido antes de enviar otro `POST`; la request original podría haberse completado. + +Hellotext evita guardar repetidamente la misma acción del ciclo para un pedido, pero tu integración igualmente debe evitar envíos duplicados y conservar un registro confiable del origen. + +## 7. Verifica un pedido de principio a fin + +Antes de importar todo el historial de pedidos: + +1. Crea un perfil de cliente de prueba fácil de reconocer. +2. Crea o recupera sus productos y variantes. +3. Crea un pedido y guarda el ID devuelto. +4. Envía un evento real del pedido. +5. Confirma que el evento aparezca en el perfil correcto del cliente. +6. Confirma productos, cantidades, monto, moneda y fecha original. +7. Envía un estado posterior y verifica que se reutilice el mismo pedido. + +Si la request falla o el evento no aparece, usa [Soluciona una integración propia]({% link _developers/troubleshoot-custom-integration.md %}). + +## Guías relacionadas + +- [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) +- [Sincroniza productos y entiende la disponibilidad de inventario]({% link _developers/products-and-inventory-with-api.md %}) +- [Seguimiento de origen externo]({% link _developers/external-tracking.md %}) +- [Seguimiento de eventos]({% link _developers/tracking-events.md %}) +- [Atribución de ventas]({% link _analytics-reporting-attribution/sales-attribution.md %}) diff --git a/_i18n/es/developers/products-and-inventory-with-api.md b/_i18n/es/developers/products-and-inventory-with-api.md new file mode 100644 index 00000000..33e6bed1 --- /dev/null +++ b/_i18n/es/developers/products-and-inventory-with-api.md @@ -0,0 +1,163 @@ +Los productos y variantes le dan a Hellotext el contexto de catálogo necesario para entender vistas de productos, carritos, pedidos, recomendaciones y playbooks relacionados con productos. + +La API pública de Productos sincroniza registros del catálogo. La cantidad y disponibilidad de stock en tiempo real son otro asunto: el endpoint público actual de productos no expone un campo específico de cantidad o disponibilidad de inventario. + +Usa la [referencia de la API](https://www.hellotext.com/api#products) para consultar los contratos completos de productos y variantes. Esta guía explica cómo mantener una identidad estable y cómo se diferencia la disponibilidad de inventario de la sincronización del catálogo. + +## Antes de comenzar + +Prepara: + +- Un token privado de autorización para la API guardado en tu backend. +- Un nombre de origen estable, como `custom_store`. +- Referencias permanentes de productos y variantes en tu sistema de comercio. +- SKU únicos cuando tu catálogo los utilice. +- URLs públicas para los productos y sus imágenes. +- Precios y códigos de moneda ISO 4217. +- Categorías, colecciones, etiquetas, marca y descripciones útiles para búsqueda y recomendaciones. + +Define qué registro es el producto principal y cuáles son sus variantes comprables antes de la primera sincronización. No cambies ese modelo entre importaciones. + +## 1. Elige una identidad estable para cada producto + +Usa estos campos de forma consistente: + +- `source`: el sistema propietario del catálogo, como `custom_store`. +- `reference`: el identificador permanente del producto o variante en ese origen. +- `sku`: el SKU del sistema de comercio cuando exista. + +No uses el nombre, la URL, el precio o la posición del producto en una importación como identidad. Esos valores pueden cambiar. + +Hellotext puede recuperar y actualizar productos por ID, referencia o SKU. De todos modos, guarda el ID de Hellotext devuelto; es el identificador más seguro para eventos y artículos de pedidos posteriores. + +## 2. Crea un producto y sus variantes + +Crea el producto principal con las variantes conocidas en ese momento: + +```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", + "source": "custom_store", + "brand": "Acme", + "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"], + "collection": ["Uso diario"], + "tags": ["Comodidad"], + "variants": [ + { + "name": "Championes Everyday / Negro / 42", + "reference": "variant-100-black-42", + "sku": "SKU-100-BLK-42", + "price": { + "amount": 89.90, + "currency": "USD" + } + } + ] + }' +``` + +El `name` del producto es obligatorio. Usa una URL de imagen accesible públicamente porque Hellotext necesita descargarla. + +Guarda los IDs devueltos para el producto y sus variantes. Consulta [Crear un producto](https://www.hellotext.com/api#create_a_product) para ver todos los campos compatibles. + +## 3. Actualiza el registro existente cuando cambie el catálogo + +No crees un producto nuevo porque cambió su precio, nombre, imagen, URL, categoría o etiquetas. + +Actualiza el producto existente por su ID de Hellotext, referencia o SKU: + +```bash +curl --request PATCH \ + --url https://api.hellotext.com/v1/attribution/products/product-100 \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "price": { + "amount": 79.90, + "currency": "USD" + }, + "tags": ["Comodidad", "Oferta"] + }' +``` + +Conserva el `source` y la `reference` originales. Usa los endpoints específicos de variantes para crear o actualizar variantes individuales en lugar de volver a crear el producto principal. + +Consulta [Actualizar un producto](https://www.hellotext.com/api#update_a_product) y [Variantes de productos](https://www.hellotext.com/api#product_variants). + +## 4. Entiende el límite del inventario + +Actualmente, la API pública de Productos no incluye un campo compatible para: + +- Cantidad actual en stock. +- Cantidad disponible para vender. +- Estado disponible o agotado. +- Saldos de inventario por ubicación. + +No agregues valores como `stock`, `quantity` o `available` dentro de `metadata` o propiedades personalizadas esperando que Hellotext los use en playbooks que dependen del inventario. La metadata no se convierte automáticamente en una señal de inventario compatible. + +Las integraciones compatibles de comercio y ERP pueden permitir que Hellotext consulte la disponibilidad directamente en el origen. Si una tienda propia necesita Alerta de Reposición, urgencia por poco stock u otro flujo que dependa de disponibilidad en tiempo real, conecta un origen de inventario compatible o confirma con Hellotext el camino de integración antes del lanzamiento. + +No elimines un producto solamente porque está agotado temporalmente. La eliminación corresponde a un producto que ya no debería permanecer en el catálogo activo de Hellotext. + +## 5. Registra actividad con el ID del producto + +Hellotext.js registra automáticamente la URL de la página, pero no puede deducir qué producto del catálogo representa. Envía `product.viewed` explícitamente: + +```javascript +await Hellotext.track('product.viewed', { + object: 'PRODUCT_ID', +}) +``` + +Usa el ID de la variante cuando el cliente haya elegido una variante específica y ese detalle sea relevante para el evento. + +En carritos y pedidos, reutiliza los mismos IDs de productos o variantes. No crees registros separados para la actividad del navegador, los artículos del carrito y los artículos del pedido. + +Consulta [Seguimiento de eventos]({% link _developers/tracking-events.md %}) y la [referencia de eventos de productos](https://www.hellotext.com/api#track_product_events). + +## 6. Diseña una sincronización segura del catálogo + +Una sincronización confiable debería: + +1. Leer los productos modificados en el sistema de origen. +2. Encontrarlos mediante el ID de Hellotext guardado o la referencia estable del origen. +3. Crear únicamente productos que no existan. +4. Actualizar los campos modificados en los productos existentes. +5. Crear o actualizar variantes por separado. +6. Conservar un mapeo entre los IDs del origen y los IDs de Hellotext. +7. Registrar errores de validación sin guardar el token de autorización. + +Para catálogos grandes, procesa lotes limitados y conserva el cursor o punto de control. Un lote fallido debe poder continuar sin volver a crear los productos que ya se sincronizaron correctamente. + +## 7. Verifica la calidad del catálogo + +Prueba un producto principal con al menos una variante: + +- El origen y la referencia coinciden con tu sistema de comercio. +- Los SKU son únicos y corresponden a las variantes correctas. +- El nombre, URL, imagen, marca, categorías, colección y etiquetas son útiles. +- El precio y la moneda coinciden con la tienda. +- Una vista de producto se resuelve con el mismo producto. +- Un pedido de prueba utiliza el mismo ID de producto o variante. +- Ningún playbook que dependa del inventario se habilita hasta que la disponibilidad en tiempo real tenga un origen compatible. + +Si aparecen duplicados o errores de validación, usa [Soluciona una integración propia]({% link _developers/troubleshoot-custom-integration.md %}). + +## Guías relacionadas + +- [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) +- [Crea y registra pedidos con la API]({% link _developers/orders-with-api.md %}) +- [Seguimiento de eventos]({% link _developers/tracking-events.md %}) +- [Verifica tus datos y señales después de configurar]({% link _integrations/verify-data-and-signals.md %}) +- [Playbook Alerta de Reposición]({% link _journeys/back-in-stock-pounce.md %}) diff --git a/_i18n/es/developers/troubleshoot-custom-integration.md b/_i18n/es/developers/troubleshoot-custom-integration.md new file mode 100644 index 00000000..cabae39d --- /dev/null +++ b/_i18n/es/developers/troubleshoot-custom-integration.md @@ -0,0 +1,193 @@ +Usa esta guía cuando una integración propia con la API o Hellotext.js devuelva errores, cree registros duplicados o envíe eventos que no aparezcan donde esperas. + +Comienza con un cliente fácil de reconocer y una sola request. Confirma cada nivel antes de probar una importación completa o habilitar playbooks. + +## 1. Confirma el token de la API y el negocio + +Prueba el token desde el backend: + +```bash +curl --request GET \ + --url https://api.hellotext.com/v1/profiles?limit=1 \ + --header "Authorization: Bearer $HELLOTEXT_API_TOKEN" +``` + +Comprueba que: + +- El header use `Authorization: Bearer TOKEN`. +- El token no haya sido revocado. +- Pertenezca al negocio de Hellotext esperado. +- Esté cargado únicamente en el entorno del backend. +- El negocio tenga acceso a la operación solicitada de la API. + +Nunca pegues el token en código del navegador, capturas de pantalla, tickets o logs de la aplicación. + +## 2. Lee el código HTTP antes del cuerpo de la respuesta + +Hellotext utiliza códigos HTTP estándar. Maneja cada categoría de forma diferente: + +| Código | Significado | Qué hacer | +| --- | --- | --- | +| `400` | La request está mal formada o falta un parámetro obligatorio. | Compara el cuerpo y el tipo de contenido con la referencia de la API. | +| `401` | El token falta, es inválido o fue revocado. | Reemplaza o corrige el token; no reintentes sin cambios. | +| `403` | El negocio o token no puede realizar la operación, normalmente porque el acceso a la API no está disponible para el estado actual del plan. | Revisa el acceso del negocio y el estado de la suscripción. | +| `404` | No se encontró el recurso, la acción o el identificador dentro de ese negocio. | Confirma el ID y que pertenezca al mismo negocio que el token. | +| `422` | La request llegó al endpoint, pero uno o más valores no pasaron la validación. | Lee todos los errores devueltos y corrige el parámetro indicado. | +| `500`, `502`, `503`, `504` | Hellotext o un servicio relacionado tuvo un problema temporal. | Reintenta de forma segura con espera progresiva. | + +Las respuestas de validación incluyen un objeto `error` o una colección `errors` con campos como `type`, `message` y `parameter`. No tomes decisiones solamente a partir del mensaje en inglés; conserva en tus logs el código y el tipo estructurado de error. + +Consulta [Errores de la API](https://www.hellotext.com/api#errors). + +## 3. Reduce la request al ejemplo válido más pequeño + +Cuando falla un payload grande: + +1. Conserva el mismo endpoint y credenciales. +2. Envía únicamente los campos obligatorios documentados. +3. Confirma que la request mínima funcione. +4. Vuelve a agregar los campos opcionales un grupo a la vez. +5. Compara el primer campo que falla con su contrato en la API. + +Causas frecuentes de `422`: + +- Falta un nombre obligatorio o una modalidad de entrega. +- Se envió un valor no compatible para una opción enumerada. +- El ID de un producto, pedido, cupón, acción, propiedad o perfil del cliente pertenece a otro negocio. +- Hay una referencia, código o SKU único duplicado. +- Se asignó una propiedad personalizada antes de crear su definición. +- Se envió `currency` sin `amount` en un evento. +- `tracked_at` tiene un valor inválido. + +## 4. Separa la creación de recursos del tracking de eventos + +Un recurso y un evento responden preguntas diferentes: + +- Un producto, pedido, cupón u objeto personalizado describe **qué elemento** participó en la actividad. +- Un evento describe **qué ocurrió, a qué cliente y cuándo**. + +Si el pedido existe, pero no aparece una compra en el perfil del cliente, revisa la request del evento. Si el evento falla porque no encuentra su objeto, revisa primero la sincronización del recurso. + +Para los eventos, confirma: + +- El nombre de la acción es exacto y existe para el negocio. +- `profile` o `session` se resuelve correctamente. +- `object` pertenece al tipo de recurso esperado. +- `tracked_at` representa la fecha original del evento. +- `amount` y `currency` están presentes cuando envías un valor monetario. + +## 5. Interpreta correctamente un evento recibido + +Una request válida de tracking responde con HTTP `200`: + +```json +{ + "status": "received" +} +``` + +Esto confirma que se recibió para su procesamiento, no que todos los perfiles, segmentos, playbooks y reportes relacionados se hayan actualizado inmediatamente. + +Si el evento todavía no aparece después de un intervalo razonable de procesamiento: + +1. Confirma que el token y el perfil del cliente pertenezcan al mismo negocio. +2. Confirma que coincidan la acción y el tipo de objeto. +3. Revisa si el evento se envió con un `tracked_at` antiguo. +4. Comprueba que una integración nativa no haya creado ya el mismo evento. +5. Revisa la actividad del perfil del cliente antes de mirar resultados de playbooks o reportes. + +Usa [Soluciona señales o actividad faltante]({% link _troubleshooting-deliverability/troubleshoot-missing-signals-or-activity.md %}) para las comprobaciones en el producto después de validar la request de la API. + +## 6. Encuentra la causa de registros duplicados + +Los duplicados normalmente comienzan cuando la identidad cambia entre requests. + +Para perfiles de clientes: + +- Guarda el ID del perfil devuelto por Hellotext. +- Normaliza teléfonos y emails antes de sincronizarlos. +- Actualiza el perfil existente del cliente en lugar de crear uno en cada job. + +Para productos y pedidos: + +- Mantén `source` constante. +- Mantén `reference` constante. +- Conserva SKU estables y únicos cuando los utilices. +- Guarda el ID devuelto por Hellotext. +- Evita que implementaciones separadas del navegador y el backend creen objetos paralelos. + +Para eventos: + +- Asigna un ID interno estable a cada evento del origen. +- Conserva un registro de salida o entrega en tu propio sistema. +- No vuelvas a enviar una request que ya respondió con `status: received`. +- Deduplica notificaciones repetidas del sistema de origen antes de llamar a Hellotext. + +## 7. Reintenta sin crear duplicados inciertos + +El comportamiento seguro depende del resultado: + +- No reintentes sin cambios respuestas `400`, `401`, `403`, `404` o `422`. +- Reintenta fallas temporales de red y errores `5xx` con espera progresiva y una cantidad máxima de intentos. +- Agrega una demora aleatoria cuando varios workers puedan reintentar al mismo tiempo. +- Deja de reintentar errores permanentes de validación y envíalos a una cola de revisión. + +Un timeout tiene un resultado incierto: el servidor podría haber completado la request antes de que terminara la conexión. Antes de repetir un `POST` de creación, reconcilia el ID de Hellotext almacenado, la referencia del origen o los resultados recientes de la API. + +La API no expone un parámetro general de idempotencia. Tu integración debe conservar su propio identificador del evento de origen y estado de entrega. + +## 8. Registra suficiente contexto sin exponer secretos + +Para cada llamada a la API, conserva: + +- Método y ruta del endpoint. +- Código HTTP. +- Tipo estructurado de error y parámetro. +- ID del registro o evento en el sistema de origen. +- ID del recurso en Hellotext cuando lo conozcas. +- Hora de inicio y duración de la request. +- Número de intento. + +Oculta: + +- Tokens de autorización. +- Números de teléfono y emails completos. +- Contenido de mensajes cuando incluya datos del cliente. +- Cuerpos completos de requests con información personal o de pagos. + +## 9. Ejecuta un diagnóstico de principio a fin + +Usa esta secuencia para aislar el nivel que falla: + +1. Autentica con una request de un solo perfil. +2. Crea o recupera un perfil del cliente. +3. Crea o recupera un producto. +4. Registra una vista de ese producto para el perfil del cliente. +5. Crea un pedido con el mismo producto. +6. Registra un evento real del pedido. +7. Confirma el evento en el perfil del cliente. +8. Recién entonces revisa segmentos, playbooks y reportes. + +Cuando identifiques el primer paso que falla, corrígelo antes de continuar. Los niveles posteriores no pueden compensar un recurso o evento inválido. + +## 10. Contacta a Hellotext con un ejemplo reproducible + +Si la request documentada sigue fallando, incluye: + +- Identificador del negocio o workspace de Hellotext. +- Endpoint y método HTTP. +- Fecha, hora y zona horaria de la request. +- Código HTTP y cuerpo de respuesta sin datos sensibles. +- Referencia del origen e ID del recurso de Hellotext, sin datos sensibles. +- Si el error es constante o intermitente. +- El payload mínimo que reproduce el problema, sin el token ni datos personales innecesarios. + +Consulta [Contacta al soporte de Hellotext]({% link _troubleshooting-deliverability/contact-hellotext-support.md %}). + +## Guías relacionadas + +- [Integra una tienda propia con Hellotext]({% link _developers/custom-store-integration.md %}) +- [Sincroniza productos y entiende la disponibilidad de inventario]({% link _developers/products-and-inventory-with-api.md %}) +- [Crea y registra pedidos con la API]({% link _developers/orders-with-api.md %}) +- [Crea y registra cupones con la API]({% link _developers/coupons-with-api.md %}) +- [Seguimiento de origen externo]({% link _developers/external-tracking.md %}) From d9c30e8b052f16055e58d1b705990ac83ad2431b Mon Sep 17 00:00:00 2001 From: Martin Caetano Date: Fri, 7 Aug 2026 14:10:25 -0300 Subject: [PATCH 2/2] Clarify order event deduplication --- _i18n/en/developers/external-tracking.md | 4 +++- _i18n/en/developers/orders-with-api.md | 4 +++- _i18n/es/developers/external-tracking.md | 4 +++- _i18n/es/developers/orders-with-api.md | 4 +++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/_i18n/en/developers/external-tracking.md b/_i18n/en/developers/external-tracking.md index b8b0caa3..83dd384c 100644 --- a/_i18n/en/developers/external-tracking.md +++ b/_i18n/en/developers/external-tracking.md @@ -190,7 +190,9 @@ Record the status and error in your logs, but never log the token or complete cu ## 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. +Most accepted tracking requests can create a new event, even when the same object is reused. Finding the same object through `reference` and `source` does not remove repeated events. + +Built-in order lifecycle actions are a narrow exception: Hellotext stores one event for each order and action pair, such as one `order.shipped` event for a given order. This does not provide general request idempotency. Other event types can still be duplicated, so prevent repeated submissions in your integration. - Store which source event has already been accepted by Hellotext in your own system. - Do not retry `200` responses. diff --git a/_i18n/en/developers/orders-with-api.md b/_i18n/en/developers/orders-with-api.md index 1019b408..056c3524 100644 --- a/_i18n/en/developers/orders-with-api.md +++ b/_i18n/en/developers/orders-with-api.md @@ -149,7 +149,9 @@ The API does not expose an idempotency-key parameter. Your integration must keep - Do not send the same order event from Hellotext.js and your backend. - If a create request times out, reconcile the order before sending another `POST`; the original request may have completed. -Hellotext avoids storing the same lifecycle action repeatedly for one order, but your integration should still prevent duplicate submissions and preserve a reliable source log. +For built-in order lifecycle actions, Hellotext stores one event for each order and action pair. For example, sending `order.shipped` again for the same order does not add another shipment event. + +This rule is not general API idempotency. Other event types can still be duplicated, and a different lifecycle action for the same order remains a separate event. Your integration should prevent duplicate submissions and preserve a reliable source log. ## 7. Verify one order end to end diff --git a/_i18n/es/developers/external-tracking.md b/_i18n/es/developers/external-tracking.md index ee327d5a..f3364df2 100644 --- a/_i18n/es/developers/external-tracking.md +++ b/_i18n/es/developers/external-tracking.md @@ -190,7 +190,9 @@ Registra el código y el error en tus logs, pero nunca guardes el token ni datos ## 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. +La mayoría de las requests de tracking aceptadas pueden crear un evento nuevo, aunque reutilices el mismo objeto. Encontrar el mismo objeto por `reference` y `source` no elimina eventos repetidos. + +Las acciones preestablecidas del ciclo de un pedido son una excepción específica: Hellotext guarda un evento por cada combinación de pedido y acción, como un solo evento `order.shipped` para un pedido determinado. Esto no ofrece idempotencia general para las requests. Otros tipos de eventos todavía pueden duplicarse, por lo que debes evitar envíos repetidos desde tu integración. - Guarda en tu sistema qué evento de origen ya fue aceptado por Hellotext. - No reintentes respuestas `200`. diff --git a/_i18n/es/developers/orders-with-api.md b/_i18n/es/developers/orders-with-api.md index 9a4c4270..6c4af183 100644 --- a/_i18n/es/developers/orders-with-api.md +++ b/_i18n/es/developers/orders-with-api.md @@ -149,7 +149,9 @@ La API no expone un parámetro general de idempotencia. Tu integración debe con - No envíes el mismo evento de pedido desde Hellotext.js y desde tu backend. - Si vence el tiempo de una request de creación, reconcilia el pedido antes de enviar otro `POST`; la request original podría haberse completado. -Hellotext evita guardar repetidamente la misma acción del ciclo para un pedido, pero tu integración igualmente debe evitar envíos duplicados y conservar un registro confiable del origen. +Para las acciones preestablecidas del ciclo de un pedido, Hellotext guarda un evento por cada combinación de pedido y acción. Por ejemplo, volver a enviar `order.shipped` para el mismo pedido no agrega otro evento de envío. + +Esta regla no es idempotencia general de la API. Otros tipos de eventos todavía pueden duplicarse y una acción diferente del ciclo para el mismo pedido sigue siendo otro evento. Tu integración debe evitar envíos duplicados y conservar un registro confiable del origen. ## 7. Verifica un pedido de principio a fin