# Create Your App Source: https://docs.vambe.me/docs/app-platform/create-your-app Register an ecommerce app, configure its OAuth and capabilities, and submit it for review. ## Register an app Create your app with a single authenticated request. Authentication uses your Vambe API key in the `x-api-key` header. ```bash theme={null} curl --request POST 'https://api.vambe.me/api/ecommerce-app' \ --header 'x-api-key: your_api_key_here' \ --header 'Content-Type: application/json' \ --data '{ "name": "My Ecommerce X", "description": "Connects My Ecommerce X stores to Vambe.", "logo_url": "https://cdn.myecommerce.com/vambe/logo.png", "website_url": "https://myecommerce.com", "developer_name": "My Ecommerce X Inc.", "contact_email": "integrations@myecommerce.com", "contact_phone": "+56912345678", "oauth": { "authorize_url": "https://myecommerce.com/oauth/authorize", "token_url": "https://myecommerce.com/oauth/token", "client_id": "vambe-client-id", "client_secret": "vambe-client-secret", "scopes": ["read_orders", "read_products"], "account_info_url": "https://api.myecommerce.com/vambe/account" }, "capabilities": { "inbound_events": ["order", "checkout", "fulfillment", "product"], "outbound": { "order_get": { "url": "https://api.myecommerce.com/vambe/orders" }, "stock_get": { "url": "https://api.myecommerce.com/vambe/stock" }, "checkout_create": { "url": "https://api.myecommerce.com/vambe/checkout" } } } }' ``` The response includes a **`signing_secret`**: ```json theme={null} { "id": "f1e2d3c4-…", "slug": "my-ecommerce-x", "status": "draft", "signing_secret": "9b1f…(64 hex chars)…", "...": "..." } ``` > [!WARNING] > > The `signing_secret` is returned **only on creation** (and on rotation). Store it securely — > you need it to sign every inbound webhook. You can rotate it later, but it is never shown > again on read. ## Fields ### Metadata **name** `string` *required* Display name shown to merchants. **slug** `string` Stable identifier. Auto-derived from `name` if omitted; must be unique. **description** `string` *required* Short description shown in the connect UI. **logo\_url** `string (https)` *required* Public URL of your app logo. **website\_url** `string (https)` Your marketing/site URL. ### Contact (required) The Vambe team uses these to reach you during review and operations. **developer\_name** `string` *required* Your company/organization name. **contact\_email** `string` *required* Contact email. **contact\_phone** `string` *required* Contact phone number. ### OAuth See [OAuth Connection](/docs/app-platform/oauth-connection) for the full flow. **oauth.authorize\_url** `string (https)` *required* Where Vambe redirects the merchant to approve scopes. **oauth.token\_url** `string (https)` *required* Where Vambe exchanges the authorization code for tokens. **oauth.client\_id** `string` *required* The client id you issued for Vambe. **oauth.client\_secret** `string` *required* The client secret you issued for Vambe. Stored encrypted at rest. **oauth.scopes** `string[]` Scopes requested during authorization. **oauth.account\_info\_url** `string (https)` Optional. Lets Vambe fetch the store identity after connection — required for multi-store apps. ### Capabilities **capabilities.inbound\_events** `string[]` Which canonical events you commit to pushing: any of `order`, `checkout`, `fulfillment`, `product`. See [Inbound Webhooks](/docs/app-platform/inbound-webhooks). **capabilities.outbound** `object` URLs Vambe calls on demand. Each entry is `{ "url": "https://..." }`. Supported keys: `order_get`, `stock_get`, `checkout_create`. If you omit a key, Vambe simply won't offer that assistant tool for your app. See [Outbound Capabilities](/docs/app-platform/outbound-capabilities). ## Manage and submit **1. Iterate (draft)** Update the app while it is `draft` or `rejected`: ```bash theme={null} curl --request PATCH 'https://api.vambe.me/api/ecommerce-app/{id}' \ --header 'x-api-key: your_api_key_here' \ --header 'Content-Type: application/json' \ --data '{ "description": "Updated copy" }' ``` **2. Submit for review** ```bash theme={null} curl --request POST 'https://api.vambe.me/api/ecommerce-app/{id}/submit' \ --header 'x-api-key: your_api_key_here' ``` This moves the app to `pending_review` and notifies the Vambe team. **3. Get approved** Once Vambe approves it, the app becomes `approved` and is installable by any account. Until then it is visible only to your account. ### Other endpoints | Method | Path | Purpose | | - | - | - | | `GET` | `/api/ecommerce-app` | List your apps. | | `GET` | `/api/ecommerce-app/{id}` | App detail (no secret). | | `POST` | `/api/ecommerce-app/{id}/rotate-secret` | Generate a new signing secret. | | `DELETE` | `/api/ecommerce-app/{id}` | Delete the app. | | `GET` | `/api/ecommerce-app/available` | Apps installable by the current account. | > [!NOTE] > > Editing an `approved` app is blocked — only `draft`/`rejected` apps are editable. Editing a > `rejected` app moves it back to `draft` so you can resubmit. # Inbound Webhooks Source: https://docs.vambe.me/docs/app-platform/inbound-webhooks Push canonical events (orders, checkouts, fulfillment, products) to Vambe. Vambe ingests them into the same pipeline as native integrations. ## Overview Your platform **pushes** events to Vambe as they happen. Each event is a canonical JSON payload — you map your own data onto Vambe's shape, so there is no per-provider code on Vambe's side. All inbound endpoints are: ``` POST https://api.vambe.me/api/public/apps/{appId}/events/{event} ``` | Event | Path | Purpose | | - | - | - | | Order | `/events/order` | A paid/created order. | | Checkout | `/events/checkout` | An abandoned checkout to recover. | | Fulfillment | `/events/fulfillment` | A shipment created/updated. | | Product upsert | `/events/product` | Create or update a product. | | Product delete | `/events/product/delete` | Remove a product. | ## Authenticating your webhooks Every request must be signed with your app's **signing secret** (the `signing_secret` from [Create Your App](/docs/app-platform/create-your-app)). Compute an HMAC-SHA256 (hex) over the string `{timestamp}.{rawBody}` and send: | Header | Value | | - | - | | `x-vambe-timestamp` | Current time in epoch milliseconds. | | `x-vambe-signature` | `HMAC_SHA256(signing_secret, "{timestamp}.{rawBody}")` as hex. | > [!WARNING] > > Sign and send the **exact same body bytes**. Vambe verifies the signature against the raw > request body — re-serializing differently will fail verification. Requests older than > **5 minutes** are rejected. ```javascript theme={null} import crypto from 'crypto'; function postEvent(appId, event, payload, signingSecret) { const timestamp = Date.now().toString(); const body = JSON.stringify(payload); // sign and send these exact bytes const signature = crypto .createHmac('sha256', signingSecret) .update(`${timestamp}.${body}`) .digest('hex'); return fetch(`https://api.vambe.me/api/public/apps/${appId}/events/${event}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-vambe-timestamp': timestamp, 'x-vambe-signature': signature, }, body, }); } ``` A `2xx` response means the event was accepted. **Retry on any non-2xx** — Vambe is idempotent on the entity's external id. ## The envelope Every payload is an envelope with two optional routing fields plus the entity: ```json theme={null} { "external_store_id": "store_12345", "event_id": "evt_abc", "order": { "...": "..." } } ``` **external\_store\_id** `string` Your identifier for the merchant store. Used to resolve the installation (see below). **event\_id** `string` Your event id. Advisory today; reserved for explicit de-duplication. ### Resolving the installation A single app can be installed by many merchants, so Vambe must map each webhook to the right installation: * **Multi-store:** send `external_store_id` matching the `external_id` Vambe captured from your [`account_info_url`](/docs/app-platform/oauth-connection). Vambe resolves by `(app, external_id)`. * **Single installation:** if the app has exactly one installation, it resolves automatically even without `external_store_id`. If no installation can be resolved, Vambe responds `404`. ## Order `POST /api/public/apps/{appId}/events/order` ```json theme={null} { "external_store_id": "store_12345", "order": { "external_id": "1001", "external_name": "#1001", "currency": "CLP", "total_price": 29990, "status_url": "https://myecommerce.com/orders/1001/status", "details_url": "https://admin.myecommerce.com/orders/1001", "customer": { "name": "Jane Doe", "phone": "+56912345678", "email": "jane@example.com" }, "line_items": [ { "external_product_id": "sku-001", "quantity": 2 } ], "metadata": { "note": "gift wrap" }, "external_checkout_id": "chk_abc123" } } ``` > [!NOTE] > > The customer **phone** is the most important field: it is how Vambe links the order to the > WhatsApp contact. Send it in E.164 format when possible. Products are matched by > `external_product_id` against the catalog you synced. > [!NOTE] > > **`external_checkout_id` attributes the sale.** When the order was paid through a checkout > Vambe requested via > [`checkout_create`](/docs/app-platform/outbound-capabilities#sale-attribution), include the > same id you returned there. Vambe uses it to credit the sale to the assistant conversation > that produced the checkout. Omit it (or send `null`) for orders that did not come from a > Vambe checkout. ## Checkout (abandoned) `POST /api/public/apps/{appId}/events/checkout` ```json theme={null} { "external_store_id": "store_12345", "checkout": { "external_id": "chk_555", "external_name": "Checkout 555", "currency": "CLP", "total_price": 19990, "recover_url": "https://myecommerce.com/checkout/chk_555", "details_url": "https://admin.myecommerce.com/checkouts/chk_555", "customer": { "name": "Jane Doe", "phone": "+56912345678", "email": "jane@example.com" }, "line_items": [ { "external_product_id": "sku-001", "quantity": 1 } ] } } ``` > [!NOTE] > > `customer.phone` and `recover_url` are required for recovery: Vambe resolves (or creates) the > contact by phone and records the abandoned checkout with its recovery link. For checkouts that > Vambe requested via `checkout_create`, `external_id` must be the same id you returned as > `external_checkout_id` — that is how the abandoned checkout is tied back to the conversation. ## Fulfillment `POST /api/public/apps/{appId}/events/fulfillment` ```json theme={null} { "external_store_id": "store_12345", "fulfillment": { "order_external_id": "1001", "fulfillment_external_id": "ful_900", "tracking_number": "TRACK123", "type": "delivery", "delivery_address": { "recipient_name": "Jane Doe", "phone": "+56912345678", "address_line_1": "Av. Siempre Viva 742", "address_line_2": null, "city": "Santiago", "region": "RM", "country": "CL", "postal_code": "8320000" } } } ``` | Field | Notes | | - | - | | `order_external_id` | Links the shipment to the order. | | `fulfillment_external_id` | Unique id of this fulfillment (Vambe upserts on it). | | `type` | `delivery` or `pickup` (defaults to `delivery`). | ## Products Products are **incremental** — each event affects only the product you send. Vambe never deletes the rest of your catalog from a webhook. ### Upsert (create or update) `POST /api/public/apps/{appId}/events/product` ```json theme={null} { "external_store_id": "store_12345", "product": { "external_id": "sku-001", "name": "Premium Coffee Beans", "description": "Arabica from Colombia, medium roast.", "price": 12990, "currency": "CLP", "sku": "COF-001", "file_url": "https://cdn.myecommerce.com/coffee.jpg", "image_urls": ["https://cdn.myecommerce.com/coffee.jpg"], "metadata": [{ "key": "roast", "value": "medium" }] } } ``` Vambe upserts by `(external_id, store)`: a new `external_id` is created, an existing one is updated. Product embeddings (for AI search and recommendations) run automatically. ### Delete `POST /api/public/apps/{appId}/events/product/delete` ```json theme={null} { "external_store_id": "store_12345", "external_id": "sku-001" } ``` This soft-deletes the product for that store. > [!NOTE] > > Catalog over webhook is the **push** model. If you'd rather have Vambe **pull** your full > catalog instead, that is handled by the `products_list` outbound capability — talk to the > Vambe team about which model fits your platform. # Custom Ecommerce Apps Overview Source: https://docs.vambe.me/docs/app-platform/introduction Build a full ecommerce integration with Vambe by registering an app. You write the code on your side; Vambe never has to write code to integrate with you. ## What are Custom Ecommerce Apps? **Custom Ecommerce Apps** let any ecommerce provider build a first-class integration with Vambe — products, orders, abandoned checkouts, fulfillment and live assistant tools — **without Vambe writing any code for you**. You register an app, implement a small, well-defined contract, and Vambe handles the rest. It works in two directions: > [card] Inbound — you push to Vambe > > Your platform sends canonical webhooks (orders, checkouts, fulfillment, products) > to Vambe. Vambe ingests them into the same pipeline used by native integrations. > [card] Outbound — Vambe calls you > > When the AI assistant needs live data (order status, stock, a checkout link), > Vambe calls URLs you declared, authenticated with the merchant's OAuth token. ## Core model There are two distinct concepts: | Concept | What it is | Who owns it | | - | - | - | | **App** | The integration definition you register once: metadata, OAuth config, and which capabilities you support. | You (the provider) | | **Installation** | A single merchant connecting their store to your app via OAuth. Each installation holds that merchant's access token. | A Vambe account (the merchant) | One approved app can be installed by many merchants. Every webhook and every outbound call is scoped to a single installation. ## How a provider integrates — end to end **1. Register your app** Create the app with your metadata, contact details, OAuth endpoints, and the capabilities you support. You receive a **signing secret** (shown once). **2. Test on your own account** While unapproved, your app is visible only to the account that created it. Install it on your own store and exercise the full flow. **3. Submit for review** Submit the app. The Vambe team is notified and reviews it. Once approved, the app becomes available to every Vambe account. **4. Merchants connect via OAuth** A merchant clicks **Connect** in Vambe and is redirected to your site to approve permissions. Vambe exchanges the code for an access token and stores the installation. **5. Data flows both ways** You push canonical webhooks; Vambe calls your capability URLs on demand. No per-provider code on Vambe's side. ## App lifecycle An app moves through these states: | State | Visible to | Meaning | | - | - | - | | `draft` | Creator only | Being built/edited. | | `pending_review` | Creator only | Submitted; awaiting Vambe approval. | | `approved` | All accounts | Live and installable by any merchant. | | `rejected` | Creator only | Needs changes; edit and resubmit. | | `suspended` | Nobody | Disabled by Vambe; stops receiving events and outbound calls. | > [!NOTE] > > The connection between a merchant and your app is **always OAuth 2.0**. Merchants never > type API keys into Vambe — they approve scopes on your own page. ## Next steps > [card] [Create your app](/docs/app-platform/create-your-app) > > Register the app and get your signing secret. > [card] [OAuth connection](/docs/app-platform/oauth-connection) > > Implement the merchant connection flow. > [card] [Inbound webhooks](/docs/app-platform/inbound-webhooks) > > Push orders, checkouts, fulfillment and products. > [card] [Outbound capabilities](/docs/app-platform/outbound-capabilities) > > Answer the assistant's live data requests. # OAuth Connection Source: https://docs.vambe.me/docs/app-platform/oauth-connection Merchants connect to your app via standard OAuth 2.0. Vambe redirects them to your site, exchanges the code, and stores an access token per installation. ## Why OAuth A merchant connects their store to your app **only through OAuth 2.0 authorization code**. They are redirected to *your* site to approve scopes — Vambe never collects their credentials in a form. The access token you return is the credential Vambe uses for every [outbound call](/docs/app-platform/outbound-capabilities). ## Fixed redirect URI Register this exact callback in your OAuth app: ``` https://api.vambe.me/api/public/apps/oauth/callback ``` ## The flow **1. Merchant starts the connection** In Vambe the merchant clicks **Connect** on your app. Vambe builds the authorization URL from your `oauth.authorize_url` and redirects the merchant's browser to: ``` {authorize_url} ?response_type=code &client_id={your client_id} &redirect_uri=https://api.vambe.me/api/public/apps/oauth/callback &scope={space-separated scopes} &state={opaque, signed by Vambe} ``` > [!WARNING] > > Treat `state` as opaque and echo it back unchanged. It is encrypted by Vambe and binds > the callback to the right app and merchant. **2. Merchant approves on your site** Your authorization page authenticates the merchant and asks them to approve the scopes. **3. You redirect back with a code** Redirect to the fixed `redirect_uri` with the `code` and the original `state`: ``` https://api.vambe.me/api/public/apps/oauth/callback?code={auth_code}&state={state} ``` **4. Vambe exchanges the code** Vambe POSTs your `oauth.token_url` (`application/x-www-form-urlencoded`): ``` grant_type=authorization_code code={auth_code} redirect_uri=https://api.vambe.me/api/public/apps/oauth/callback client_id={your client_id} client_secret={your client_secret} ``` Respond with JSON: ```json theme={null} { "access_token": "the-merchant-access-token", "refresh_token": "optional", "expires_in": 3600, "scope": "read_orders read_products" } ``` > [!NOTE] > > The `access_token` you return is sent back to you as `Authorization: Bearer …` on every > outbound call. Make it a token that authorizes API access for that specific store. **5. (Optional) Vambe fetches the store identity** If you set `oauth.account_info_url`, Vambe immediately calls it (`GET`, with `Authorization: Bearer {access_token}`) and expects: ```json theme={null} { "external_id": "store_12345", "name": "Acme Store" } ``` Vambe stores `external_id` on the installation. This is **required for multi-store apps**: it lets inbound webhooks resolve which merchant an event belongs to (see [Inbound Webhooks → resolving the installation](/docs/app-platform/inbound-webhooks#resolving-the-installation)). ## After connection Vambe creates an installation (an api token) bound to your app, holding the merchant's `access_token` (encrypted) and `external_id`. From here: * You can start pushing [inbound webhooks](/docs/app-platform/inbound-webhooks) for that store. * Vambe can call your [outbound capabilities](/docs/app-platform/outbound-capabilities) for that store. > [!NOTE] > > Token refresh: store the `refresh_token` and `expires_in` you return; managed refresh on > Vambe's side is on the roadmap. For now, return long-lived access tokens or tokens you can > validate server-side on each outbound call. # Outbound Capabilities Source: https://docs.vambe.me/docs/app-platform/outbound-capabilities Expose URLs that Vambe calls on demand so the AI assistant can fetch live order status, stock, and create checkout links. ## Overview Some assistant tools need **live** data that does not arrive via webhooks — "where is my order?", "is this in stock?", "send me a checkout link". For those, Vambe calls URLs you declare in `capabilities.outbound`. You expose an endpoint per capability; Vambe calls it on demand. If you don't declare a capability, Vambe simply won't offer that tool for your app. ## How Vambe calls you Every outbound request is an HTTP `POST` with a JSON body and these headers: | Header | Value | | - | - | | `Authorization` | `Bearer {access_token}` — the merchant's OAuth token from connection. | | `X-Vambe-Store-Id` | The store's `external_id` (from `account_info_url`), when available. | | `Content-Type` | `application/json` | Use the bearer token (and store id) to scope the response to the right merchant. > [!WARNING] > > **Security requirements.** Capability URLs must be **HTTPS** and must resolve to a public IP — > Vambe blocks requests to private, loopback, and link-local addresses. Respond within **\~15 > seconds**; on timeout or error Vambe degrades gracefully (the tool returns no data). ## `order_get` — live order status Vambe calls this when the assistant is asked about an order's status. **Request** ```json theme={null} { "order_id": "vambe-internal-uuid", "order_external_id": "1001" } ``` **Response** — the canonical order status shape: ```json theme={null} { "fulfillmentStatus": "fulfilled", "statusPageUrl": "https://myecommerce.com/orders/1001/status", "financialStatus": "paid", "tags": [], "shippingLine": { "title": "Standard", "deliveryCategory": "shipping" }, "createdAt": "2026-06-10T12:00:00Z", "cancelledAt": null, "closedAt": null, "cancelReason": null, "fulfillments": [ { "status": "delivered", "deliveredAt": "2026-06-12T09:30:00Z", "fulfillmentAt": "2026-06-10T18:00:00Z", "estimatedDeliveryAt": "2026-06-12T00:00:00Z", "trackingInfo": [ { "company": "Correos", "number": "TRACK123", "url": "https://track/TRACK123" } ], "items": [{ "quantity": 2, "variantName": "Premium Coffee Beans" }] } ] } ``` All fields except `fulfillmentStatus`, `tags`, and `fulfillments` are optional. ## `stock_get` — stock by location Vambe calls this when the assistant needs live inventory. **Request** ```json theme={null} { "product_external_ids": ["sku-001", "sku-002"] } ``` **Response** — an array, one entry per product: ```json theme={null} [ { "externalId": "sku-001", "locations": [ { "locationName": "Main Warehouse", "locationAddress": "Santiago, CL", "stockQuantity": 12 }, { "locationName": "Store #2", "locationAddress": "Valparaíso, CL", "stockQuantity": 0 } ] } ] ``` ## `checkout_create` — create a checkout link Vambe calls this when the assistant builds a cart and needs a payable link to send the customer. **Request** ```json theme={null} { "items": [ { "external_product_id": "sku-001", "quantity": 2 } ], "customer": { "checkoutEmail": "jane@example.com", "name": "Jane", "lastName": "Doe", "address": "Av. Siempre Viva 742", "city": "Santiago" }, "ai_contact_id": "contact-uuid", "assistant_id": "assistant-uuid", "marketplace_source": "whatsapp" } ``` **Response** — the checkout link (full URL; Vambe shortens it before sending) and the id of the checkout you created: ```json theme={null} { "link": "https://myecommerce.com/checkout/abc123", "external_checkout_id": "chk_abc123", "stockAdjustments": [ { "productExternalId": "sku-001", "requestedQuantity": 2, "availableStock": 1, "adjustedQuantity": 1 } ] } ``` `external_checkout_id` is **required**: it is your own id for the checkout behind the link. Vambe records at this moment which conversation produced the checkout, keyed by that id — see [Sale attribution](#sale-attribution) below. If your ids are numeric, send them as numbers or as strings — Vambe accepts both here and on the order and checkout webhooks, and stores them in their string form. Ids above JSON's safe integer range (2^53 - 1, i.e. `9007199254740991`) **must** be sent as strings: above that, JSON parsers silently round the value and two different checkouts can collapse onto the same id, so Vambe rejects them. `stockAdjustments` is optional — include it if you clamped quantities to available stock. Return `{ "link": null }` if a link cannot be created; you may add an optional `error` string explaining why (it is logged on Vambe's side, never shown to the shopper). ### Sale attribution When the shopper later pays, your [order webhook](/docs/app-platform/inbound-webhooks) must include the same id as `external_checkout_id`. That is the only thing Vambe needs to credit the sale to the assistant conversation that produced it: 1. You respond to `checkout_create` with `external_checkout_id`. 2. Vambe stores the attribution (conversation ↔ checkout) on its side. 3. Your order webhook repeats `external_checkout_id`; Vambe looks the checkout up and attributes the order. If the response omits `external_checkout_id`, the link still reaches the shopper but the sale can never be attributed — the app checklist fails the `checkout_create` check for this reason. One checkout attributes at most one order. ## Reserved capability — `products_list` If you prefer Vambe to **pull** your full catalog instead of pushing product webhooks, the `products_list` capability key is reserved for that model. Coordinate with the Vambe team before relying on it. # Reference Source: https://docs.vambe.me/docs/app-platform/reference Security model, lifecycle, event types, supported currencies and operational notes for Custom Ecommerce Apps. ## Security model | Direction | Auth | Detail | | - | - | - | | Inbound (you → Vambe) | HMAC-SHA256 | Sign `{timestamp}.{rawBody}` with your `signing_secret`; send `x-vambe-signature` + `x-vambe-timestamp`. 5-minute freshness window. | | Outbound (Vambe → you) | Bearer token | Vambe sends `Authorization: Bearer {merchant access_token}` + `X-Vambe-Store-Id`. | | OAuth state | Encrypted | The `state` parameter is encrypted by Vambe; echo it back unchanged. | | Secrets at rest | AES-256 | Your `client_secret` and the app `signing_secret` are encrypted at rest. | > [!NOTE] > > Rotate your signing secret anytime with `POST /api/ecommerce-app/{id}/rotate-secret`. The new > secret is returned once; update your webhook signer before the old one stops being used. ### Outbound URL requirements * **HTTPS only.** * Must resolve to a **public IP** — private, loopback and link-local addresses are blocked (SSRF protection). * Respond within **\~15 seconds**. ## App lifecycle | State | Visible to | Editable | Receives events | | - | - | - | - | | `draft` | Creator | Yes | Yes (creator's own installs) | | `pending_review` | Creator | No | Yes | | `approved` | All accounts | No | Yes | | `rejected` | Creator | Yes (→ draft) | No | | `suspended` | Nobody | No | No | ## Event types ### Inbound (`capabilities.inbound_events`) | Event | Endpoint | | - | - | | `order` | `POST /api/public/apps/{appId}/events/order` | | `checkout` | `POST /api/public/apps/{appId}/events/checkout` | | `fulfillment` | `POST /api/public/apps/{appId}/events/fulfillment` | | `product` | `POST /api/public/apps/{appId}/events/product` and `…/product/delete` | ### Outbound (`capabilities.outbound`) | Capability | Tool it powers | | - | - | | `order_get` | Live order status ("where is my order?") | | `stock_get` | Stock by location | | `checkout_create` | Checkout link generation + sale attribution (via `external_checkout_id`) | | `products_list` | Reserved — catalog pull (coordinate with Vambe) | ## Supported currencies ISO codes accepted in `currency` / `total_price` / `price` fields: ``` CLP, USD, MXN, BRL, UF, ARS, COP, UYU, PEN, EUR, HNL, BOB, PYG, GTQ, NIO, PAB, CRC, DOP, VES, BZD, SRD, GYD ``` ## Operational notes * **Idempotency.** Orders, checkouts, fulfillments and products upsert on their external id — safe to retry. Always retry on non-2xx; webhooks may be redelivered. * **Product sync is incremental.** A product webhook only affects the product it carries; it never deletes the rest of your catalog. * **Multi-store resolution** depends on `account_info_url` populating `external_id`. Without it, only single-installation apps resolve automatically. * **Graceful degradation.** If an outbound capability is missing, slow, or errors, the corresponding assistant tool simply returns no data — it does not break the conversation. ## Endpoint cheat-sheet | Method | Path | Auth | Who | | - | - | - | - | | `POST` | `/api/ecommerce-app` | `x-api-key` | Provider | | `PATCH` | `/api/ecommerce-app/{id}` | `x-api-key` | Provider | | `POST` | `/api/ecommerce-app/{id}/submit` | `x-api-key` | Provider | | `POST` | `/api/ecommerce-app/{id}/rotate-secret` | `x-api-key` | Provider | | `GET` | `/api/ecommerce-app/available` | `x-api-key` | Merchant | | `GET` | `/api/public/apps/oauth/callback` | OAuth state | Provider redirect | | `POST` | `/api/public/apps/{appId}/events/{event}` | HMAC | Provider | # Connect your first channel Source: https://docs.vambe.me/docs/connect-channel Set up WhatsApp, Instagram, Webchat, or Messenger to start receiving customer messages in Vambe. ## 🌐 What you'll build You'll connect at least one communication channel to Vambe so customers can reach you through their preferred platform. > [!TIP] > > Channels are where your customers will interact with your AI assistants and > human agents. You can connect multiple channels to the same pipeline. *** ## Why Connect Channels? Without connected channels, your AI assistants and pipelines can't receive real customer messages. Channels are the entry points where customers start conversations that flow through your sales funnels. ### Supported Channels > [card] WhatsApp > > **Most popular for direct communication** > > * Personal, instant messaging > * High engagement rates > * Support for media, documents > * Business API integration > [card] Instagram > > **Perfect for social media engagement** > > * Comments and direct messages > * Visual content support > * Young demographic reach > * Business profile integration > [card] Webchat > > **Essential for website visitors** > > * Embedded on your website > * Real-time visitor support > * No app installation required > * Professional appearance > [card] Messenger > > **Great for Facebook users** > > * Facebook ecosystem integration > * Automated responses > * Rich media support > * Business page connection *** ## Prerequisites Before connecting channels, ensure you have: * ✅ Completed the [Quickstart guide](/docs/quickstart) * ✅ A Vambe account with **Owner** role * ✅ Business accounts for the platforms you want to connect > [!WARNING] > > **Important:** You'll need business/professional accounts for WhatsApp > Business API and Instagram Business. Personal accounts have limited > functionality. *** ## Channel Setup Guides Choose the channel that best fits your business needs and follow the detailed setup guide: > [accordion] Platform Settings & Account Management > > **Start here** - Learn how to manage your account and basic platform settings before connecting specific channels. > > > [card] [Account Setup Guide](https://www.skool.com/vambe/classroom/c8a9223e?md=4275437de7cd49e695abcb0fa1805e81) > > > > Comprehensive guide for managing your Vambe account, user permissions, and platform configuration. > > **What you'll learn:** > > * Account and user management > * Permission and role configuration > * Basic platform navigation > * Security settings > [accordion] WhatsApp Business API (Dual Numbers) > > **Advanced WhatsApp setup** - Connect multiple WhatsApp numbers to the same Vambe account for larger operations. > > > [card] [Dual WhatsApp API Setup](https://www.skool.com/vambe/classroom/b9d85b56?md=8c0cf6cff5304cc2867752346ad661a6) > > > > Step-by-step guide for connecting two WhatsApp Business numbers to increase capacity and coverage. > > **Best for:** > > * Large businesses with high message volume > * Multiple departments or regions > * Redundancy and load distribution > * A/B testing different approaches > [accordion] WhatsApp Business API (Single Number) > > **Standard WhatsApp setup** - Connect one WhatsApp Business number for most businesses. > > > [card] [Single WhatsApp API Setup](https://www.skool.com/vambe/classroom/b9d85b56?md=78852de8849b4e039fe88411db8a2571) > > > > Complete guide for connecting your WhatsApp Business API to Vambe with full automation features. > > **Best for:** > > * Small to medium businesses > * Single customer service team > * Straightforward messaging needs > * Getting started with WhatsApp automation > [accordion] Instagram Business Integration > > **Social media engagement** - Connect Instagram to capture leads from comments and direct messages. > > > [card] [Instagram Connection Guide](https://www.skool.com/vambe/classroom/b9d85b56?md=2a6c6a138faa4082ba7cbf3d0b7d5266) > > > > Learn how to link your Instagram Business account for automated comment responses and DM management. > > **Features:** > > * Automatic comment responses > * Direct message automation > * Lead capture from social posts > * Integration with your sales pipeline > [accordion] WhatsApp QR Code (Quick Setup) > > **Fastest setup option** - Get started immediately by scanning a QR code with your WhatsApp. > > > [card] [QR Code Setup Guide](https://www.skool.com/vambe/classroom/b9d85b56?md=49ca73a0cb8143a3a681e0dd59f4f8af) > > > > Quick setup method using QR code scanning - perfect for testing and small-scale operations. > > **Best for:** > > * Quick testing and setup > > * Small businesses > > * Personal WhatsApp numbers > > * Temporary or trial setups > > > [!NOTE] > > > > QR code setup has some limitations compared to Business API. For production use, consider the Business API options. *** ## Setup Process Overview Regardless of which channel you choose, the general process follows these steps: **1. Prepare Your Accounts** * Ensure you have business accounts for your chosen platforms * Gather necessary credentials and permissions * Verify account ownership and admin access **2. Access Channel Settings** Navigate to your Vambe dashboard and find the channel configuration section. **3. Follow Platform-Specific Guide** Use the detailed guides above for your chosen channel. Each platform has unique requirements and steps. **4. Test Your Connection** * Send a test message to verify the connection works - Confirm messages appear in your Vambe dashboard - Test basic AI responses if you have a pipeline configured **5. Configure Channel Settings** * Set up welcome messages * Configure business hours * Customize automatic responses * Connect to your pipeline (if created) *** ## Multi-Channel Strategy > [!NOTE] > > **Pro Tip:** You can connect multiple channels to the same pipeline, allowing > customers to reach you through their preferred platform while maintaining > consistent service. ### Channel Selection Guide | Business Type | Recommended Channels | Priority Order | | - | - | - | | **E-commerce** | WhatsApp + Webchat + Instagram | 1. Webchat 2. WhatsApp 3. Instagram | | **B2B Services** | WhatsApp + Webchat | 1. WhatsApp 2. Webchat | | **Local Business** | WhatsApp + Facebook Messenger | 1. WhatsApp 2. Messenger | | **Content Creator** | Instagram + WhatsApp | 1. Instagram 2. WhatsApp | | **SaaS/Tech** | Webchat + WhatsApp | 1. Webchat 2. WhatsApp | ### Best Practices > [card] Consistent Messaging > > * Use the same AI assistant across all channels > * Maintain consistent tone and responses > * Ensure brand voice is uniform > * Train assistants with the same knowledge base > [card] Channel-Specific Optimization > > * Customize welcome messages per channel - Adjust response timing for platform > norms - Use platform-specific features (e.g., Instagram Stories) - Respect > platform communication styles > [card] Performance Monitoring > > * Track engagement rates per channel - Monitor response times and quality - > Analyze conversion rates by source - Optimize based on channel performance > [card] Customer Experience > > * Allow customers to choose their preferred channel > * Provide consistent service quality everywhere > * Maintain conversation history across sessions > * Offer seamless handoffs between channels *** ## Troubleshooting Common Issues > [accordion] Connection Failed > > **If your channel won't connect:** > > * Verify you have admin/owner permissions on the platform account > * Check that business verification is complete (for WhatsApp/Instagram Business) > * Ensure you're using the correct credentials > * Try disconnecting and reconnecting > * Contact support if issues persist > [accordion] Messages Not Appearing > > **If messages aren't showing in Vambe:** > > * Confirm the channel connection is active (green status) > * Check webhook configurations are correct > * Verify message permissions are granted > * Test with a simple text message first > * Review platform API status pages > [accordion] AI Not Responding > > **If your AI assistant isn't replying:** > > * Ensure you have a pipeline configured and connected > * Check that your AI assistant has training data > * Verify API key permissions are sufficient > * Test with simple, clear messages > * Review your pipeline trigger conditions *** ## Get Your Channel IDs Once your channels are connected, you can retrieve their IDs using the Vambe API. This is useful for integrations, webhooks, and analytics tracking. ```bash cURL theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/channels/{channelType} ``` ```javascript JavaScript theme={null} const response = await fetch( 'https://api.vambe.me/api/public/channels/whatsapp', { headers: { 'x-api-key': process.env.VAMBE_API_KEY }, }, ); const channel = await response.json(); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.vambe.me/api/public/channels/whatsapp', headers={'x-api-key': os.environ['VAMBE_API_KEY']} ) channel = response.json() ``` ### Available Channel Types | Channel Type | Description | API Parameter | | - | - | - | | WhatsApp | WhatsApp Business API or QR | `whatsapp` | | Instagram | Instagram Business | `instagram` | | Webchat | Website embedded chat | `web-whatsapp` | | Messenger | Facebook Messenger | `playground` | ### Expected Response ```json theme={null} { "id": "channel_abc123", "type": "whatsapp", "name": "WhatsApp Business", "status": "connected", "created_at": "2025-01-01T12:00:00Z", "settings": { "phone_number": "+1234567890", "business_verified": true } } ``` > [!TIP] > > Save your channel IDs - you'll need them for webhook configurations, analytics > tracking, and API integrations. *** ## Next Steps > [!TIP] > > Congratulations! Your channel is now connected and ready to receive customer > messages. Now you can: > [card] [Create Your First Pipeline](/docs/create-pipeline) > > Build AI-powered sales funnels to automatically handle customer conversations > [card] [Configure AI Assistants](/docs/create-pipeline) > > Train your AI with company knowledge and sales processes > [card] [Set Up Webhooks](/docs/webhooks) > > Get real-time notifications when customers message you > [card] [Monitor Analytics](/docs/analytics) > > Track performance and optimize your customer interactions > [!NOTE] > > **Need help?** Each platform guide includes troubleshooting steps and common > solutions. For additional support, contact our team or check the community > forums. # Connect WhatsApp Business API Source: https://docs.vambe.me/docs/connect-whatsapp-api Set up official Meta WhatsApp Business API integration with Vambe for scalable messaging. ## 🚀 What you'll build You'll connect your WhatsApp Business API account with Vambe to send official WhatsApp messages, templates, and automated responses at scale. > [!TIP] > > WhatsApp Business API is Meta's official solution for businesses to > communicate with customers. It provides higher limits, better reliability, and > advanced features compared to WhatsApp QR. *** ## Prerequisites Before connecting WhatsApp Business API, ensure you have: * ✅ A **Meta Business Account** (formerly Facebook Business Manager) * ✅ **WhatsApp Business API** access approved by Meta * ✅ A verified **phone number** for your business * ✅ Completed [Quickstart guide](/docs/quickstart) with valid API key > [!WARNING] > > **Important:** WhatsApp Business API requires approval from Meta and has > different requirements than regular WhatsApp Business. The verification > process can take several days. *** ## Understanding WhatsApp Business API ### API vs QR Connection > [card] WhatsApp Business API > > **Official Meta integration for businesses** > > * Higher message limits (1000+ per day) > * Template message support > * Webhook integrations > * Business verification required > * Costs per message > * Advanced automation features > [card] WhatsApp QR Setup > > **Quick scan-and-go setup** > > * Limited daily messages (\~250) > * Personal/small business use > * Free to use > * No templates required > * Basic automation > * Easy setup in minutes ### When to Use Business API Choose WhatsApp Business API when you need: * **High volume messaging** (>250 messages/day) * **Template messages** for notifications, confirmments, updates * **Official business presence** with green checkmark verification * **Advanced automation** with webhooks and integrations * **Customer support at scale** with multiple agents * **E-commerce integrations** with order updates and confirmations *** ## Prerequisites Before starting the setup, ensure you have: > [card] Required Items > > * **Phone number** that can receive SMS or calls - **Available number** - > not currently linked to any WhatsApp account - **Active Meta Business > Portfolio** - same account where you manage Facebook ads - **Admin access** > to your Meta Business Manager account > [!WARNING] > > **Important:** The phone number must not be currently associated with any > WhatsApp account (personal or business). You'll need to use a completely new > number. *** ## Step-by-Step Vambe Setup Based on the official Vambe guide from [`Skool - WhatsApp API Setup`](https://www.skool.com/vambe/classroom/b9d85b56?md=78852de8849b4e039fe88411db8a2571), follow these steps: **1. Add WhatsApp API in Vambe** In your Vambe dashboard: * Click **"Platform Settings"** in the upper right corner * Go to **Channels** section * Click **"Add Channel"** button at the bottom * Select **"WhatsApp API"** * Choose **"Register Phone Number"** **2. Meta Business Login** A new tab will open: * **Sign in** with your Facebook Business account * Click **"Continue"** * Click **"Get Started"** > [!NOTE] > > Make sure you're using the same Meta account where you manage your business ads and have admin access. **3. Complete Business Information** Fill out your company details: * **Select** your business commercial portfolio * **Enter** your company name * **Provide** your company website URL * **Select** your country > [!TIP] > > Use the same business information that's verified in your Meta Business Manager to avoid approval delays. **4. Create WhatsApp Business Profile** Set up your WhatsApp Business account: **If you already have a WhatsApp Business account:** * Select your existing account from the dropdown **If you need to create a new profile:** * Choose **"Create new profile"** * Enter **WhatsApp Business account name** * Set **display name** (visible to customers) * Select your **business category** **5. Associate Phone Number** Link your phone number: * **Enter** the phone number you want to link * **Select** option to receive verification code via **SMS** > [!WARNING] > > **CRITICAL:** You'll receive a code in format **XXX XXX**. Save this code - you'll need to enter it **twice** during the process. **6. Verify the Code** Complete the verification: * **Enter** the received verification code * **Review** all information for accuracy * Click **"Continue"** * Click **"Finish"** > [!NOTE] > > The verification code format is XXX XXX (with space). Make sure to enter it exactly as received. **7. Connect with Vambe** Return to Vambe platform: * You'll **automatically return** to Vambe dashboard * **Re-enter** the verification code (format: XXX XXX) * **Select the pipeline** where you want to associate this phone number > [!TIP] > > Success! Your WhatsApp API number is now linked to Vambe and ready to automate conversations. *** ## Verify Your Connection Once setup is complete, test your WhatsApp API connection: ```bash Test via Vambe API theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/channels/whatsapp ``` ```javascript Check Connection Status theme={null} const response = await fetch( 'https://api.vambe.me/api/public/channels/whatsapp', { headers: { 'x-api-key': process.env.VAMBE_API_KEY }, }, ); const channel = await response.json(); console.log('WhatsApp Status:', channel.status); ``` ```python Verify Setup theme={null} import requests response = requests.get( 'https://api.vambe.me/api/public/channels/whatsapp', headers={'x-api-key': os.environ['VAMBE_API_KEY']} ) if response.status_code == 200: channel = response.json() print(f"WhatsApp API connected: {channel['status']}") ``` > [!TIP] > > You can also send a test message from a personal WhatsApp to your business > number to verify that messages appear in your Vambe dashboard. *** ## Troubleshooting Common Issues > [accordion] Phone Number Already in Use > > **If you get an error that the number is already linked:** > > * Ensure the number isn't connected to any other WhatsApp account > * Check if it's linked to personal WhatsApp or WhatsApp Business app > * Try using a completely new, unused phone number > * Contact Meta support if you believe this is an error > [accordion] Verification Code Issues > > **If you don't receive the XXX XXX verification code:** > > * Check your phone can receive SMS messages > * Verify the phone number was entered correctly with country code > * Wait a few minutes and try requesting the code again > * Ensure the number has good cellular coverage > * Try the voice call option if SMS doesn't work > [accordion] Meta Business Account Problems > > **If you can't access Meta Business Manager:** > > * Ensure you have admin permissions on the business account > * Verify your Meta account is not restricted or suspended > * Check that your business is verified in Meta Business Manager > * Make sure you're using the correct Facebook account > * Clear browser cache and cookies, try incognito mode > [accordion] Connection Failed in Vambe > > **If the final Vambe connection doesn't work:** > > * Double-check you entered the verification code correctly (XXX XXX format) > * Ensure you selected the correct pipeline for association > * Try refreshing the Vambe page and re-entering the code > * Contact Vambe support if the issue persists > * Verify your Vambe account has proper permissions *** ## Message Limits & Pricing ### Messaging Tiers WhatsApp Business API uses a tier system that increases with verified phone numbers: | Tier | Messages per 24h | How to Increase | | - | - | - | | **Tier 1** | 1,000 | Start with 10 verified recipients | | **Tier 2** | 10,000 | Message 10 unique users | | **Tier 3** | 100,000 | Message 100 unique users | | **Tier 4** | Unlimited | Message 1,000 unique users | ### Message Categories > [card] Utility Messages > > **Business-critical updates** > > * Order confirmations > * Appointment reminders > * Account alerts > * Payment confirmations > > **Cost: Lower rates** > [card] Authentication > > **Security codes and verification** > > * Login codes > * Password resets > * Account verification > * Two-factor authentication > > **Cost: Lowest rates** > [card] Marketing Messages > > **Promotional content** > > * Product announcements > * Special offers > * Newsletter updates > * Event invitations > > **Cost: Higher rates** > [!NOTE] > > **Pricing varies by country.** Check [Meta's pricing > page](https://developers.facebook.com/docs/whatsapp/pricing) for current rates > in your region. *** ## Next Steps > [!TIP] > > Congratulations! Your WhatsApp Business API is now connected to Vambe. Now you can: > [card] [Create Message Templates](/docs/create-template) > > Design approved templates for notifications and marketing messages > [card] [Send Template Messages](/docs/send-template-message) > > Learn how to send template messages through the API > [card] [Set Up Automated Flows](/docs/create-pipeline) > > Create AI-powered conversations and automated responses > [card] [Monitor Message Analytics](/docs/analytics) > > Track delivery rates, response times, and engagement metrics > [!WARNING] > > **Important:** Always comply with WhatsApp Business Policy. Sending spam or > unsolicited messages can result in account suspension or permanent ban. # Connect WhatsApp QR Source: https://docs.vambe.me/docs/connect-whatsapp-qr Quick setup guide to connect your personal or business WhatsApp using QR code scanning. ## 🚀 What you'll build You'll connect your WhatsApp number to Vambe using QR code scanning - the fastest way to start automating your WhatsApp conversations. > [!TIP] > > WhatsApp QR connection works like WhatsApp Web. It's perfect for personal > numbers, small businesses, or quick testing before setting up Business API. *** ## QR vs Business API > [card] WhatsApp QR (This Guide) > > **Quick scan-and-go setup** > > * ✅ Setup in under 5 minutes > * ✅ Works with personal WhatsApp > * ✅ Free to use > * ✅ No Meta approval needed > * ⚠️ Limited to \~250 messages/day > * ⚠️ Basic automation features > [card] WhatsApp Business API > > **Official Meta integration** > > * ✅ Unlimited messaging (with tiers) > * ✅ Template message support > * ✅ Advanced automation > * ✅ Business verification > * ⚠️ Requires Meta approval > * ⚠️ Setup can take days > [!NOTE] > > **Choose QR if:** You want to test Vambe quickly, have a personal/small business WhatsApp, or need immediate setup. > > **Choose Business API if:** You need high-volume messaging, template messages, or official business presence. *** ## Prerequisites Before connecting WhatsApp QR, ensure you have: * ✅ **WhatsApp installed** on your mobile device * ✅ **Active WhatsApp account** with the number you want to connect * ✅ **Vambe account** with Owner role * ✅ **Pipeline created** (optional, but recommended) > [!WARNING] > > **Important:** The WhatsApp number cannot be simultaneously connected to > WhatsApp Web and Vambe QR. You'll need to disconnect from WhatsApp Web first > if you're using it. *** ## Step-by-Step QR Setup Based on the official Vambe guide from [`Skool - WhatsApp QR Setup`](https://www.skool.com/vambe/classroom/b9d85b56?md=49ca73a0cb8143a3a681e0dd59f4f8af): **1. Access Platform Settings** In your Vambe dashboard: * Click **"Platform Settings"** in the upper right corner * Go to **Channels** section * Click **"Add Channel"** button at the bottom * Select **"WhatsApp"** as the channel type **2. Prepare Your Phone** Get your mobile device ready: * **Open WhatsApp** on your phone * Ensure you have the **same number** you want to connect * Make sure your phone has a **stable internet connection** * **Close WhatsApp Web** if you're using it elsewhere **3. Scan QR Code** Connect using QR scanning: * A **QR code will appear** on your Vambe screen * **Open WhatsApp** on your phone * Tap the **three dots (⋮)** or **Settings** * Select **"Linked Devices"** (Dispositivos vinculados) * Tap **"Link a Device"** (Vincular un dispositivo) * **Point your camera** at the QR code on Vambe * **Wait for confirmation** of successful connection **4. Select Pipeline** Link to your automation: * A **dropdown menu will appear** in Vambe * **Select the specific Pipeline** (Embudo) where you want to link this WhatsApp number * This determines which AI assistant will handle conversations **5. Finish Configuration** Complete the setup: * Click **"Finish"** or **"Finalizar"** to complete configuration * Verify the connection shows as **active** in your channels list * Your WhatsApp QR is now connected to Vambe **6. Link Channel to Pipeline** Ensure messages reach your AI: * **Navigate to your Pipeline** (Embudo) * Click the **green phone icon** in the upper right corner * **Select channels to link** to the pipeline * **Save the configuration** > [!TIP] > > Success! Your pipeline will now automatically receive all messages sent to your WhatsApp number. *** ## Understanding the Connection ### How QR Connection Works > [card] WhatsApp Web Protocol > > **Vambe uses the same technology as WhatsApp Web:** > > * Your phone remains the **primary device** > * Vambe acts as a **linked device** (like WhatsApp Web) > * Messages sync between your phone and Vambe > * Your phone must stay connected to internet > * All WhatsApp features work normally on your phone ### Pipeline Integration Once connected, here's how messages flow: **1. Customer Messages You** * Customer sends WhatsApp message to your number * Message appears on your phone (as normal) * Message also syncs to Vambe platform **2. AI Takes Control** * Vambe AI assistant receives the message - AI analyzes content and customer intent - AI generates appropriate response based on your pipeline configuration **3. Automated Response** * AI sends response through Vambe * Response appears as sent from your WhatsApp number * Customer sees normal WhatsApp conversation * You can see the full conversation in Vambe dashboard > [!NOTE] > > **Phone Dependency:** Your phone must remain connected to internet for the QR > connection to work. If your phone goes offline, the Vambe connection will > pause until your phone reconnects. *** ## Verify Your Connection Test your WhatsApp QR setup: ```bash Check QR Connection theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/channels/web-whatsapp ``` ```javascript Verify Status theme={null} const response = await fetch( 'https://api.vambe.me/api/public/channels/web-whatsapp', { headers: { 'x-api-key': process.env.VAMBE_API_KEY }, }, ); const channel = await response.json(); console.log('WhatsApp QR Status:', channel.status); ``` ```python Check Connection theme={null} import requests response = requests.get( 'https://api.vambe.me/api/public/channels/web-whatsapp', headers={'x-api-key': os.environ['VAMBE_API_KEY']} ) if response.status_code == 200: channel = response.json() print(f"WhatsApp QR connected: {channel['status']}") ``` > [!TIP] > > You can also test by sending a message to your WhatsApp number from another > phone and verifying it appears in your Vambe dashboard. *** ## Troubleshooting > [accordion] QR Code Won't Scan > > **If the QR code scanning fails:** > > * Ensure your phone's **camera has good lighting** > * **Move closer or farther** from the screen > * Try **refreshing the QR code** in Vambe > * Check that **WhatsApp is updated** to the latest version > * Verify you're using the **correct WhatsApp account** > [accordion] Connection Keeps Dropping > > **If the QR connection is unstable:** > > * Ensure your **phone has stable internet** connection > * Check that your phone **doesn't go to sleep** mode > * Verify **WhatsApp background app refresh** is enabled > * Avoid connecting to **multiple devices** simultaneously > * Try **reconnecting** the QR code if issues persist > [accordion] Messages Not Appearing > > **If messages aren't showing in Vambe:** > > * Verify the **channel is linked to your pipeline** > * Check that your **pipeline is active and configured** > * Ensure the **green phone icon** shows linked channels > * Test with a simple message from another phone > * Refresh your Vambe dashboard > [accordion] AI Not Responding > > **If your AI assistant isn't replying:** > > * Ensure your **pipeline has AI stages configured** > * Check that your **AI assistant has training data** > * Verify **pipeline triggers are set up correctly** > * Test with simple, clear messages > * Review your pipeline configuration *** ## QR vs Business API Comparison | Feature | WhatsApp QR | Business API | | - | - | - | | **Setup Time** | 5 minutes | 1-5 days | | **Approval Required** | No | Yes (Meta approval) | | **Message Limits** | \~250/day | 1,000+ (tiered) | | **Template Messages** | No | Yes | | **Phone Dependency** | Yes (phone must be online) | No | | **Cost** | Free | Paid per message | | **Business Verification** | No | Yes (green checkmark) | | **Advanced Features** | Basic | Full automation | > [!NOTE] > > **Migration Path:** You can start with QR for testing and later upgrade to > Business API for production use without losing your pipeline configuration. *** ## Next Steps > [!TIP] > > Congratulations! Your WhatsApp QR is now connected and ready to receive > automated responses. Now you can: > [card] [Send QR Messages](/docs/send-qr-message) > > Learn how to send messages through your QR-connected WhatsApp > [card] [Configure AI Assistant](/docs/create-pipeline) > > Train your AI with company knowledge and conversation flows > [card] [Monitor Conversations](/docs/analytics) > > Track customer interactions and AI performance > [card] [Upgrade to Business API](/docs/connect-whatsapp-api) > > Scale up with official Meta integration for higher limits > [!WARNING] > > **Remember:** Keep your phone connected to internet and avoid logging into > WhatsApp Web on other devices while using Vambe QR connection. # Create your first pipeline Source: https://docs.vambe.me/docs/create-pipeline Learn how to build a sales funnel with AI assistants and human agents using Vambe Mercur. ## 🎯 What you'll build You'll create your first sales pipeline in Vambe Mercur with AI assistants and human agents to automate customer interactions, qualify leads, and drive conversions. > [!TIP] > > Pipelines in Vambe are called "Embudos" (funnels) - structured flows that > guide customers from first contact to conversion. *** ## Understanding Vambe Mercur Vambe Mercur transforms your customer service by automating responses, scheduling appointments, and processing payments while you sleep. Everything starts with your **pipeline (embudo)**. ### What is a Pipeline? A pipeline is a visual representation of your sales process where potential customers move through different stages before converting. Each stage can be handled by: > [card] AI Assistants > > **Blue stages** - Automated virtual assistants powered by AI > > * Answer FAQs about products/services > * Qualify initial prospects > * Schedule appointments > * Collect customer data > * Process standard sales > * Provide 24/7 support > [card] Human Agents > > **Orange stages** - Your team members for complex interactions > > * Handle special negotiations > * Resolve complex cases/complaints > * Close high-value sales > * Provide detailed proposal customization > * Manage exceptions and edge cases > [!NOTE] > > AI assistants learn about your company through configuration "blocks" where > you teach them your sales process, products, and communication style. *** ## How Pipeline Flow Works When a customer starts chatting with your assistant, here's what happens: **1. Contact Card Creation** The system automatically generates a contact card containing all conversation history between the AI and your customer. **2. Intelligent Processing** The AI analyzes each message and generates appropriate responses based on your configuration, deciding whether to: - Continue the conversation - Move to another AI assistant stage - Transfer to a human agent **3. Real-time Monitoring** You can see in real-time where each customer is in your sales process based on their responses. **4. Automatic Stage Progression** When customers show interest, the AI detects keywords or behavior patterns and automatically moves them to the next stage using configured "triggers." ### Multi-Channel Support Connect multiple channels simultaneously while maintaining consistent communication: | Channel | Use Case | Integration | | - | - | - | | **WhatsApp** | Direct, personal communication | Business API | | **Instagram** | Social media lead capture | Comments, DMs | | **Webchat** | Website visitors | Embedded chat widget | | **Messenger** | Facebook users | Business integration | > [!NOTE] > > All channels use the same assistant configuration, ensuring consistent > messaging regardless of where customers contact you. *** ## Pipeline Use Cases > [accordion] Appointment Scheduling > > **Perfect for consultations, demos, or service bookings** > > * AI qualifies the customer and schedules directly in your calendar > * Collects pre-appointment information > * Sends automatic reminders > * Handles rescheduling requests > > **Flow:** Initial contact → Qualification → Calendar integration → Confirmation → Reminders > [accordion] E-commerce Sales > > **Ideal for online stores and product catalogs** > > * Helps customers find products > * Answers product questions > * Processes basic orders > * Handles shipping inquiries > * Escalates complex issues to humans > > **Flow:** Product inquiry → Recommendations → Order processing → Payment → Fulfillment > [accordion] Lead Qualification > > **Great for B2B services and high-ticket items** > > * Identifies qualified leads > * Collects contact information > * Segments customers by needs > * Filters out non-ideal prospects > * Prioritizes high-quality leads > > **Flow:** First contact → Qualification questions → Scoring → Segmentation → Human handoff > [accordion] Customer Support > > **Perfect for handling common inquiries** > > * Resolves frequent questions instantly > * Collects issue details > * Routes complex problems to specialists > * Provides 24/7 basic support > * Escalates urgent matters > > **Flow:** Issue identification → Self-service options → Data collection → Routing → Resolution *** ## Creating Your Pipeline ### Prerequisites Before building your pipeline, ensure you have: * ✅ Completed the [Quickstart guide](/docs/quickstart) * ✅ At least one communication channel connected * ✅ Clear understanding of your sales process * ✅ Defined customer journey stages > [!WARNING] > > **Important:** Review the lead management guides before creating automated systems: > > * [Sales Funnel Management](https://www.skool.com/vambe/classroom/64c0a2ad?md=cfbc84fa2d7e486b80bea5e00cd670ee) > * [Pipeline Flow Understanding](https://www.skool.com/vambe/classroom/64c0a2ad?md=d970ac4e0b7649ebb317e25d256003c9) ### Step-by-Step Creation **1. Access Vambe Mercur** Navigate to your Vambe dashboard and locate the pipeline section. You'll see vertical rectangles (stages) in blue and orange representing your funnel. **2. Design Your Stages** Plan your customer journey: 1. **Entry point** - How customers first contact you 2. **Qualification** - What information you need to collect 3. **Engagement** - How you nurture interest 4. **Conversion** - Your sales or appointment process 5. **Follow-up** - Post-conversion care **3. Configure AI Assistants** For each blue stage, configure your AI assistant: * **Training blocks** - Teach about your company, products, and processes * **Response style** - Define tone and communication approach * **Triggers** - Set conditions for moving to next stage * **Data collection** - Specify what information to gather **4. Set Up Human Handoffs** For orange stages, configure when and how to transfer to your team: * **Handoff triggers** - Define conditions requiring human intervention * **Team assignment** - Route to appropriate specialists * **Context transfer** - Ensure smooth conversation continuity **5. Test and Refine** Before going live: * Test all conversation paths * Verify trigger conditions work correctly * Ensure data collection is complete * Confirm human handoffs function properly *** ## Get Your Pipeline ID Once your pipeline is created, you can retrieve its ID using the Vambe API: ```bash cURL theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/pipeline ``` ```javascript JavaScript theme={null} const response = await fetch('https://api.vambe.me/api/public/pipeline', { headers: { 'x-api-key': process.env.VAMBE_API_KEY }, }); const pipelines = await response.json(); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.vambe.me/api/public/pipeline', headers={'x-api-key': os.environ['VAMBE_API_KEY']} ) pipelines = response.json() ``` ### Expected Response ```json theme={null} { "pipelines": [ { "id": "pipeline_abc123", "name": "Sales Funnel", "stages": [ { "id": "stage_1", "name": "Initial Contact", "type": "ai_assistant" }, { "id": "stage_2", "name": "Qualification", "type": "ai_assistant" }, { "id": "stage_3", "name": "Sales Consultation", "type": "human_agent" } ] } ] } ``` > [!TIP] > > Save your pipeline ID - you'll need it for API integrations, webhooks, and > analytics tracking. *** ## Best Practices > [card] AI Assistant Optimization > > * Keep training blocks focused and specific > * Use clear, conversational language > * Test edge cases and unexpected inputs > * Regularly update knowledge base > * Monitor conversation quality > [card] Human Handoff Strategy > > * Define clear handoff criteria - Provide context to human agents - Set > response time expectations - Train team on AI-generated leads - Maintain > conversation continuity > [card] Pipeline Performance > > * Track conversion rates by stage - Monitor drop-off points - Analyze customer > journey data - A/B test different approaches - Optimize based on results > [card] Customer Experience > > * Ensure natural conversation flow > * Personalize interactions when possible > * Provide clear next steps > * Respect customer preferences > * Offer human option when needed *** ## Next Steps > [!TIP] > > Congratulations! You now understand how to create and manage pipelines in > Vambe Mercur. Ready to build more advanced automations? > [card] [Advanced Pipeline Features](/docs/create-pipeline) > > Learn about complex routing, conditions, and integrations > [card] [Webhook Integration](/docs/webhooks) > > Set up real-time notifications for pipeline events > [card] [Analytics Dashboard](/docs/analytics) > > Monitor performance and optimize your funnels > [card] [Team Management](https://app.vambeai.com/team) > > Configure roles and permissions for your pipeline > [!NOTE] > > Need help setting up your first pipeline? Check out our detailed video guides > or contact support for personalized assistance. # Create your first template Source: https://docs.vambe.me/docs/create-template Design and submit WhatsApp message templates for approval to send notifications, confirmations, and marketing messages. ## 🎯 What you'll build You'll create your first WhatsApp message template, submit it for Meta approval, and learn how to use it for business communications. > [!TIP] > > WhatsApp templates are pre-approved message formats required for sending > messages outside the 24-hour customer service window. They're essential for > notifications, reminders, and marketing. *** ## Understanding WhatsApp Templates ### Why Templates Are Required WhatsApp Business API requires templates for: * **Messages outside 24-hour window** after customer's last message * **Proactive notifications** (order updates, appointment reminders) * **Marketing messages** (promotions, announcements) * **Automated sequences** (welcome series, follow-ups) ### Template Categories > [card] Utility Templates > > **Business-critical updates** > > * Order confirmations > * Shipping notifications > * Appointment reminders > * Payment alerts > > **Approval: Usually fast (24-48h)** > [card] Authentication > > **Security and verification** > > * Login codes > * Password resets > * Account verification > * OTP messages > > **Approval: Fastest (few hours)** > [card] Marketing Templates > > **Promotional content** > > * Product launches > * Special offers > * Event invitations > * Newsletter updates > > **Approval: Slower (2-7 days)** *** ## Template Structure ### Basic Components Every WhatsApp template consists of: **1. Header (Optional)** **Text, Image, Video, or Document** * Maximum 60 characters for text headers * Media headers for rich content * Can include variables `{{1}}`, `{{2}}`, etc. **2. Body (Required)** **Main message content** * Maximum 1,024 characters * Can include variables `{{1}}`, `{{2}}`, etc. * Must provide clear value to recipients **3. Footer (Optional)** **Additional context or branding** * Maximum 60 characters * No variables allowed * Often used for company name or unsubscribe info **4. Buttons (Optional)** **Call-to-action buttons** * Up to 3 buttons * Types: URL, Phone, Quick Reply * Can include variables in URL buttons ### Variable Parameters Templates support dynamic content through variables: * `{{1}}` - First variable (customer name, order number, etc.) * `{{2}}` - Second variable (date, amount, etc.) * `{{3}}` - Third variable (and so on...) > [!NOTE] > > Variables must be used in sequential order (`{{1}}`, then `{{2}}`, then `{{3}}`). You cannot skip numbers. *** ## Creating Your First Template in Vambe Templates are predefined messages you can send to your prospects. In WhatsApp, they allow you to start new conversations or reopen closed ones. From the Templates section, you can view all created templates, their categories, and enabled channels. ### Template Categories > [card] Marketing > > **Promotional content** > > * Product promotions > * Advertising announcements > * Product launches > * Customer base campaigns > > **Use:** Reaching customer base with offers > [card] Utility > > **Internal business purposes** > > * Appointment reminders > * Reactivate inactive conversations > * Order confirmations > * Service notifications > > **Use:** Business operations and customer service > [card] Authentication > > **Verification and security** > > * Verification codes > * Login confirmations > * Security alerts > * Account access > > **Use:** Identity verification processes > [!NOTE] > > Each template type has specific rates charged directly by **Meta**. Check > [Meta's official pricing > page](https://developers.facebook.com/docs/whatsapp/pricing) for current > costs. *** ## Step-by-Step Template Creation **1. Access Templates Section** In your Vambe dashboard: * Navigate to the **Templates** section * Click the blue **"+Crear"** button in the upper right corner > [!NOTE] > > Templates are managed through Platform Settings along with other channel configurations. Reference: [`Skool - Platform Settings Templates`](https://www.skool.com/vambe/classroom/c8a9223e?md=656dc09c2f984a10a0a464114270742f) **2. Select Channels** Choose which channels will use this template: * **WhatsApp API** - For Business API templates * **WhatsApp QR** - For QR-connected numbers * **Other channels** - As available in your account > [!TIP] > > You can select multiple channels if you want the same template available across different communication methods. **3. Configure Basic Information** Set up the template fundamentals: * **Name**: Choose a descriptive, unique identifier * **Category**: Select Marketing, Utility, or Authentication * **Language**: Define the language for the template content > [!WARNING] > > **Template names cannot be changed** after creation. Use clear, descriptive names like `appointment_reminder` or `product_launch`. **4. Customize Content** Design your template structure: **Header (Optional):** * Text header (max 60 characters) * Image, video, or document * Can include variables for personalization **Body (Required):** * Main message content (max 1,024 characters) * Include variables to personalize automatically (e.g., customer name) * Use `{{1}}`, `{{2}}`, `{{3}}` for dynamic content **Footer (Optional):** * Additional message footer * Usually used for company branding or disclaimers **Quick Reply Buttons (Optional):** * Add response options like "¿Quieres comprar este producto? Sí / No" * Up to 3 quick reply buttons * URL or phone number buttons also available **5. Submit for Approval** Complete the template creation: * Review all content for accuracy * Click **Create** or **Submit** * Template is automatically sent to Meta for approval * Approval process typically completes almost immediately * Only approved templates can be used in conversations > [!TIP] > > Once approved, your template will be available for use in your Vambe campaigns and automated flows. *** ## Template Design Example Let's create an order confirmation template: ```text Header theme={null} Order Confirmed! 📦 ``` ```text Body theme={null} Hi `{{1}}`, Great news! Your order #`{{2}}` has been confirmed and is being prepared. Order Details: • Total: $`{{3}}` • Estimated delivery: `{{4}}` We'll send you tracking information once your order ships. Thank you for shopping with us! ``` ```text Footer theme={null} MyStore - Your trusted partner ``` ### Step 4: Add Interactive Buttons (Optional) > [accordion] URL Button > > **Track Order Button** > > * Button Text: "Track Order" > * URL: `https://mystore.com/track/{{2}}` > * Uses variable `{{2}}` for order number > [accordion] Phone Button > > **Call Support Button** > > * Button Text: "Call Support" > * Phone Number: "+1234567890" > * No variables allowed in phone buttons > [accordion] Quick Reply > > **Quick Response Options** > > * "Need Help?" > * "Change Address" > * "Cancel Order" > > These appear as clickable options for customers *** ## Template Examples by Use Case ### 1. Appointment Reminder > [card] Healthcare Appointment Reminder > > **Category:** UTILITY > > **Body:** > > ``` > Hi `{{1}}`, > > This is a reminder that you have an appointment with Dr. `{{2}}` tomorrow at `{{3}}`. > > Location: `{{4}}` > > Please arrive 15 minutes early. If you need to reschedule, please call us at least 24 hours in advance. > ``` > > **Buttons:** > > * URL: "Get Directions" → `https://maps.google.com/?q={{4}}` > * Phone: "Call to Reschedule" → `+1234567890` ### 2. Welcome Message > [card] New Customer Welcome > > **Category:** UTILITY > > **Header:** Welcome to `{{1}}`! 🎉 > > **Body:** > > ``` > Hi `{{2}}`, > > Welcome to our community! We're excited to have you on board. > > Here's what you can expect: > • Exclusive offers and updates > • 24/7 customer support > • Easy returns and exchanges > > Your customer ID is: `{{3}}` > ``` > > **Buttons:** > > * URL: "Explore Products" → `https://mystore.com/products` > * Quick Reply: "Contact Support" ### 3. Payment Confirmation > [card] Payment Received > > **Category:** UTILITY > > **Body:** > > ``` > Hi `{{1}}`, > > We've successfully received your payment of $`{{2}}` for invoice #`{{3}}`. > > Payment Details: > • Method: `{{4}}` > • Date: `{{5}}` > • Transaction ID: `{{6}}` > > Thank you for your business! > ``` > > **Footer:** Questions? Reply to this message *** ## Template Approval Process ### Submission Guidelines **1. Review Template Content** * Ensure clear business value * Use proper grammar and spelling * Include relevant variables * Follow WhatsApp Commerce Policy **2. Submit for Review** * Click **Submit** in Template Manager - Templates enter Meta's review queue - Initial status shows as "PENDING" **3. Approval Timeline** * **Authentication:** Few hours - **Utility:** 24-48 hours - **Marketing:** 2-7 days - Complex templates may take longer **4. Handle Results** * **Approved:** Status changes to "APPROVED" * **Rejected:** Review feedback and resubmit * **Pending:** Wait or contact Meta support ### Common Rejection Reasons > [accordion] Content Issues > > **Common problems:** > > * Vague or unclear messaging > * Missing context for variables > * Grammatical errors or typos > * Non-business related content > * Misleading information > [accordion] Policy Violations > > **WhatsApp policy violations:** > > * Requesting personal information unnecessarily > * Threatening or aggressive language > * Adult content or illegal activities > * Spam-like characteristics > * Misleading offers or claims > [accordion] Technical Problems > > **Format and structure issues:** > > * Invalid variable usage > * Broken or suspicious URLs > * Incorrect button configurations > * Character limit exceeded > * Missing required components *** ## Best Practices > [card] Content Quality > > * **Be clear and concise** - Get to the point quickly > * **Provide value** - Every message should benefit the customer > * **Use friendly tone** - Professional but approachable > * **Include context** - Explain why you're messaging them > * **Add clear CTAs** - Make next steps obvious > [card] Technical Optimization > > * **Test variables** - Ensure all scenarios work - **Optimize length** - > Shorter templates perform better - **Use buttons wisely** - Don't overwhelm > with options - **Plan for localization** - Consider multiple languages - > **Monitor performance** - Track open and click rates > [card] Compliance > > * **Follow WhatsApp policies** - Read and understand guidelines - **Respect > opt-outs** - Honor unsubscribe requests - **Be transparent** - Identify your > business clearly - **Avoid spam tactics** - Focus on genuine value - **Keep > records** - Document approval processes > [card] User Experience > > * **Personalize content** - Use customer names and data > * **Time messages well** - Consider customer time zones > * **Provide support** - Make it easy to get help > * **Test thoroughly** - Verify all links and variables > * **Gather feedback** - Learn from customer responses *** ## Managing Templates ### Template Status Monitoring Check template status regularly: ```bash Check Templates via API theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/templates ``` ```javascript Get Templates via Vambe API theme={null} const response = await fetch('https://api.vambe.me/api/public/templates', { headers: { 'x-api-key': process.env.VAMBE_API_KEY }, }); const templates = await response.json(); ``` ```python List Approved Templates theme={null} import requests response = requests.get( 'https://api.vambe.me/api/public/templates', headers={'x-api-key': os.environ['VAMBE_API_KEY']} ) templates = response.json() ``` ### Template Maintenance * **Regular audits** - Review template performance monthly * **Update content** - Refresh outdated information * **Archive unused** - Remove templates you no longer need * **Version control** - Keep track of template changes * **Performance tracking** - Monitor delivery and engagement rates *** ## Next Steps > [!TIP] > > Congratulations! You've created your first WhatsApp message template. Once your template is approved, you can: > [card] [Send Template Messages](/docs/send-template-message) > > Learn how to send your approved templates via API > [card] [Automate with Pipelines](/docs/create-pipeline) > > Integrate templates into your automated conversation flows > [card] [Track Performance](/docs/analytics) > > Monitor template delivery rates and customer engagement > [card] [Advanced Templates](/docs/create-template) > > Learn about media templates, carousels, and interactive elements > [!NOTE] > > **Pro Tip:** Start with simple utility templates to get familiar with the > approval process before creating complex marketing templates. # E-commerce Integration Guide Source: https://docs.vambe.me/docs/ecommerce-guide Learn how to integrate your product catalog with Vambe AI assistants. Manage products, sync inventory, and enable AI-powered product recommendations. ## Overview Vambe's e-commerce integration allows your AI assistants to recommend and discuss products with customers. Products are organized in **Product Blocks** (also called Prompt Blocks), which are containers that hold related products. ## Key Concepts ### Product Blocks * **Container**: A product block is a container that holds related products * **AI Context**: AI assistants use product blocks to understand available products * **Organization**: Organize products by category, brand, or use case * **Multiple Blocks**: You can have multiple product blocks for different purposes ### Product Structure Each product has: * **Basic Info**: Name, description, price, currency * **Type**: PRODUCT (physical/digital) or SERVICE * **External ID**: Your unique identifier for tracking * **Metadata**: Custom key-value pairs for additional data * **AI Description**: Natural language description for AI understanding ## Getting Started ### Step 1: Get Your Product Block IDs Before managing products, you need to know which product blocks are available: ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/product/product-blocks' \ --header 'x-api-key: your_api_key_here' ``` **Response**: ```json theme={null} [ { "id": "block-abc123", "name": "Main Product Catalog", "count": 150 }, { "id": "block-def456", "name": "Seasonal Products", "count": 25 } ] ``` Save these IDs - you'll need them for all product operations! ### Step 2: Choose Your Product Management Strategy Depending on your needs, choose the right endpoint: | Endpoint | Use When | Behavior | | - | - | - | | **Create** | Adding new products or updating specific ones | Keeps existing products | | **Upsert** | Full catalog synchronization | Deletes products not in request | | **Delete** | Removing specific products | Deletes only specified products | ## Complete Workflows ### Workflow 1: Initial Product Catalog Setup ```javascript theme={null} // 1. Get product block ID const blocksResponse = await fetch( 'https://api.vambe.me/api/public/product/product-blocks', { headers: { 'x-api-key': 'your_api_key_here' }, }, ); const blocks = await blocksResponse.json(); const mainBlockId = blocks.find((b) => b.name === 'Main Product Catalog')?.id; // 2. Create initial products const createResponse = await fetch( `https://api.vambe.me/api/public/product/create/${mainBlockId}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify([ { name: 'Premium Coffee Beans', description: 'High-quality arabica coffee from Colombia. Rich flavor with chocolate notes. Perfect for espresso.', price: 24.99, currency: 'USD', type: 'PRODUCT', external_id: 'coffee-001', file_url: 'https://shop.com/coffee.jpg', metadata: [ { key: 'origin', value: 'Colombia' }, { key: 'roast', value: 'Medium' }, { key: 'weight', value: '500g' }, ], }, { name: 'Express Delivery', description: 'Fast delivery service. Next-day delivery for orders placed before 2 PM. Available nationwide.', price: 5.0, currency: 'USD', type: 'SERVICE', external_id: 'delivery-express', metadata: [ { key: 'delivery_time', value: '1 day' }, { key: 'coverage', value: 'Nationwide' }, ], }, ]), }, ); console.log('Products created successfully!'); ``` ### Workflow 2: Nightly Catalog Sync ```javascript theme={null} // Complete catalog sync from your e-commerce platform const syncCatalog = async (productBlockId) => { // 1. Get products from your e-commerce platform const shopProducts = await yourEcommercePlatform.getAllProducts(); // 2. Transform to Vambe format const vambeProducts = shopProducts.map((product) => ({ name: product.title, description: `${product.description}. ${product.features.join('. ')}`, price: parseFloat(product.price), currency: 'USD', type: 'PRODUCT', external_id: `shop-${product.id}`, file_url: product.image_url, metadata: [ { key: 'sku', value: product.sku }, { key: 'category', value: product.category }, { key: 'brand', value: product.brand }, { key: 'in_stock', value: product.in_stock.toString() }, ], })); // 3. Upsert to Vambe (full sync - removes discontinued products) const response = await fetch( `https://api.vambe.me/api/public/product/upsert/${productBlockId}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify(vambeProducts), }, ); const result = await response.json(); console.log(`Synced ${vambeProducts.length} products`); console.log(`Created: ${result.created}, Updated: ${result.updated}`); return result; }; // Run nightly // cron.schedule('0 2 * * *', () => syncCatalog('block-abc123')); ``` ### Workflow 3: Add New Product ```javascript theme={null} // Add a single new product without affecting others const addNewProduct = async (productBlockId, newProduct) => { const response = await fetch( `https://api.vambe.me/api/public/product/create/${productBlockId}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify([ { name: newProduct.name, description: newProduct.description, price: newProduct.price, currency: 'USD', type: 'PRODUCT', external_id: `new-${Date.now()}`, file_url: newProduct.imageUrl, metadata: [ { key: 'category', value: newProduct.category }, { key: 'new_arrival', value: 'true' }, ], }, ]), }, ); console.log('New product added!'); return await response.json(); }; ``` ### Workflow 4: Remove Discontinued Products ```javascript theme={null} // Remove products that are no longer available const removeDiscontinued = async (productBlockId, externalIds) => { const response = await fetch( `https://api.vambe.me/api/public/product/delete/${productBlockId}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify(externalIds.map((id) => ({ external_id: id }))), }, ); const result = await response.json(); console.log(`Deleted ${result.deleted} products`); return result; }; // Usage removeDiscontinued('block-abc123', ['old-product-001', 'discontinued-002']); ``` ## Best Practices ### 1. Writing Good Product Descriptions The description field is crucial for AI understanding. Follow these guidelines: **✅ Good Description**: ``` "Premium wireless headphones with active noise cancellation. Over-ear design provides comfort for long listening sessions. 30-hour battery life. Perfect for travel, work, and music lovers who demand high-quality audio." ``` **❌ Poor Description**: ``` "Model: WH-1000XM4. Price: $349.99. Buy now at https://shop.com. SKU: WH1000XM4." ``` **Tips**: * Use natural language that describes features and benefits * Avoid URLs, prices (already in price field), or SKU codes * Focus on what makes the product unique * Include use cases and who it's for * Mention key features in conversational language ### 2. Use Meaningful External IDs ```javascript theme={null} // Good: Trackable, meaningful IDs external_id: 'sku-WH1000XM4'; external_id: 'shopify-6789012345'; external_id: 'coffee-premium-colombia-500g'; // Avoid: Hard to track external_id: '1'; external_id: 'product'; ``` ### 3. Organize with Metadata ```javascript theme={null} metadata: [ { key: 'category', value: 'Electronics' }, { key: 'subcategory', value: 'Audio' }, { key: 'brand', value: 'Sony' }, { key: 'in_stock', value: 'true' }, { key: 'warehouse_location', value: 'A-12' }, { key: 'seasonal', value: 'false' }, ]; ``` ### 4. Handle Large Catalogs For catalogs with 1000+ products: ```javascript theme={null} // Batch products into chunks for reliability const BATCH_SIZE = 500; const uploadInBatches = async (products, blockId) => { for (let i = 0; i < products.length; i += BATCH_SIZE) { const batch = products.slice(i, i + BATCH_SIZE); await fetch(`https://api.vambe.me/api/public/product/create/${blockId}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify(batch), }); console.log(`Uploaded batch ${Math.floor(i / BATCH_SIZE) + 1}`); // Small delay between batches await new Promise((resolve) => setTimeout(resolve, 1000)); } }; ``` ## Product Types ### PRODUCT Physical or digital items that customers purchase: * Physical products (clothes, electronics, etc.) * Digital products (ebooks, software, etc.) * Consumables (food, drinks, etc.) ### SERVICE Services or subscriptions: * Delivery services * Consulting services * Subscriptions * Warranties * Installation services ## Currency Codes Supported currencies include: * **USD**: US Dollar * **EUR**: Euro * **GBP**: British Pound * **CLP**: Chilean Peso * **MXN**: Mexican Peso * **COP**: Colombian Peso * **ARS**: Argentine Peso * **PEN**: Peruvian Sol * **BRL**: Brazilian Real And many more! ## API Endpoints Reference ### Product Management 1. **[GET /api/public/product/product-blocks](/reference/product/get-product-blocks)** - List available product blocks 2. **[POST /api/public/product/create/](/reference/product/create-products)** - Add/update products (keeps others) 3. **[POST /api/public/product/upsert/](/reference/product/upsert-products)** - Full sync (deletes unlisted) 4. **[POST /api/public/product/delete/](/reference/product/delete-products)** - Delete specific products ### Order Information 5. **[GET /api/public/order//product](/reference/product/get-order-products)** - Get products in an order ## Common Scenarios ### Scenario 1: E-commerce Platform Integration ```javascript theme={null} // Daily sync from Shopify/WooCommerce/etc const dailySync = async () => { // 1. Get block ID const blocks = await getProductBlocks(); const blockId = blocks[0].id; // 2. Get products from your platform const products = await shopifyAPI.getProducts(); // 3. Transform and sync const vambeProducts = products.map(transformToVambeFormat); // 4. Upsert (removes products no longer in your catalog) await upsertProducts(blockId, vambeProducts); console.log('Daily sync complete!'); }; ``` ### Scenario 2: Real-time Updates ```javascript theme={null} // When a product is added/updated in your system const onProductChange = async (product) => { const blockId = 'block-abc123'; // Use create (doesn't affect other products) await createProducts(blockId, [transformProduct(product)]); console.log('Product updated in AI knowledge'); }; // When a product is discontinued const onProductDiscontinued = async (productId) => { const blockId = 'block-abc123'; await deleteProducts(blockId, [{ external_id: productId }]); console.log('Product removed from AI knowledge'); }; ``` ### Scenario 3: Multi-category Management ```javascript theme={null} // Different product blocks for different categories const setupCategories = async () => { const blocks = await getProductBlocks(); const electronicsBlock = blocks.find((b) => b.name === 'Electronics'); const clothingBlock = blocks.find((b) => b.name === 'Clothing'); // Sync electronics await upsertProducts(electronicsBlock.id, electronicsProducts); // Sync clothing await upsertProducts(clothingBlock.id, clothingProducts); console.log('All categories synced!'); }; ``` ## Troubleshooting ### Product Not Showing in AI Responses 1. **Check Description**: Ensure description uses natural language 2. **Verify Block**: Confirm product is in the correct block 3. **Check AI Configuration**: Ensure assistant has access to product block 4. **Wait for Processing**: Allow a few minutes for AI indexing ### Products Being Deleted Unexpectedly * **Using Upsert?**: Remember upsert deletes products not in request * **Solution**: Use `create` endpoint for partial updates * **Or**: Include all products in upsert request ### Metadata Not Appearing * **Check Format**: Metadata must be array of `{key, value}` objects * **Verify Keys**: Keys should be simple strings * **Check Response**: Verify metadata was saved ## Related Resources * [Product Endpoints](/reference/product/get-product-blocks) - Full API reference * [Create Pipeline](/docs/create-pipeline) - Set up AI assistant to use products * [Analytics](/docs/analytics) - Track product recommendation performance ## Next Steps 1. **Get Your Block IDs**: Call GET /product-blocks 2. **Upload Products**: Use create or upsert endpoint 3. **Configure AI Assistant**: Link product block to your assistant 4. **Test**: Chat with your AI and ask about products 5. **Monitor**: Track which products are being recommended # Quickstart Source: https://docs.vambe.me/docs/quickstart Get started with Vambe: account setup, channels, API keys, and your first request. ## 🚀 What you'll build You'll set up your Vambe account and channel, create an API key, and make your first API request. > [!TIP] > > This guide takes about 10 minutes to complete. By the end, you'll have made > your first successful API call to Vambe. *** ## 1) Prerequisites Before you start, you'll need: * A Vambe account with the role **Owner** > [!NOTE] > > Don't have an account yet? Create one at > [`app.vambeai.com/login`](https://app.vambeai.com/login) > [!NOTE] > > **Want to connect channels?** Check out our [Connect your first > channel](/docs/connect-channel) guide to set up WhatsApp, Instagram, Webchat, > or Messenger for receiving customer messages. *** ## 2) Create your API key **1. Navigate to Developers** Go to [`app.vambeai.com/developers`](https://app.vambeai.com/developers) and open the **API Keys** section. **2. Create New Key** Click the **New API Key** button to open the creation dialog. **3. Configure Key Details** * **Name**: Give it a descriptive name (e.g., "Server", "Zapier", "Development") - **Role**: Choose the appropriate permission level **4. Select Role** Choose the appropriate role for your use case: | Role | Description | Use Case | | - | - | - | | `OWNER` | Full organization control | Initial testing, admin tasks | | `ADMIN` | Administrative access | Team management | | `SUPER_ADMIN` | Extended system access | Advanced operations | | `AGENT` | Standard operations | Daily tasks, integrations | **5. Create and Store** Click **Create**, then reveal and copy your API key. Store it securely in your environment variables or secret manager. > [!WARNING] > > **Security Best Practices:** - Treat API keys like passwords—never commit them > to git - Use environment variables: `VAMBE_API_KEY=your_key_here` - Rotate or > delete unused keys from the Developers page - Prefer least-privilege roles for > production keys *** ## 3) Your first API call Vambe authenticates server-side requests via the `x-api-key` header. Replace `YOUR_API_KEY` with your newly created key. ```bash cURL theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/health/ping ``` ```javascript JavaScript (fetch) theme={null} await fetch('https://api.vambe.me/health/ping', { headers: { 'x-api-key': process.env.VAMBE_API_KEY }, }); ``` ```python Python (requests) theme={null} import os, requests resp = requests.get( 'https://api.vambe.me/health/ping', headers={'x-api-key': os.environ['VAMBE_API_KEY']} ) ``` ### Expected Response ```json theme={null} { "status": "ok", "message": "pong", "date": "2025-01-01T12:00:00.000Z" } ``` > [accordion] Testing Tips > > * **Latency simulation**: Add `?sleep=500` to test response times: > `.../health/ping?sleep=500` - **Database health check**: Use `GET /health` for > a full system check including database connectivity - **Postman setup**: Add a > header `x-api-key: YOUR_API_KEY` to your request *** ## 4) Next steps > [!TIP] > > Congratulations! You've successfully made your first API call to Vambe. Here's what to explore next: > [card] [API Reference](/reference) > > Explore all available endpoints for channels, contacts, and webhooks > [card] [Integration Guide](/docs/integration-to-the-api) > > Learn how to integrate Vambe into your existing workflows > [card] [Team Management](https://app.vambeai.com/team) > > Invite teammates and configure role-based access > [card] [Webhooks](/docs/webhooks) > > Set up real-time notifications for events > [!NOTE] > > Need help? Contact our support team or check the **API Reference** section for > detailed endpoint documentation. # Send verification codes (OTP) Source: https://docs.vambe.me/docs/send-otp-message Send one-time passwords over WhatsApp with authentication templates through the Vambe API. ## 🔐 What you'll build You'll send a one-time verification code (OTP) to a customer over WhatsApp, using an **authentication template** and the Vambe API, and follow its delivery. > [!TIP] > > Authentication templates are the WhatsApp format for login codes, account > verification and password resets. WhatsApp renders the copy, adds a **Copy > code** button and, for one-tap and zero-tap templates, can autofill the code > in your Android app. *** ## Prerequisites * ✅ [Connected WhatsApp Business API](/docs/connect-whatsapp-api) * ✅ An **approved authentication template** on the number you send from * ✅ Valid Vambe API key from the [developers page](https://app.vambeai.com/developers) ### Getting an authentication template You can create it in either place: * **In Vambe:** Templates → create a template with the **Authentication** category. Choose whether to add the security recommendation ("For your security, do not share this code.") and how many minutes the code is valid. * **In WhatsApp Manager (Meta):** create it there and sync your templates in Vambe. Vambe imports it with its security recommendation, expiration and button type, ready to send. Then copy its ID from `GET /api/public/templates`. > [!WARNING] > > An authentication template only carries the code. WhatsApp writes the rest of > the copy, so you can't add your own text, links or media to it. *** ## Choose an endpoint | Endpoint | Use it when | | - | - | | `POST /api/public/whatsapp/message/send/{phone}/template/{templateId}` | You send one code and want the structured format: the phone in the path and the code as the first variable. | | `POST /api/public/whatsapp/message/send/template/{templateId}` | You already call the smart endpoint for your other templates and want the same flow. | | `POST /api/public/whatsapp/message/send/template/{templateId}/many` | You send codes to several recipients in one request. | The code is never rewritten or extracted by AI. The structured endpoint sends `variables[0]` as is; the smart endpoints only trim spaces around it (`" 482913 "` is sent as `482913`), so store the trimmed value if you compare it later. *** ## Send a code > [tab] Structured > > The phone goes in the path (country code, digits only) and the code is the only variable: > > ```bash theme={null} > curl -X POST \ > -H "x-api-key: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ "variables": ["482913"] }' \ > https://api.vambe.me/api/public/whatsapp/message/send/56912345678/template/{templateId} > ``` > > **Response (201):** > > ```json theme={null} > { > "messageId": "f1e2d3c4-b5a6-4978-8899-aabbccddeeff", > "aiContactId": "b7c9a9e2-4a4b-4f4e-9d2a-1c2d3e4f5a6b", > "ticketId": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d", > "contactPhoneNumber": "56912345678", > "channelPhoneNumber": "56211111111", > "variables": [ ... ] > } > ``` > [tab] Smart > > Put the recipient and the code in the body: > > ```bash theme={null} > curl -X POST \ > -H "Content-Type: application/json" \ > -d '{ "phone": "+56 9 1234 5678", "code": "482913" }' \ > "https://api.vambe.me/api/public/whatsapp/message/send/template/{templateId}?x-api-key=YOUR_API_KEY" > ``` > > The body keys can be named in any of these ways: > > | Value | Accepted keys | > | - | - | > | Recipient phone | `phone`, `phone_number`, `phoneNumber`, `to` | > | Code | `code`, `otp`, `otp_code`, `otpCode` | > > Spaces, `+`, parentheses and dashes in the phone are removed. The code can be a string or a number. > > **Response (201):** > > ```json theme={null} > { > "contactId": "b7c9a9e2-4a4b-4f4e-9d2a-1c2d3e4f5a6b", > "messageId": "f1e2d3c4-b5a6-4978-8899-aabbccddeeff", > "contactPhoneNumber": "56912345678", > "channelPhoneNumber": "56211111111" > } > ``` > [tab] Bulk > > Send an array; each item needs its own phone and code: > > ```bash theme={null} > curl -X POST \ > -H "x-api-key: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '[ > { "phone": "56912345678", "code": "482913" }, > { "phone": "56987654321", "code": "190274" } > ]' \ > https://api.vambe.me/api/public/whatsapp/message/send/template/{templateId}/many > ``` > > Before anything is queued, every item is checked for a usable phone and code. If any item fails that check, the whole request is rejected with the position of each failing item and **nothing is queued**: > > ```json theme={null} > { > "message": "Authentication templates need the recipient and the code in the body, e.g. {\"phone\": \"56912345678\", \"code\": \"123456\"}", > "errors": [ > { "index": 1, "error": "Missing the OTP code. Authentication templates need the recipient and the code in the body, e.g. {\"phone\": \"56912345678\", \"code\": \"123456\"}" } > ] > } > ``` > > When every item passes, the response is `{ "success": true }` and each code is sent in the background, **independently**. A problem with one recipient found while sending (for example, a blocked contact or a number WhatsApp rejects) only affects that item, and the others may already have been sent. The response carries no message IDs. ### Optional parameters * `from-phone-number` (query): the number to send from, when you have more than one, written exactly as it is registered in Vambe (digits with country code, e.g. `56211111111`). * **Structured endpoint:** if the number isn't one the template is approved on, the request fails with `Template cant be sent from this phone number`. * **Smart endpoints:** if it doesn't match any WhatsApp number of your account (mistyped, or formatted differently), the request fails with `from-phone-number … is not a WhatsApp number of this account`. If it's one of your numbers but the template isn't approved on it, it fails with `Template is not valid for this channel`. Either way nothing is sent from another number. * `stage` (query, smart endpoints) or `stageId` (body, structured endpoint): the pipeline stage to put the contact in. *** ## Track delivery For single sends (structured and smart), use the `messageId` from the response with [GET /api/public/whatsapp/message/status/](/reference/whatsapp-message/get-the-delivery-status-of-a-sent-message). It starts as `accepted` and moves through `sent`, `delivered` and `read`, or ends in `failed` with WhatsApp's reason. A `404` right after sending means the message is still being registered: retry after a few seconds. Bulk sends don't return message IDs. If you need to follow each code, send them one by one. *** ## Rules to keep in mind > [accordion] Codes are up to 15 characters > > That is WhatsApp's limit for authentication templates. Longer codes are rejected with `OTP code must be 15 characters or less`. > [accordion] Repeating a request does not resend the code > > The smart endpoints are idempotent: a request identical to a previous one within **10 minutes** counts as one send and returns the original response. "Identical" means the same template, the **whole body**, `stage` and `from-phone-number`: > > * Retrying the exact same request sends nothing new, so to resend a code to the same phone inside that window, generate a new code. > * Any other difference, such as a timestamp or request ID in the body, a different `stage` or another `from-phone-number`, makes it a new request and **sends the code again**. If you rely on this protection against duplicate sends, retry with exactly the same body. > > The structured endpoint is not idempotent: every call sends a message. > [accordion] The recipient needs a phone number > > WhatsApp only delivers authentication templates to phone numbers. A contact Vambe knows only by its WhatsApp username (BSUID), without a phone, can't receive one. > [accordion] Treat the code as a secret > > Generate a new random code for every attempt, keep its expiration short (it should match the minutes set on the template) and never log it in plain text on your side. *** ## Error reference | Status | Message | What to do | | - | - | - | | 400 | `OTP code is required for authentication templates` | Structured endpoint: send the code as the first variable, `{"variables": ["482913"]}`. | | 400 | `Missing the OTP code. …` | Smart endpoints: add the code to the body (`code`, `otp`, `otp_code` or `otpCode`). | | 400 | `Missing the recipient phone. …` | Smart endpoints: add the phone to the body (`phone`, `phone_number`, `phoneNumber` or `to`). | | 400 | `Invalid recipient phone "…"` | Send digits with country code; spaces, `+`, parentheses and dashes are fine. | | 400 | `OTP code must be 15 characters or less` | Shorten the code. | | 400 | `Template cant be sent from this phone number` | Structured endpoint: use a `from-phone-number` the template is approved on, or omit it. | | 400 | `from-phone-number … is not a WhatsApp number of this account` | Smart endpoints: write the number exactly as registered in Vambe (digits with country code), or omit it. | | 400 | `Template is not valid for this channel` | Smart endpoints: use a `from-phone-number` the template is approved on, or omit it. | | 400 | `Authentication templates cannot be sent to BSUID-only contacts. A phone number is required.` | Send to the customer's phone number. | | 401 | `Unauthorized` | Check the API key. | | 429 | `An identical send is already being processed. …` | An identical request is still in flight; retry shortly to get its result. | *** ## Next steps > [card] [Send template messages](/docs/send-template-message) > > Send your other templates with variables. > [card] [Create templates](/docs/create-template) > > Design and submit templates for approval. # Send QR message Source: https://docs.vambe.me/docs/send-qr-message Learn how to send WhatsApp messages through your QR-connected number using Vambe API. ## 🚀 What you'll build You'll send messages through your QR-connected WhatsApp number using the Vambe API. Choose between AI-generated messages or manual control. > [!TIP] > > QR messaging works like WhatsApp Web but with AI automation. Perfect for > personal numbers and quick setup. *** ## Prerequisites * ✅ [Connected WhatsApp QR](/docs/connect-whatsapp-qr) to your Vambe account * ✅ **Phone connected to internet** and WhatsApp QR active * ✅ Valid Vambe API key from [developers page](https://app.vambeai.com/developers) *** ## Two Ways to Send Messages ### Option 1: AI-Generated Messages (Recommended) Let Vambe AI create intelligent messages for you: **1. Get QR Channel ID** ```bash theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/channels/web-whatsapp ``` Save the `id` field as your phoneId for the ticket endpoint. **2. Get Pipeline Stage ID** ```bash theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/pipeline ``` Save the stage ID where you want to start the conversation. **3. Create AI-Generated Message** ```bash theme={null} curl -X POST \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "to_phone_number": "+1234567890", "contact_name": "John Doe", "stage_id": "stage_initial_001", "contact_metadata": { "source": "api", "priority": "normal" }, "ticket_metadata": { "topic": "product_inquiry" } }' \ https://api.vambe.me/api/public/ticket/open/web-whatsapp/{phoneId} ``` > [!TIP] > > AI automatically creates appropriate message content and initiates the conversation based on your pipeline configuration. ### Option 2: Manual Message Control For when you want full control over message content: **1. Get QR Channel ID** ```bash theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/channels/web-whatsapp ``` Save the `id` field as your phoneId. **2. Get Pipeline Stage ID** ```bash theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/pipeline ``` Save the stage ID where you want to send the message. **3. Send Your Custom Message** ```bash theme={null} curl -X POST \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Hello! This is a custom message from Vambe.", "stage": "stage_initial_001", "toPhoneNumber": "+1234567890", "contactName": "John Doe", "metaData": {} }' \ https://api.vambe.me/api/public/web-whatsapp-message/send/1001/message ``` *** ## What Happens Behind the Scenes When you send a message through QR API, Vambe automatically: > [card] AI Processing > > * **Extracts contact data** using GPT > * **Creates or updates** contact records > * **Generates intelligent content** (ticket mode) > * **Validates data format** automatically > [card] Conversation Management > > * **Links contact to pipeline** stage > * **Preserves conversation** history > * **Tracks customer journey** progression > * **Enables AI responses** for incoming messages *** ## API Comparison | Feature | AI-Generated (Ticket) | Manual Message | | - | - | - | | **Setup** | 3 steps | 3 steps | | **Message Creation** | AI creates content | You write content | | **Required Fields** | Minimal | All manual | | **Best For** | Automation | Full control | *** ## Error Handling > [accordion] Phone Offline (503) > > **If your phone is disconnected:** > > * Check phone internet connection > * Ensure WhatsApp is running > * Reconnect QR in Vambe dashboard > [accordion] Invalid Stage (400) > > **If stage ID doesn't exist:** > > * Get stage ID from pipeline API > * Verify pipeline is active > * Check stage belongs to your account > [accordion] Rate Limit (429) > > **If too many messages:** > > * QR limit: \~250 messages/day > * Add delays between messages > * Consider Business API for higher volume *** ## Next Steps > [!TIP] > > You're now ready to send messages through your WhatsApp QR connection. > [card] [Configure AI Assistant](/docs/create-pipeline) > > Train your AI to handle customer responses automatically > [card] [Monitor Analytics](/docs/analytics) > > Track message performance and customer engagement > [card] [Create Pipelines](/docs/create-pipeline) > > Build conversation flows for automated customer journeys > [card] [Upgrade to Business API](/docs/connect-whatsapp-api) > > Scale to higher limits with official Meta integration > [!NOTE] > > **Pro Tip:** Start with AI-generated messages for easier setup, then use > manual control when you need specific content formatting. # Send a template message Source: https://docs.vambe.me/docs/send-template-message Learn how to send WhatsApp template messages via Vambe API for notifications, confirmations, and marketing campaigns. ## 🚀 What you'll build You'll send your first WhatsApp template message using the Vambe API with the correct 3-step flow to gather required IDs. > [!TIP] > > Template messages allow you to reach customers outside the 24-hour window and > send structured, pre-approved content for notifications and marketing. *** ## Prerequisites Before sending template messages, ensure you have: * ✅ [Connected WhatsApp Business API](/docs/connect-whatsapp-api) * ✅ [Created and approved templates](/docs/create-template) * ✅ Valid Vambe API key from [developers page](https://app.vambeai.com/developers) * ✅ Customer phone numbers (must have opted in to receive messages) > [!WARNING] > > **Important:** Only send template messages to customers who have explicitly > opted in. Sending unsolicited messages violates WhatsApp's policies and can > result in account suspension. *** ## Complete API Flow for Sending Templates To send a template message, you need to make 3 API calls in sequence to get the required IDs: **1. Get Channel Information** First, retrieve your channel details: ```bash theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/channels/whatsapp ``` **Sample Response:** ```json theme={null} { "phone_number": "56211111111", "client_id": "339e9487-8168-4e14-b1d8-3dce22d07760", "id": 1951, "name": "Test" } ``` > [!TIP] > > This endpoint retrieves the channel configuration by type. Use `whatsapp`, `instagram`, `web-whatsapp`, or `playground` as channel types. Save the `phone_number` and `client_id` for the template call. **2. Get Pipeline and Stage IDs** Retrieve your pipeline configuration to get stage IDs: ```bash theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/pipeline ``` **Sample Response:** ```json theme={null} [ { "id": "6c9804e2-0b8d-4df1-98f7-7e5be7f69ddb", "name": "Support Iris", "description": "Este embudo califica leads que ten", "stages": [ { "id": "72ba8482-5c1c-4bed-8a6e-16fdb1495776", "name": "Inicial", "description": "En esta etapa la IA de Vambe i" }, { "id": "3690b160-3c79-45f2-b88f-b640d96a36aa", "name": "Asistencia Humana", "description": "Si es que en cualquier punto d" } ] } ] ``` > [!WARNING] > > **Save the stage ID** where you want to send the message. You'll need this `stageId` parameter for the template call. **3. Get Template ID** Find your approved template ID: ```bash theme={null} curl -X GET \ -H "x-api-key: YOUR_API_KEY" \ https://api.vambe.me/api/public/templates ``` **Look for your template name and copy its ID for the final call.** **4. Send the Template Message** Now send your template using the collected IDs: ```bash theme={null} curl -X POST \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "contactName": "John Doe", "variables": ["John Doe", "ORD-12345", "89.99"], "meta_data": {}, "stageId": "72ba8482-5c1c-4bed-8a6e-16fdb1495776" }' \ https://api.vambe.me/api/public/whatsapp/message/send/{phone}/template/{templateId} ``` > [!NOTE] > > **The recipient goes in the path:** `{phone}` is the destination number with country code, digits only (e.g. `56912345678`). > > **Body fields:** > > * `contactName`: Customer name > * `variables`: Array of values for template variables (in order) > * `stageId`: Stage ID from pipeline response > * `meta_data`: Additional metadata object (can be empty) > * `agent_id`: (Optional) Agent ID to assign to the conversation **5. Handle the Response** Process the API response to confirm delivery: ```json theme={null} { "messageId": "f1e2d3c4-b5a6-4978-8899-aabbccddeeff", "aiContactId": "b7c9a9e2-4a4b-4f4e-9d2a-1c2d3e4f5a6b", "ticketId": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d", "contactPhoneNumber": "56912345678", "channelPhoneNumber": "56211111111", "variables": [ ... ] } ``` The message is queued for delivery. Use `messageId` with [GET /api/public/whatsapp/message/status/](/reference/whatsapp-message/get-the-delivery-status-of-a-sent-message) to follow it until it is delivered or read. **Response codes:** * `201`: Message sent successfully * `400`: Bad request (check required fields) * `401`: Unauthorized (verify API key) *** > [!NOTE] > > **Sending verification codes?** Authentication (OTP) templates only take the code. See [Send verification codes (OTP)](/docs/send-otp-message). *** ## Vambe Template Examples ### Simple Template (No Variables) ```bash Welcome Message theme={null} curl -X POST \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "contactName": "John Doe", "variables": [], "meta_data": {}, "stageId": "72ba8482-5c1c-4bed-8a6e-16fdb1495776" }' \ https://api.vambe.me/api/public/whatsapp/message/send/1234567890/template/welcome_message_id ``` ```javascript JavaScript theme={null} const response = await fetch( 'https://api.vambe.me/api/public/whatsapp/message/send/1234567890/template/welcome_message_id', { method: 'POST', headers: { 'x-api-key': process.env.VAMBE_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ contactName: 'John Doe', variables: [], meta_data: {}, stageId: '72ba8482-5c1c-4bed-8a6e-16fdb1495776' }), }, ); ``` ```python Python theme={null} import requests response = requests.post( 'https://api.vambe.me/api/public/whatsapp/message/send/1234567890/template/welcome_message_id', headers={ 'x-api-key': os.environ['VAMBE_API_KEY'], 'Content-Type': 'application/json' }, json={ "contactName": "John Doe", "variables": [], "meta_data": {}, "stageId": "72ba8482-5c1c-4bed-8a6e-16fdb1495776" } ) ``` ### Template with Variables ```bash Order Confirmation theme={null} curl -X POST \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "contactName": "Sarah Johnson", "variables": ["Sarah Johnson", "ORD-12345", "$159.99", "December 28, 2024"], "meta_data": { "order_id": "ORD-12345", "customer_type": "premium", "payment_method": "credit_card" }, "stageId": "72ba8482-5c1c-4bed-8a6e-16fdb1495776" }' \ https://api.vambe.me/api/public/whatsapp/message/send/1234567890/template/order_confirmation_id ``` ```javascript Appointment Reminder theme={null} const response = await fetch( 'https://api.vambe.me/api/public/whatsapp/message/send/1234567890/template/appointment_reminder_id', { method: 'POST', headers: { 'x-api-key': process.env.VAMBE_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ contactName: 'Dr. Smith', variables: [ 'Dr. Smith', 'January 15, 2024', '2:30 PM', 'Downtown Medical Center', ], meta_data: { appointment_id: 'APT-789', department: 'cardiology', patient_id: 'PAT-456', }, stageId: '3690b160-3c79-45f2-b88f-b640d96a36aa' }), }, ); ``` ```python Payment Reminder theme={null} import requests response = requests.post( 'https://api.vambe.me/api/public/whatsapp/message/send/1234567890/template/payment_reminder_id', headers={ 'x-api-key': os.environ['VAMBE_API_KEY'], 'Content-Type': 'application/json' }, json={ "contactName": "Mike Wilson", "variables": ["Mike Wilson", "INV-2024-001", "$250.00", "January 20, 2024"], "meta_data": { "invoice_id": "INV-2024-001", "payment_method": "bank_transfer", "due_date": "2024-01-20" }, "stageId": "72ba8482-5c1c-4bed-8a6e-16fdb1495776" } ) ``` ### Carousel Template Carousel templates allow you to send multiple product cards with images, descriptions, and action buttons in a single message. > [!NOTE] > > The `from-phone-number` query parameter specifies which WhatsApp Business number to send from. This is useful when you have multiple phone numbers connected to your account. ```bash Product Carousel theme={null} curl -X POST \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "variables": ["Customer Name", "Store Name"], "meta_data": {}, "carouselVariables": [ { "cardIndex": 0, "headerVariable": "https://example.com/product1.jpg", "bodyVariables": ["15000"], "buttonVariables": ["https://store.com/product1"] }, { "cardIndex": 1, "headerVariable": "https://example.com/product2.jpg", "bodyVariables": ["16000"], "buttonVariables": ["https://store.com/product2"] }, { "cardIndex": 2, "headerVariable": "https://example.com/product3.jpg", "bodyVariables": ["13000"], "buttonVariables": ["https://store.com/product3"] } ] }' \ "https://api.vambe.me/api/public/whatsapp/message/send/+1234567890/template/{templateId}?from-phone-number=+1987654321" ``` ```javascript Product Carousel theme={null} const response = await fetch( 'https://api.vambe.me/api/public/whatsapp/message/send/+1234567890/template/{templateId}?from-phone-number=+1987654321', { method: 'POST', headers: { 'x-api-key': process.env.VAMBE_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ variables: ['Customer Name', 'Store Name'], meta_data: {}, carouselVariables: [ { cardIndex: 0, headerVariable: 'https://example.com/product1.jpg', bodyVariables: ['15000'], buttonVariables: ['https://store.com/product1'], }, { cardIndex: 1, headerVariable: 'https://example.com/product2.jpg', bodyVariables: ['16000'], buttonVariables: ['https://store.com/product2'], }, { cardIndex: 2, headerVariable: 'https://example.com/product3.jpg', bodyVariables: ['13000'], buttonVariables: ['https://store.com/product3'], }, ], }), }, ); ``` ```python Product Carousel theme={null} import requests import os response = requests.post( 'https://api.vambe.me/api/public/whatsapp/message/send/+1234567890/template/{templateId}?from-phone-number=+1987654321', headers={ 'x-api-key': os.environ['VAMBE_API_KEY'], 'Content-Type': 'application/json' }, json={ "variables": ["Customer Name", "Store Name"], "meta_data": {}, "carouselVariables": [ { "cardIndex": 0, "headerVariable": "https://example.com/product1.jpg", "bodyVariables": ["15000"], "buttonVariables": ["https://store.com/product1"] }, { "cardIndex": 1, "headerVariable": "https://example.com/product2.jpg", "bodyVariables": ["16000"], "buttonVariables": ["https://store.com/product2"] }, { "cardIndex": 2, "headerVariable": "https://example.com/product3.jpg", "bodyVariables": ["13000"], "buttonVariables": ["https://store.com/product3"] } ] } ) ``` *** ## Understanding Vambe Template Format The destination number goes in the path (`/send/{phone}/template/{templateId}`). These are the body fields: | Field | Type | Required | Description | | - | - | - | - | | `contactName` | string | Optional | Customer's name for personalization | | `variables` | string\[] | Required | Array of values for template variables in order | | `meta_data` | object | Optional | Additional metadata (key-value pairs) | | `stageId` | string | Optional | Pipeline stage ID where to send the message | | `carouselVariables` | object\[] | Optional | Variables for carousel template cards (see below) | > [!NOTE] > > **Variable Order:** The `variables` array must match the order of variables in your template. If your template has `{{1}}` for name and `{{2}}` for order number, then `variables: ["John Doe", "ORD-123"]`. ### Carousel Card Variables When sending carousel templates, each card in the `carouselVariables` array has the following structure: | Field | Type | Required | Description | | - | - | - | - | | `cardIndex` | number | Required | Zero-based index of the carousel card (0, 1, 2, ...) | | `headerVariable` | string | Required | URL for the card's header image or video | | `bodyVariables` | string\[] | Optional | Array of variables for the card's body text | | `buttonVariables` | string\[] | Optional | Array of variables for the card's buttons (e.g., URLs) | > [!TIP] > > **Carousel Templates** allow you to send multiple cards with images/videos in a single message. Each card can have its own header media, body text variables, and button actions. Cards are indexed starting from 0. *** ## Alternative Endpoint: Body-based V2 There's an alternative endpoint that accepts all parameters in the request body, including the phone number and template name: **Endpoint:** `POST /api/public/whatsapp/message/send` ### V2 Request Body Schema | Field | Type | Required | Description | | - | - | - | - | | `phone` | string | Required | Phone number to send the template to | | `template_name` | string | Required | Name of the template to send | | `contact_name` | string | Optional | Customer's name for personalization | | `variables` | string\[] | Required | Array of values for template variables in order | | `meta_data` | object | Optional | Additional metadata (key-value pairs) | | `stage_id` | string | Optional | Pipeline stage ID where to send the message | | `agent_id` | string | Optional | Agent ID to assign to the conversation | | `from_phone_number` | string | Optional | Phone number to send the template from | | `carouselVariables` | object\[] | Optional | Variables for carousel template cards (same as above) | ### V2 Carousel Template Example ```bash V2 Product Carousel theme={null} curl -X POST \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "phone": "+1234567890", "template_name": "product_carousel", "contact_name": "John Doe", "variables": ["John Doe", "Store Name"], "meta_data": {}, "from_phone_number": "+1987654321", "carouselVariables": [ { "cardIndex": 0, "headerVariable": "https://example.com/product1.jpg", "bodyVariables": ["15000"], "buttonVariables": ["https://store.com/product1"] }, { "cardIndex": 1, "headerVariable": "https://example.com/product2.jpg", "bodyVariables": ["16000"], "buttonVariables": ["https://store.com/product2"] } ] }' \ https://api.vambe.me/api/public/whatsapp/message/send ``` ```javascript V2 Product Carousel theme={null} const response = await fetch( 'https://api.vambe.me/api/public/whatsapp/message/send', { method: 'POST', headers: { 'x-api-key': process.env.VAMBE_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ phone: '+1234567890', template_name: 'product_carousel', contact_name: 'John Doe', variables: ['John Doe', 'Store Name'], meta_data: {}, from_phone_number: '+1987654321', carouselVariables: [ { cardIndex: 0, headerVariable: 'https://example.com/product1.jpg', bodyVariables: ['15000'], buttonVariables: ['https://store.com/product1'], }, { cardIndex: 1, headerVariable: 'https://example.com/product2.jpg', bodyVariables: ['16000'], buttonVariables: ['https://store.com/product2'], }, ], }), }, ); ``` ```python V2 Product Carousel theme={null} import requests import os response = requests.post( 'https://api.vambe.me/api/public/whatsapp/message/send', headers={ 'x-api-key': os.environ['VAMBE_API_KEY'], 'Content-Type': 'application/json' }, json={ "phone": "+1234567890", "template_name": "product_carousel", "contact_name": "John Doe", "variables": ["John Doe", "Store Name"], "meta_data": {}, "from_phone_number": "+1987654321", "carouselVariables": [ { "cardIndex": 0, "headerVariable": "https://example.com/product1.jpg", "bodyVariables": ["15000"], "buttonVariables": ["https://store.com/product1"] }, { "cardIndex": 1, "headerVariable": "https://example.com/product2.jpg", "bodyVariables": ["16000"], "buttonVariables": ["https://store.com/product2"] } ] } ) ``` > [!NOTE] > > The V2 endpoint uses `template_name` instead of `templateId` in the URL path, and uses snake\_case for field names (`contact_name`, `stage_id`, `from_phone_number`) instead of camelCase. *** ## Advanced Use Cases ### Bulk Template Sending Send templates to multiple customers efficiently: ```javascript Bulk Send theme={null} const customers = [ { name: "John Doe", phone: "1234567890", orderId: "ORD-001" }, { name: "Jane Smith", phone: "1987654321", orderId: "ORD-002" }, { name: "Bob Johnson", phone: "1555123456", orderId: "ORD-003" } ]; const results = await Promise.allSettled( customers.map(async (customer) => { const response = await fetch( `https://api.vambe.me/api/public/whatsapp/message/send/${customer.phone}/template/order_confirmation_id`, { method: 'POST', headers: { 'x-api-key': process.env.VAMBE_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ contactName: customer.name, variables: [customer.name, customer.orderId], meta_data: { order_id: customer.orderId }, stageId: '72ba8482-5c1c-4bed-8a6e-16fdb1495776' }) } ); return { customer: customer.name, result: await response.json() }; }) ); console.log('Bulk send results:', results); ``` ```python Batch Processing theme={null} import requests import time from concurrent.futures import ThreadPoolExecutor def send_template_message(customer): try: response = requests.post( f"https://api.vambe.me/api/public/whatsapp/message/send/{customer['phone']}/template/order_confirmation_id", headers={ 'x-api-key': os.environ['VAMBE_API_KEY'], 'Content-Type': 'application/json' }, json={ "contactName": customer['name'], "variables": [customer['name'], customer['order_id']], "meta_data": {"order_id": customer['order_id']}, "stageId": "72ba8482-5c1c-4bed-8a6e-16fdb1495776" } ) return {"customer": customer['name'], "success": response.status_code == 201} except Exception as e: return {"customer": customer['name'], "error": str(e)} # Rate-limited batch sending customers = [ {"phone": "1234567890", "name": "John Doe", "order_id": "ORD-001"}, {"phone": "1987654321", "name": "Jane Smith", "order_id": "ORD-002"} ] with ThreadPoolExecutor(max_workers=5) as executor: results = list(executor.map(send_template_message, customers)) print("Batch results:", results) ``` *** ## Error Handling ### Common Error Responses > [accordion] Template Not Found (404) > > ```json theme={null} > { > "error": "Template not found", > "code": "TEMPLATE_NOT_FOUND", > "details": "Template ID 'invalid_template_id' does not exist or is not approved" > } > ``` > > **Solutions:** > > * Verify template ID is correct > * Check template approval status in Vambe dashboard > * Ensure template exists for your account > [accordion] Invalid Stage ID (400) > > ```json theme={null} > { > "error": "Invalid stage ID", > "code": "INVALID_STAGE_ID", > "details": "Stage ID does not exist in your pipelines" > } > ``` > > **Solutions:** > > * Check stage ID from pipeline API response > * Verify stage belongs to your account > * Ensure pipeline is active and configured > [accordion] Invalid Phone Number (400) > > ```json theme={null} > { > "error": "Invalid recipient", > "code": "INVALID_PHONE_NUMBER", > "details": "Phone number must include country code" > } > ``` > > **Solutions:** > > * Include country code (e.g., +1 for US) > * Validate phone number format > * Ensure number is active on WhatsApp > [accordion] Rate Limit Exceeded (429) > > ```json theme={null} > { > "error": "Rate limit exceeded", > "code": "RATE_LIMIT_EXCEEDED", > "retry_after": 3600 > } > ``` > > **Solutions:** > > * Implement exponential backoff retry logic > * Check your messaging tier limits > * Spread messages over longer time periods ### Robust Error Handling Example ```javascript Error Handling theme={null} async function sendVambeTemplate(contactName, variables, stageId, toPhoneNumber, templateId) { try { const response = await fetch( `https://api.vambe.me/api/public/whatsapp/message/send/${toPhoneNumber}/template/${templateId}`, { method: 'POST', headers: { 'x-api-key': process.env.VAMBE_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ contactName, variables, meta_data: {}, stageId }) } ); if (!response.ok) { const error = await response.json(); throw new Error(`API Error: ${error.code} - ${error.details}`); } const result = await response.json(); console.log('Message sent successfully:', result.messageId); return result; } catch (error) { console.error('Failed to send template message:', error.message); // Handle specific error cases if (error.message.includes('RATE_LIMIT_EXCEEDED')) { console.log('Rate limit hit, retrying in 1 hour...'); // Implement retry logic } else if (error.message.includes('TEMPLATE_NOT_FOUND')) { console.log('Template needs to be created or approved'); } throw error; } } // Usage with error handling try { await sendVambeTemplate( "John Doe", ["John Doe", "ORD-12345"], "72ba8482-5c1c-4bed-8a6e-16fdb1495776", "1234567890", "order_confirmation_template_id" ); } catch (error) { console.error('Template message failed:', error); } ``` ```python Error Handling theme={null} import requests import time from typing import List, Dict def send_vambe_template( contact_name: str, variables: List[str], stage_id: str, to_phone: str, template_id: str ) -> Dict: url = f"https://api.vambe.me/api/public/whatsapp/message/send/{to_phone}/template/{template_id}" payload = { "contactName": contact_name, "variables": variables, "meta_data": {}, "stageId": stage_id } headers = { 'x-api-key': os.environ['VAMBE_API_KEY'], 'Content-Type': 'application/json' } try: response = requests.post(url, json=payload, headers=headers) if response.status_code == 429: # Rate limit retry_after = response.headers.get('Retry-After', 3600) print(f"Rate limited. Retrying after {retry_after} seconds") time.sleep(int(retry_after)) return send_vambe_template(contact_name, variables, stage_id, to_phone, template_id) response.raise_for_status() result = response.json() print(f"Message sent successfully: {result.get('messageId')}") return result except requests.exceptions.HTTPError as e: error_data = e.response.json() if e.response.content else {} error_code = error_data.get('code', 'UNKNOWN_ERROR') error_details = error_data.get('details', str(e)) print(f"HTTP Error {e.response.status_code}: {error_code} - {error_details}") if error_code == 'TEMPLATE_NOT_FOUND': print("Check if template exists and is approved") elif error_code == 'INVALID_STAGE_ID': print("Verify stage ID from pipeline API") raise except requests.exceptions.RequestException as e: print(f"Request failed: {e}") raise # Usage try: send_vambe_template( "Jane Smith", ["Jane Smith", "ORD-67890"], "72ba8482-5c1c-4bed-8a6e-16fdb1495776", "1234567890", "order_confirmation_template_id" ) except Exception as e: print(f"Failed to send template: {e}") ``` *** ## Best Practices > [card] Message Timing > > * **Respect time zones** - Send during business hours > * **Consider urgency** - Use appropriate delivery timing > * **Batch wisely** - Spread bulk sends over time > * **Avoid peak hours** - Prevent rate limiting > [card] Content Optimization > > * **Personalize content** - Use customer data effectively - **Keep variables > relevant** - Don't include unnecessary data - **Test thoroughly** - Verify all > variable combinations - **Monitor performance** - Track delivery and > engagement > [card] Compliance > > * **Verify opt-ins** - Only message consenting customers - **Honor opt-outs** > * Respect unsubscribe requests - **Follow policies** - Adhere to WhatsApp > guidelines - **Document consent** - Keep records of permissions > [card] Technical Excellence > > * **Handle errors gracefully** - Implement proper error handling > * **Use rate limiting** - Respect API limits > * **Monitor delivery** - Track message status > * **Log thoroughly** - Maintain audit trails *** ## Next Steps > [!TIP] > > Congratulations! You've successfully sent your first WhatsApp template > message. Now you can: > [card] [Automate with Pipelines](/docs/create-pipeline) > > Integrate template messages into automated conversation flows > [card] [Track Performance](/docs/analytics) > > Monitor delivery rates, engagement, and customer responses > [card] [Webhook Integration](/docs/webhooks) > > Set up real-time notifications for message status updates > [card] [Channel Management](/docs/connect-channel) > > Connect additional channels for multi-platform messaging > [!NOTE] > > **Remember:** Template messages are powerful tools for customer communication. > Use them responsibly and always prioritize customer value and consent. # Webchat Integration Guide Source: https://docs.vambe.me/docs/webchat-integration Learn how to integrate Vambe Webchat into your website. Add AI-powered customer support directly to your web pages in minutes. ## Overview The Vambe Webchat is a powerful tool that allows customers to interact with your AI assistant directly from your website, enabling real-time communication and instant support. ## Quick Start ### Prerequisites * Active Vambe account * Access to your website's HTML code * Your Vambe API credentials ### Installation Steps **1. Access Your Vambe Account** Log in to your Vambe account at [app.vambeai.com](https://app.vambeai.com) **2. Navigate to Channels & Accounts** Go to **Settings** → **Channels & Accounts** You can access this directly at: [app.vambeai.com/settings?q=channels](https://app.vambeai.com/settings?q=channels) **3. Add Webchat Channel** 1. Click **"Add Channel"** 2. Select **"Webchat"** from the available options 2. Give your webchat channel a descriptive name (internal use only, not visible to customers) **4. Get Your Integration Code** 1. Click on the newly created Webchat channel 2. Click the three dots menu (⋮) 3. Select the code icon (`<>`) 4. Copy the provided script code **5. Add Code to Your Website** Paste the copied code into the `` section of your website's HTML, preferably just before the closing `` tag. ```html theme={null} Your Website ``` **6. Test the Integration** Refresh your website and you should see the Vambe chat widget appear in the corner of your page. > [!TIP] > > **Success!** Your webchat is now live on your website. Customers can start > chatting with your AI assistant immediately. ## Configuration Options After the basic installation, you can customize your webchat with various options: ### Basic Configuration ```javascript theme={null} window.embeddedWebchatConfig = { // Required fields clientId: 'YOUR_CLIENT_ID', channelId: 'YOUR_CHANNEL_ID', // Agent customization agentName: 'Sofia', agentIconUrl: 'https://your-domain.com/agent-avatar.png', // Appearance primaryColor: '#2994FF', darkTheme: false, // Initial data collection askForName: true, askForEmail: true, askForPhoneNumber: false, // Positioning xPosition: 20, yPosition: 20, // Language language: 'es', // "es" or "en" // Custom text chatWithUsText: 'Chat with us', // Suggested questions suggestedQuestions: [ 'What services do you offer?', 'How can I get started?', 'What are your pricing plans?', ], }; ``` ### Configuration Reference **clientId** `string` *required* Your Vambe client ID (found in the integration code) **channelId** `string` *required* Your webchat channel ID (found in the integration code) **agentName** `string` (default: "") The name of the agent displayed in the chat. Example: `"Sofia"`, `"Customer Support"` **agentIconUrl** `string` (default: "") URL to the agent's avatar image. Must be a valid image URL (JPG, PNG, SVG, etc.) Example: `"https://your-domain.com/avatar.png"` **externalUserId** `string` The user ID from your system. Use this if you're embedding the webchat on a page where users are already logged in. This allows you to: * Track conversations by your user IDs * Link chat history across sessions * Use with [POST /api/public/webchat/contact/add-metadata](/reference/webchat/add-webchat-contact-metadata) endpoint **externalUserName** `string` The user's name from your system. Use when embedding on authenticated pages. **askForPhoneNumber** `boolean` (default: false) Request user's phone number before starting the chat. **askForEmail** `boolean` (default: false) Request user's email before starting the chat. **askForName** `boolean` (default: false) Request user's name before starting the chat. If not provided, contact will be named "Webchat Contact" in Vambe. **darkTheme** `boolean` (default: false) Enable dark theme for the webchat widget. **primaryColor** `string` (default: "#2994FF") Primary color for the chat widget. Must be a valid hex color code. Examples: `"#2994FF"`, `"#FF5733"`, `"#00AA00"` **language** `string` (default: "es") Chat interface language. Options: `"es"` (Spanish) or `"en"` (English) **suggestedQuestions** `array` Up to 4 suggested questions displayed to start the conversation. Example: ```javascript theme={null} suggestedQuestions: [ 'What services do you offer?', 'How can I get started?', 'What are your pricing plans?', 'How do I contact support?', ]; ``` **chatWithUsText** `string` (default: "") Text displayed next to the chat button. Example: `"Chat with us"`, `"Need help?"` **xPosition** `number` (default: 20) Horizontal position of the chat button in pixels from the right edge. **yPosition** `number` (default: 20) Vertical position of the chat button in pixels from the bottom edge. ## Advanced Examples ### Example 1: E-commerce Website ```html theme={null} ``` ### Example 2: Logged-in User Area ```html theme={null} ``` ### Example 3: Multilingual Support ```javascript theme={null} // Detect user's browser language const userLang = navigator.language.startsWith('es') ? 'es' : 'en'; window.embeddedWebchatConfig = { clientId: 'YOUR_CLIENT_ID', channelId: 'YOUR_CHANNEL_ID', language: userLang, // Language-specific suggestions suggestedQuestions: userLang === 'es' ? [ '¿Qué servicios ofrecen?', '¿Cómo puedo empezar?', '¿Cuáles son sus precios?', ] : [ 'What services do you offer?', 'How can I get started?', 'What are your prices?', ], chatWithUsText: userLang === 'es' ? 'Habla con nosotros' : 'Chat with us', }; ``` ### Example 4: Dark Theme for Dark Websites ```html theme={null} ``` ## Customization Tips ### Choosing Colors * **Primary Color**: Used for buttons, headers, and accents * **Brand Alignment**: Use your brand's primary color * **Contrast**: Ensure good contrast with white/dark backgrounds * **Test**: Test with both light and dark themes ```javascript theme={null} // Brand color examples primaryColor: '#2994FF'; // Vambe blue primaryColor: '#FF6B6B'; // E-commerce red primaryColor: '#4CAF50'; // Success green primaryColor: '#9C27B0'; // Tech purple ``` ### Positioning the Widget ```javascript theme={null} // Bottom right (default) xPosition: 20, yPosition: 20 // Bottom left xPosition: 20, yPosition: 20, // + CSS: right -> left position // Custom positioning xPosition: 100, // Further from edge yPosition: 80 // Higher up ``` ### Creating Effective Suggested Questions **✅ Good Examples**: ```javascript theme={null} suggestedQuestions: [ 'What are your business hours?', // Practical 'How much does it cost?', // Clear 'Can you help me track my order?', // Specific 'Do you offer custom solutions?', // Open-ended ]; ``` **❌ Avoid**: ```javascript theme={null} suggestedQuestions: [ 'Hello', // Too vague 'I have a question', // Not specific 'Click here', // Not a question 'Tell me everything', // Too broad ]; ``` ## Integration with User Data ### Pass User Information If users are logged in on your website, pass their information: ```javascript theme={null} // Example with template engine (EJS, Handlebars, etc.) window.embeddedWebchatConfig = { clientId: "YOUR_CLIENT_ID", channelId: "YOUR_CHANNEL_ID", // User info from your session externalUserId: "<%= user.id %>", externalUserName: "<%= user.full_name %>", // Skip collection if already have data askForName: false, askForEmail: <%= user.email ? 'false' : 'true' %> }; ``` ### Add Metadata After Chat Start Use the webchat metadata endpoint to enrich contact data: ```javascript theme={null} // After user interacts with chat async function enrichChatContact(externalUserId, userData) { await fetch('https://api.vambe.me/api/public/webchat/contact/add-metadata', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ externalUserId: externalUserId, metadata: { subscription_tier: userData.tier, account_status: userData.status, lifetime_value: userData.ltv.toString(), last_purchase: userData.lastPurchaseDate, }, }), }); } ``` ## Common Integrations ### WordPress Add to your theme's `footer.php` before ``: ```php theme={null} ``` ### React/Next.js ```typescript theme={null} // components/VambeChat.tsx import { useEffect } from 'react'; export function VambeChat() { useEffect(() => { // Set configuration (window as any).embeddedWebchatConfig = { clientId: process.env.NEXT_PUBLIC_VAMBE_CLIENT_ID, channelId: process.env.NEXT_PUBLIC_VAMBE_CHANNEL_ID, agentName: "Support Team", primaryColor: "#2994FF", language: "en", suggestedQuestions: [ "How can I upgrade my plan?", "Do you offer a free trial?", "How do I contact sales?" ] }; // Load script const script = document.createElement('script'); script.src = 'https://vambeai.com/webchat.js'; script.async = true; document.body.appendChild(script); return () => { // Cleanup if needed document.body.removeChild(script); }; }, []); return null; } // In your layout/page import { VambeChat } from '@/components/VambeChat'; export default function Layout({ children }) { return ( <> {children} ); } ``` ### Vue.js ```vue theme={null} ``` ### Shopify Add to **Online Store** → **Themes** → **Edit Code** → `theme.liquid` before ``: ```liquid theme={null} ``` ## Advanced Features ### Conditional Loading Only load webchat on specific pages: ```javascript theme={null} // Only on product and checkout pages if ( window.location.pathname.includes('/products') || window.location.pathname.includes('/checkout') ) { window.embeddedWebchatConfig = { clientId: 'YOUR_CLIENT_ID', channelId: 'YOUR_CHANNEL_ID', chatWithUsText: 'Need help with your purchase?', }; const script = document.createElement('script'); script.src = 'https://vambeai.com/webchat.js'; document.body.appendChild(script); } ``` ### Dynamic User Identification ```javascript theme={null} // When user logs in, update webchat config function initializeWebchatForUser(user) { window.embeddedWebchatConfig = { clientId: 'YOUR_CLIENT_ID', channelId: 'YOUR_CHANNEL_ID', externalUserId: user.id, externalUserName: user.name, askForName: false, askForEmail: false, }; // Reload webchat with user context const script = document.createElement('script'); script.src = 'https://vambeai.com/webchat.js'; document.body.appendChild(script); } ``` ### Custom Styling While the widget is pre-styled, you can adjust positioning and behavior: ```css theme={null} /* Hide webchat on mobile */ @media (max-width: 768px) { #vambe-webchat { display: none; } } /* Custom z-index if needed */ #vambe-webchat { z-index: 9999 !important; } ``` ## Best Practices ### Performance 1. **Load Asynchronously**: The script loads async by default 2. **After Page Load**: Consider loading after main content 3. **Lazy Load**: Load only when user interacts ```javascript theme={null} // Load on first user interaction let chatLoaded = false; document.addEventListener( 'mousemove', function loadChat() { if (!chatLoaded) { chatLoaded = true; // Load webchat script const script = document.createElement('script'); script.src = 'https://vambeai.com/webchat.js'; document.body.appendChild(script); // Remove listener document.removeEventListener('mousemove', loadChat); } }, { once: true }, ); ``` ### User Experience 1. **Collect Minimal Info**: Only ask for necessary information 2. **Clear Suggestions**: Provide helpful suggested questions 3. **Brand Consistency**: Match your website's colors and style 4. **Mobile Friendly**: Test on mobile devices 5. **Response Time**: Configure AI for quick responses ### Privacy & Compliance ```html theme={null} ``` ## Troubleshooting ### Widget Not Appearing > [accordion] Check script is loaded > > Open browser console and verify: > > ```javascript theme={null} > console.log(window.embeddedWebchatConfig); > ``` > > Should show your configuration object. > [accordion] Verify IDs are correct > > Check that `clientId` and `channelId` match your Vambe account settings. > [accordion] Check for JavaScript errors > > Open browser DevTools (F12) → Console tab Look for errors related to the > webchat script. > [accordion] Verify script source > > Ensure `https://vambeai.com/webchat.js` is accessible and loading. ### Widget Styling Issues * **Z-index**: If widget appears behind other elements, adjust z-index * **Mobile**: Test responsiveness on different screen sizes * **Colors**: Verify hex color codes are valid * **Images**: Ensure avatar URL is accessible and CORS-friendly ### Data Not Syncing * **External User ID**: Verify externalUserId matches your system * **Metadata Endpoint**: Use correct endpoint for webchat contacts * **API Key**: Ensure API key has proper permissions ## Testing Your Integration ### Local Testing 1. **Open your website** in a browser 2. **Click the chat button** - should open chat interface 3. **Send a test message** - verify it appears in Vambe dashboard 4. **Check contact creation** - go to Vambe → Contacts 5. **Verify metadata** - if using externalUserId, check it's saved ### Production Checklist * [ ] Chat button visible and positioned correctly * [ ] Colors match your brand * [ ] Suggested questions are relevant * [ ] Agent name and icon display properly * [ ] Language is correct * [ ] Form fields (name/email/phone) work as expected * [ ] Messages appear in Vambe dashboard * [ ] Contacts are created with correct information * [ ] Mobile version works properly * [ ] No console errors ## Related Resources * [Webchat Metadata Endpoint](/reference/webchat/add-webchat-contact-metadata) - Add metadata to webchat contacts * [Contact Management](/reference/contact/get-info-of-an-ai-contact) - Manage webchat contacts * [Analytics](/docs/analytics) - Track webchat performance * [Webhooks](/docs/webhooks) - Real-time notifications for webchat events # Webhooks Source: https://docs.vambe.me/docs/webhooks Set up real-time notifications for events in your Vambe account using webhooks. Get notified instantly when messages are received, tickets are created, or pipeline stages change. ## Overview Webhooks allow your application to receive real-time notifications when events occur in your Vambe account. Instead of polling for changes, Vambe will send HTTP POST requests to your specified endpoint when events happen. ## Common Use Cases * **Message Notifications**: Get notified when customers send messages * **Ticket Updates**: Track when tickets are created, updated, or closed * **Pipeline Changes**: Monitor when contacts move through pipeline stages * **Contact Events**: Know when new contacts are created * **Integration Sync**: Keep external systems in sync with Vambe data ## How Webhooks Work 1. **Configure Webhook**: Set up a webhook URL in your Vambe account 2. **Events Occur**: Customer sends message, ticket created, stage changed, etc. 3. **Vambe Sends Request**: HTTP POST sent to your webhook URL 4. **Your Server Responds**: Process the event and return 200 OK 5. **Retry Logic**: If your server doesn't respond, Vambe retries ## Webhook Management API Use the webhooks API to manage your webhook configurations programmatically. ### Available Endpoints Check the **Automation & Pipelines** API tab for webhook management endpoints: * **Create Webhook**: `POST /api/webhooks` * **List Webhooks**: `GET /api/webhooks` * **Get Webhook**: `GET /api/webhooks/{id}` * **Update Webhook**: `PUT /api/webhooks/{id}` * **Delete Webhook**: `DELETE /api/webhooks/{id}` * **Restore Webhook**: `POST /api/webhooks/{id}/restore` * **Get Topics**: `GET /api/webhooks/topics` * **Get Webhook Calls**: `GET /api/webhooks/calls` ## Event Types (Topics) Subscribe to specific events to receive notifications: ### Message Events **`message.received`** - Customer sends an inbound message ```json theme={null} { "aiContactId": "38f37371-aa05-477a-b6c1-d161417@ed8d", "data": { "fromNumber": "56998389641", "message": "Ok", "messageId": "0f475695-ec1b-4ca8-b03d-a1c8d066b999", "messageType": "text", "name": "Waita", "stageId": "3abb9d28-141c-45ab-87f8-52919caf63a7", "toNumber": "56961210530" }, "type": "message.received" } ``` **`message.sent`** - Your team sends an outbound message ```json theme={null} { "aiContactId": "e8e08253-aa12-4f32-b4c9-b1fbd180c26b", "data": { "error_details": [ { "code": 131026, "error_data": { "details": "..." }, "message": "Message undeliverable", "title": "Message undeliverable" } ], "fromNumber": "56961210530", "message": "¡Listo Eduardo! ✨ Aquí tienes tu propuesta definitiva...", "messageId": "467ae215-f27a-4c79-ac44-f46fd8a3b28d", "messageType": "template", "name": "Eduardo Mella Navarrete", "status": "failed", "toNumber": "56986874408" }, "type": "message.sent" } ``` **Note**: The `error_details` field in `message.sent` is optional and only present when there are delivery errors. ### Ticket Events **`ticket.created`** - New support ticket opened ```json theme={null} { "event": "ticket.created", "timestamp": "2024-09-30T10:00:00.000Z", "data": { "ticket_id": "ticket-123", "contact_id": "df980fc8-b6db-4820-bf22-2969482d106d", "contact_name": "Maria Rodriguez", "pipeline_id": "pipeline-456", "stage_id": "stage-789", "status": "OPEN" } } ``` **`ticket.updated`** - Ticket status or assignment changes **`ticket.closed`** - Ticket is resolved/closed ### Contact Events **`contact.created`** - New contact added to system **`contact.updated`** - Contact information modified **`contact.tag_added`** - A tag is assigned to a contact or to one of its tickets ```json theme={null} { "topic": "contact.tag_added", "event_type": "CREATE", "entity_name": "AiContactTag", "entity_data": { "id": "8c1f0f3e-5b7a-4d1e-9a51-2f6a1c9d4e10", "created_at": "2026-10-13T14:02:11.000Z", "contact_id": "df980fc8-b6db-4820-bf22-2969482d106d", "ticket_id": null, "tag_id": 12, "tag": { "id": 12, "value": "VIP", "entity_type": "contact" }, "contact": { "id": "df980fc8-b6db-4820-bf22-2969482d106d", "name": "Maria Rodriguez" } }, "timestamp": "2026-10-13T14:02:11.420Z" } ``` * This event uses the entity envelope (`topic`, `entity_data`) instead of `type` and `data`: dispatch on `event.type ?? event.topic`, as the receiver examples below do. * **Customer tags** (`tag.entity_type` = `"contact"`, shown as *Cliente* in the app) belong to the person, not to a single channel: every contact of the same customer (WhatsApp, Instagram, email…) shows them. The event fires **once per assignment** to the customer, with `contact_id` set to the contact it was applied from and `ticket_id` = `null`. Assigning a tag the customer already has, from any channel, does not fire it again; removing it and assigning it again does. * **Customers without contacts** (for example, created only from orders) can be tagged from their customer page. Then `contact_id` and `contact` are `null`, and `entity_data.ai_customer_id` identifies the customer. Webhooks filtered by channel do not receive these events, since there is no channel. * **Ticket tags** (`tag.entity_type` = `"ticket"`) fire it once per assignment to a ticket, with `ticket_id` set, and again if the tag is removed and re-added. * `entity_data.id` identifies the tag assignment, not the tag: use `tag_id` (or `tag.value`) to know which tag was assigned. ### Pipeline Events **`stage.changed`** - Contact moves to different pipeline stage ```json theme={null} { "event": "stage.changed", "timestamp": "2024-09-30T10:05:00.000Z", "data": { "contact_id": "df980fc8-b6db-4820-bf22-2969482d106d", "previous_stage_id": "stage-789", "new_stage_id": "stage-890", "pipeline_id": "pipeline-456", "changed_by": "agent-123" } } ``` ## Webhook Payload Structure When an event occurs, Vambe sends a POST request to your webhook URL: ```json theme={null} { "aiContactId": "38f37371-aa05-477a-b6c1-d161417@ed8d", "data": { "fromNumber": "56998389641", "message": "Hello, I need help", "messageId": "46964423", "messageType": "text", "name": "Maria Rodriguez", "stageId": "3abb9d28-141c-45ab-87f8-52919caf63a7", "toNumber": "56961210530" }, "type": "message.received" } ``` ## Setting Up Webhooks ### 1. Create a Webhook Endpoint Your server must have an endpoint that: * Accepts POST requests * Returns 200 OK status * Responds within 5 seconds * Processes events asynchronously (don't block the response) ```javascript Express.js theme={null} // Express.js webhook endpoint const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhooks/vambe', async (req, res) => { const event = req.body; // Immediately return 200 OK res.status(200).json({ received: true }); // Process event asynchronously try { await processVambeEvent(event); console.log(`✅ Processed ${event.type ?? event.topic}`); } catch (error) { console.error(`❌ Error processing ${event.type ?? event.topic}:`, error); } }); // Message events carry `type` + `data`; entity events such as // contact.tag_added carry `topic` + `entity_data`. async function processVambeEvent(event) { switch (event.type ?? event.topic) { case 'message.received': await handleNewMessage(event.data); break; case 'message.sent': await handleMessageSent(event.data); break; case 'ticket.created': await handleNewTicket(event.data); break; case 'stage.changed': await handleStageChange(event.data); break; case 'contact.tag_added': await handleTagAdded(event.entity_data); break; default: console.log('Unknown event:', event.type ?? event.topic); } } app.listen(3000); ``` ```python FastAPI theme={null} # FastAPI webhook endpoint from fastapi import FastAPI, BackgroundTasks from pydantic import BaseModel app = FastAPI() class WebhookEvent(BaseModel): # Message events carry type + data; entity events such as # contact.tag_added carry topic + entity_data. type: str | None = None topic: str | None = None aiContactId: str | None = None data: dict | None = None entity_data: dict | None = None async def process_vambe_event(event: WebhookEvent): """Process event asynchronously""" if event.topic == "contact.tag_added": await handle_tag_added(event.entity_data) elif event.type == "message.received": await handle_new_message(event.data) elif event.type == "message.sent": await handle_message_sent(event.data) elif event.type == "ticket.created": await handle_new_ticket(event.data) elif event.type == "stage.changed": await handle_stage_change(event.data) @app.post("/webhooks/vambe") async def vambe_webhook( event: WebhookEvent, background_tasks: BackgroundTasks ): # Return immediately background_tasks.add_task(process_vambe_event, event) return {"received": True} ``` ```typescript NestJS theme={null} // NestJS webhook controller import { Controller, Post, Body, HttpCode } from '@nestjs/common'; @Controller('webhooks') export class WebhooksController { constructor( private readonly webhookService: WebhookService, private readonly eventEmitter: EventEmitter2, ) {} @Post('vambe') @HttpCode(200) async handleVambeWebhook(@Body() event: any) { // Emit event for async processing // Message events carry type + data; entity events such as // contact.tag_added carry topic + entity_data. this.eventEmitter.emit( `vambe.${event.type ?? event.topic}`, event.data ?? event.entity_data, ); // Return immediately return { received: true }; } } // Event handler @OnEvent('vambe.message.received') async handleMessageReceived(data: any) { console.log('Processing new message:', data.message); // Your logic here } ``` ### 2. Configure in Vambe Use the API to create a webhook configuration: ```bash theme={null} curl --request POST \ 'https://api.vambe.me/api/webhooks' \ --header 'Content-Type: application/json' \ --header 'x-api-key: your_api_key_here' \ --data-raw '{ "url": "https://your-domain.com/webhooks/vambe", "topics": ["message.received", "ticket.created"], "active": true }' ``` ### 3. Test Your Webhook * Send a test message to trigger the webhook * Check your server logs to verify receipt * Ensure you're returning 200 OK ## Security Best Practices 1. **Validate Requests**: Verify requests are from Vambe 2. **Use HTTPS**: Always use secure endpoints 3. **Verify Signatures**: Check webhook signatures if provided 4. **Rate Limiting**: Implement rate limiting on your endpoint 5. **Idempotency**: Handle duplicate events gracefully ## Error Handling If your webhook endpoint fails to respond: * **Retry Logic**: Vambe will retry failed webhooks * **Backoff Strategy**: Increasing delays between retries * **Max Retries**: After several failures, webhook may be disabled * **Monitor Logs**: Check webhook call logs via API ## Real-World Use Cases ### Use Case 1: Auto-Response to High-Priority Messages ```javascript theme={null} async function handleNewMessage(data) { // If message contains "urgent" keyword if (data.message.toLowerCase().includes('urgent')) { // Tag contact as high priority await fetch( `https://api.vambe.me/api/public/channels/whatsapp/${data.fromNumber}/tags`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': process.env.VAMBE_API_KEY, }, body: JSON.stringify({ tags: ['urgent', 'high-priority'] }), }, ); // Send notification to team await sendSlackAlert(`🚨 Urgent message from ${data.name}`); } } ``` ### Use Case 2: CRM Integration on Ticket Creation ```javascript theme={null} async function handleNewTicket(data) { // Create deal in external CRM await externalCRM.createDeal({ contact_id: data.contact_id, contact_name: data.contact_name, source: 'Vambe Chat', stage: 'New Lead', vambe_ticket_id: data.ticket_id, }); console.log('Deal created in CRM for', data.contact_name); } ``` ### Use Case 3: Update Analytics on Stage Change ```javascript theme={null} async function handleStageChange(data) { // Track conversion funnel await analytics.track('Stage Changed', { contact_id: data.contact_id, from_stage: data.previous_stage_id, to_stage: data.new_stage_id, pipeline: data.pipeline_id, timestamp: new Date(), }); // If moved to "Qualified" stage, notify sales team if (data.new_stage_id === 'qualified-stage-id') { await notifySalesTeam(data.contact_id); } } ``` ### Use Case 4: Auto-Assignment Based on Message Content ```javascript theme={null} async function handleNewMessage(data) { const messageText = data.message.toLowerCase(); // Route based on message content let assigneeId; if (messageText.includes('billing') || messageText.includes('payment')) { assigneeId = 'billing-team-member-id'; } else if (messageText.includes('technical') || messageText.includes('bug')) { assigneeId = 'tech-support-member-id'; } else { assigneeId = 'general-support-member-id'; } // Auto-assign to appropriate team member // Note: Use the aiContactId from the parent webhook event await fetch( `https://api.vambe.me/api/public/contact/{aiContactId}/assign-team-member/${assigneeId}`, { method: 'POST', headers: { 'x-api-key': process.env.VAMBE_API_KEY }, }, ); } ``` ## Webhook Management with API ### Create a Webhook ```bash theme={null} curl --request POST \ 'https://api.vambe.me/api/webhooks' \ --header 'Content-Type: application/json' \ --header 'x-api-key: your_api_key_here' \ --data-raw '{ "url": "https://your-domain.com/webhooks/vambe", "topics": ["message.received", "ticket.created", "stage.changed"], "active": true, "description": "Main webhook for production" }' ``` ### List All Webhooks ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/webhooks' \ --header 'x-api-key: your_api_key_here' ``` ### Update Webhook ```bash theme={null} curl --request PUT \ 'https://api.vambe.me/api/webhooks/webhook-id-123' \ --header 'Content-Type: application/json' \ --header 'x-api-key: your_api_key_here' \ --data-raw '{ "active": false }' ``` ### Delete Webhook ```bash theme={null} curl --request DELETE \ 'https://api.vambe.me/api/webhooks/webhook-id-123' \ --header 'x-api-key: your_api_key_here' ``` ### Get Available Topics ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/webhooks/topics' \ --header 'x-api-key: your_api_key_here' ``` ### View Webhook Call History ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/webhooks/calls' \ --header 'x-api-key: your_api_key_here' ``` ## Debugging Webhooks ### Log Everything During Development ```javascript theme={null} app.post('/webhooks/vambe', (req, res) => { console.log('=== Webhook Received ==='); console.log('Headers:', req.headers); console.log('Body:', JSON.stringify(req.body, null, 2)); console.log('Event Type:', req.body.type); console.log('AI Contact ID:', req.body.aiContactId); console.log('========================'); res.status(200).send('OK'); // Process after response processEvent(req.body); }); ``` ### Test Webhook Locally with ngrok ```bash theme={null} # 1. Start ngrok tunnel ngrok http 3000 # 2. Use ngrok URL for webhook # https://abc123.ngrok.io/webhooks/vambe # 3. Test by triggering events in Vambe # 4. Watch logs in ngrok dashboard ``` ### Common Issues **Issue**: Webhook not receiving events * ✅ Verify webhook is active (`GET /api/webhooks`) * ✅ Check URL is publicly accessible * ✅ Verify subscribed to correct topics * ✅ Check firewall/security groups **Issue**: Receiving duplicate events * ✅ Implement idempotency with event IDs * ✅ Track processed events in database * ✅ Return 200 OK even if duplicate **Issue**: Webhook timing out * ✅ Process events asynchronously * ✅ Return 200 OK immediately * ✅ Don't wait for external API calls ## Advanced Patterns ### Idempotency Pattern ```javascript theme={null} const processedEvents = new Set(); app.post('/webhooks/vambe', async (req, res) => { const event = req.body; const eventId = `${event.type}-${event.aiContactId}-${event.data.messageId}`; // Check if already processed if (processedEvents.has(eventId)) { console.log('Duplicate event, skipping'); return res.status(200).send('OK'); } // Mark as processed processedEvents.add(eventId); res.status(200).send('OK'); // Process event await processVambeEvent(event); }); ``` ### Queue-Based Processing ```javascript theme={null} // Use a queue for reliable processing const Queue = require('bull'); const webhookQueue = new Queue('vambe-webhooks'); app.post('/webhooks/vambe', async (req, res) => { // Add to queue await webhookQueue.add(req.body); // Return immediately res.status(200).send('OK'); }); // Process from queue webhookQueue.process(async (job) => { const event = job.data; await processVambeEvent(event); }); ``` ### Event Filtering ```javascript theme={null} // Only process certain events or conditions app.post('/webhooks/vambe', async (req, res) => { const event = req.body; res.status(200).send('OK'); // Filter: Only process messages with "order" keyword if ( event.type === 'message.received' && event.data.message.toLowerCase().includes('order') ) { await processOrderInquiry(event.data); } // Filter: Only process tickets in specific pipeline if ( event.type === 'ticket.created' && event.data.pipeline_id === 'sales-pipeline-id' ) { await processSalesTicket(event.data); } }); ``` ## Related Resources * [Webhook API Reference](#) - Full webhook management endpoints * [Analytics](/docs/analytics) - Monitor webhook event patterns * [Integration Guide](/docs/integration-to-the-api) - API integration overview * [Contact Management](/reference/contact/get-info-of-an-ai-contact) - Webhook data usage # Create Merge Customers By Ai Contact Source: https://docs.vambe.me/reference/ai-customer/post-api-public-ai-customer-merge-customers-by-ai-contact post /api/public/ai-customer/merge-customers/by-ai-contact # Start OAuth connection Source: https://docs.vambe.me/reference/app-platform/connect-app post /api/ecommerce-app/{id}/connect Returns the provider authorization URL to redirect the merchant to. The merchant approves scopes on the provider page — Vambe never collects credentials. Returns the provider authorization URL to redirect the merchant to. The merchant approves the requested scopes on the provider's own page — Vambe never collects provider credentials. After approval the provider redirects back to Vambe's callback, which exchanges the code and persists the installation. # Create an app Source: https://docs.vambe.me/reference/app-platform/create-app post /api/ecommerce-app Creates an app in draft status, owned by the calling account. Only visible to the account until approved by the Vambe team. Creates an app in `draft` status, owned by the calling account. The app stays visible only to your account until the Vambe team approves it; once approved it becomes installable by any account. The response includes the `signing_secret` used to sign webhook payloads — store it securely, it is shown only on create and on [rotate](/reference/app-platform/rotate-secret). # Delete an app Source: https://docs.vambe.me/reference/app-platform/delete-app delete /api/ecommerce-app/{id} Deletes an app you own. # Get an app Source: https://docs.vambe.me/reference/app-platform/get-app get /api/ecommerce-app/{id} Returns a single app owned by the calling account. Secrets are never returned here — use [rotate the signing secret](/reference/app-platform/rotate-secret) if you need a new one. # List your apps Source: https://docs.vambe.me/reference/app-platform/list-apps get /api/ecommerce-app Lists the apps owned by the calling account, in any status (draft, pending review, approved, rejected, suspended). # List installable apps Source: https://docs.vambe.me/reference/app-platform/list-installable-apps get /api/ecommerce-app/available Apps the account can install: approved apps only. A developer connects their own draft from the app checklist. Lists the apps the account can install: every approved app plus any drafts owned by the calling account. This is the catalog a merchant picks from when connecting an integration. # Rotate the signing secret Source: https://docs.vambe.me/reference/app-platform/rotate-secret post /api/ecommerce-app/{id}/rotate-secret Generates a new signing secret for webhook HMAC signatures. The previous secret stops being valid immediately. Generates a new `signing_secret` for webhook HMAC signatures and returns it. The previous secret stops being valid immediately, so update your signing code before sending the next webhook. # Submit an app for review Source: https://docs.vambe.me/reference/app-platform/submit-app post /api/ecommerce-app/{id}/submit Sends the app to the Vambe team for approval. Once approved it becomes installable by any account. Sends the app to the Vambe team for approval and notifies them on Slack. While pending the app remains visible only to your account. Once approved it becomes installable by any account. # Update an app Source: https://docs.vambe.me/reference/app-platform/update-app patch /api/ecommerce-app/{id} Updates the editable fields of an app you own (name, description, logo URL, contact details, OAuth config, capabilities). Editing an app that was already approved may require re-submission for review. # Checkout event Source: https://docs.vambe.me/reference/app-platform/webhook-checkout post /api/public/apps/{appId}/events/checkout Push an abandoned/created checkout to enable recovery for the resolved installation. Push an abandoned or created checkout so Vambe can drive checkout recovery for the resolved installation. > [!NOTE] > > Every webhook must be signed: send `x-vambe-signature` (hex HMAC-SHA256 of `${x-vambe-timestamp}.${rawBody}` using the app signing secret) and `x-vambe-timestamp` (unix epoch seconds). Requests older than 5 minutes are rejected. # Fulfillment event Source: https://docs.vambe.me/reference/app-platform/webhook-fulfillment post /api/public/apps/{appId}/events/fulfillment Push a shipment/fulfillment. Linked to its order even if it arrives before the order webhook. Push a shipment/fulfillment update. The shipment is linked to its order even if the fulfillment arrives before the order webhook (it is backfilled when the order lands). > [!NOTE] > > Every webhook must be signed: send `x-vambe-signature` (hex HMAC-SHA256 of `${x-vambe-timestamp}.${rawBody}` using the app signing secret) and `x-vambe-timestamp` (unix epoch seconds). Requests older than 5 minutes are rejected. # Order event Source: https://docs.vambe.me/reference/app-platform/webhook-order post /api/public/apps/{appId}/events/order Push a created/updated order. Routed into the standard ecommerce order pipeline for the resolved installation. Push a created or updated order. Vambe resolves the installation from `appId` (and `external_store_id` for multi-store apps) and routes the order into the standard ecommerce pipeline. > [!NOTE] > > Every webhook must be signed: send `x-vambe-signature` (hex HMAC-SHA256 of `${x-vambe-timestamp}.${rawBody}` using the app signing secret) and `x-vambe-timestamp` (unix epoch seconds). Requests older than 5 minutes are rejected. # Product upsert event Source: https://docs.vambe.me/reference/app-platform/webhook-product post /api/public/apps/{appId}/events/product Create or update a product (matched by external id) for the resolved installation. Create or update a product, matched by its external id, for the resolved installation. > [!NOTE] > > Every webhook must be signed: send `x-vambe-signature` (hex HMAC-SHA256 of `${x-vambe-timestamp}.${rawBody}` using the app signing secret) and `x-vambe-timestamp` (unix epoch seconds). Requests older than 5 minutes are rejected. # Product delete event Source: https://docs.vambe.me/reference/app-platform/webhook-product-delete post /api/public/apps/{appId}/events/product/delete Delete a product by external id for the resolved installation. Delete a product by its external id for the resolved installation. > [!NOTE] > > Every webhook must be signed: send `x-vambe-signature` (hex HMAC-SHA256 of `${x-vambe-timestamp}.${rawBody}` using the app signing secret) and `x-vambe-timestamp` (unix epoch seconds). Requests older than 5 minutes are rejected. # Get booking page configuration Source: https://docs.vambe.me/reference/booking-url/get-api-public-booking-url-urlname get /api/public/booking-url/{urlName} # Get availabilities Source: https://docs.vambe.me/reference/booking-url/get-api-public-booking-url-urlname-availabilities get /api/public/booking-url/{urlName}/availabilities # Get availabilities by professional & treatment Source: https://docs.vambe.me/reference/booking-url/get-api-public-booking-url-urlname-availabilities-professional-treatment get /api/public/booking-url/{urlName}/availabilities/professional/treatment # Get availabilities by treatment & location Source: https://docs.vambe.me/reference/booking-url/get-api-public-booking-url-urlname-availabilities-treatment-location get /api/public/booking-url/{urlName}/availabilities/treatment/location # List professionals Source: https://docs.vambe.me/reference/booking-url/get-api-public-booking-url-urlname-professionals get /api/public/booking-url/{urlName}/professionals # List treatments Source: https://docs.vambe.me/reference/booking-url/get-api-public-booking-url-urlname-treatments get /api/public/booking-url/{urlName}/treatments # Create an appointment Source: https://docs.vambe.me/reference/booking-url/post-api-public-booking-url-urlname-create-appointment post /api/public/booking-url/{urlName}/create-appointment # Create a patient Source: https://docs.vambe.me/reference/booking-url/post-api-public-booking-url-urlname-patients post /api/public/booking-url/{urlName}/patients # Create campaign Source: https://docs.vambe.me/reference/campaigns/create-campaign post /api/public/outreach-campaign Create a one-time campaign that sends up to 5 Meta templates, in order, to the contacts of a segment. A recipient who replies stops receiving the steps after it. One campaign can be created every 30 minutes per account. Creates a one-time campaign that sends up to 5 Meta templates, in order, to the contacts of a segment. ## How it sends * **Audience**: the segment's contacts are captured when the campaign is created. Contacts who join the segment later are not added. * **Steps**: each step waits `wait_before` (1 day by default) after the previous one. A recipient who replies stops receiving the steps after it. * **Start**: `start_at` is `"now"` (the default) or a future date-time. Without `batch_size`, everyone is released at once; with `batch_size` and `batch_interval_minutes`, the audience is released in batches until everyone has been reached. ## Template variables `variables` sets each template variable by its position: `"1"` is `{{1}}`, counted across header, body and buttons, in that order. A value is either fixed text or a contact placeholder resolved for each recipient: | Placeholder | Value | | - | - | | `__CONTACT_NAME__` | Contact name | | `__CONTACT_EMAIL__` | Contact email | | `__CONTACT_PHONE__` | Contact phone | Header and body variables you leave out are written by the AI for each recipient, from their contact information and conversation. The response lists them in `ai_filled_variables`. Button variables (URLs, phone numbers and button text) are required. ## Limits One campaign can be created every 30 minutes per account. A request inside that window answers `429` with `retry_after_seconds`. Requests rejected with a `4xx` before the campaign is created do not start the window. Track the campaign with [Get campaign](/reference/campaigns/get-campaign) and [Get campaign recipients](/reference/campaigns/get-campaign-recipients). # Get campaign Source: https://docs.vambe.me/reference/campaigns/get-campaign get /api/public/outreach-campaign/{campaignId} Retrieve one campaign with its results (reach, responses, conversions and revenue) and the performance of each send step. Use Get campaign recipients for the per-recipient detail. # Get campaign recipients Source: https://docs.vambe.me/reference/campaigns/get-campaign-recipients get /api/public/outreach-campaign/{campaignId}/recipients Retrieve a campaign's recipients a page at a time: who was reached, who responded or converted and, for every send step, the per-message outcome (delivered, read, failed and why, buttons pressed, email status, call result). # List campaigns Source: https://docs.vambe.me/reference/campaigns/get-campaigns get /api/public/outreach-campaign List your one-time campaigns, newest first, with their status, audience and delivery progress. # Get contacts sent in a campaign (Removed) Source: https://docs.vambe.me/reference/campaigns/legacy-get-campaign-contacts get /api/public/campaign/contacts/{campaignId} Removed: every call returns 410 Gone. Use [List campaigns](/reference/campaigns/get-campaigns) (`GET /api/public/outreach-campaign`) and [Get campaign](/reference/campaigns/get-campaign) (`GET /api/public/outreach-campaign/{campaignId}`) instead. Campaign IDs are now UUIDs. # List campaigns (Removed) Source: https://docs.vambe.me/reference/campaigns/legacy-list-campaigns get /api/public/campaign Removed: every call returns 410 Gone. Use [List campaigns](/reference/campaigns/get-campaigns) (`GET /api/public/outreach-campaign`) and [Get campaign](/reference/campaigns/get-campaign) (`GET /api/public/outreach-campaign/{campaignId}`) instead. Campaign IDs are now UUIDs. # List a contact's campaigns Source: https://docs.vambe.me/reference/campaigns/list-contact-campaigns get /api/public/outreach-campaign/by-contact/{contactId} List the campaigns a contact received, newest first, each with only that contact's participation: delivery status, whether they responded or converted, the ticket fields uploaded for them and the outcome of every send step. # Retrieve channel by type Source: https://docs.vambe.me/reference/channels/retrieve-channel-by-type get /api/public/channels/{channelType} Fetches the channel associated with the specified channel type for the authenticated user. # Get all tags for an AI contact Source: https://docs.vambe.me/reference/contact/get-all-tags-for-an-ai-contact get /api/public/contact/tags/{aiContactId} Returns the tags the contact shows: its customer's tags (CONTACT type, shared by every contact of the same customer) plus the tags of its open tickets (TICKET type). Each item is the tag itself (`id`, `value`) with the date it was assigned. # Get contacts by time filters Source: https://docs.vambe.me/reference/contact/get-contacts-by-days get /api/public/contacts Retrieve contacts filtered by activity (last message within N days), creation time, or update time. Works across all channels (WhatsApp, Instagram, etc.). At least one of days, created_after, or updated_after is required. For incremental sync, poll with updated_after set to the latest updated_at you have stored: the response includes both created_at and updated_at so you can tell new contacts (created_at > your cursor) apart from updated ones. Results are ordered ascending by updated_at (or created_at) when those filters are used, so you can page forward with limit/offset and advance your cursor safely. Optionally filter by custom field values. ## Overview Retrieve contacts that had their last message within a specified number of days. This endpoint works across all communication channels (WhatsApp, Instagram, Web Chat, SMS, etc.) providing a unified view of recent contact activity. Perfect for identifying active contacts, tracking engagement, and filtering contacts by recency across your entire customer base. ## Use Cases * **Active Contacts Dashboard**: Show contacts who messaged in the last 7, 30, or 90 days * **Engagement Metrics**: Track how many contacts are actively engaging * **Re-engagement Campaigns**: Find contacts who haven't messaged recently * **Activity Reports**: Generate reports of contact activity over time * **Cross-Channel Analytics**: See all active contacts regardless of channel * **CRM Sync**: Export recently active contacts to external systems ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Query Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `days` | number | No | Filter contacts whose last message was within this many days (1-365) | | `created_after` | string (ISO 8601) | No | Return only contacts created strictly after this timestamp. Use for syncing newly created contacts. | | `updated_after` | string (ISO 8601) | No | Return only contacts updated strictly after this timestamp. Use as a sync cursor to pull both new and modified contacts since the last poll. | | `limit` | number | No | Maximum number of contacts to return (1-1000) | | `offset` | number | No | Number of contacts to skip, for pagination | | `stage_id` | string (UUID) | No | Stage ID to filter contacts by stage | | `pipeline_id` | string (UUID) | No | Pipeline ID to filter contacts by their active ticket's pipeline | | `custom_field_key` | string | No | The key of the custom field to filter by. Must be provided together with `custom_field_value`. | | `custom_field_value` | string | No | The value to match for the custom field. Must be provided together with `custom_field_key`. | | `entity_type` | string | No | `"ticket"` or `"customer"` — scopes the custom field filter to that entity type. Only applies with `custom_field_key`/`custom_field_value`. | | `with_utm_events` | boolean | No | Set to `true` to include the per-contact `utm_events` array (marketing attribution). Off by default — the key is omitted entirely unless requested. | > [!NOTE] > > **At least one time filter is required**: you must provide `days`, > `created_after`, or `updated_after`. ## Response Structure Returns an array of contact objects: | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier for the contact | | `name` | string | Contact's full name | | `phone` | string \| null | Contact's phone number | | `email` | string \| null | Contact's email address | | `platform` | string | Communication channel (whatsapp, instagram, etc.) | | `last_message_at` | string (ISO) | Timestamp of the last message sent/received | | `chat_status` | string | Current chat status (UNATTENDED, ATTENDED, etc.) | | `created_at` | string (ISO) | Contact creation timestamp | | `client_id` | string (UUID) | Your organization ID | | `ai_customer_id` | string (UUID) | Associated customer profile ID | | `default_stage_id` | string (UUID) | Contact's default pipeline stage | | `blocked` | boolean | Whether the contact is blocked | | `is_chat_read` | boolean | Whether the chat has been read by an agent | | `active_ticket_v2` | object \| null | Active ticket information (see below) | | `utm_events` | array | Marketing attribution events for this contact (see below) | ### Active Ticket Object (`active_ticket_v2`) | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier for the ticket | | `current_stage_id` | string \| null | Current pipeline stage ID for the ticket | ### UTM Event Object (`utm_events[]`) Marketing attribution events recorded for the contact, ordered oldest first. Empty array when the contact has no attribution events. | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier for the UTM event | | `created_at` | string (ISO) \| null | When the attribution event was recorded | | `customer_id` | string (UUID) \| null | Associated customer profile ID | | `integration_type` | string \| null | Ad platform (facebook, google, tiktok, etc.) | | `ad_id` | string \| null | Ad identifier | | `referrer_url` | string \| null | Landing / referrer URL that captured the contact | | `search_keyword` | string \| null | Search keyword that triggered the ad | ## Example Request ### Basic Request (All Contacts) ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contacts?days=30' \ --header 'x-api-key: your_api_key_here' ``` ### Request with Stage Filter ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contacts?days=30&stage_id=123e4567-e89b-12d3-a456-426614174000' \ --header 'x-api-key: your_api_key_here' ``` ### Request with Pipeline Filter ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contacts?days=30&pipeline_id=123e4567-e89b-12d3-a456-426614174000' \ --header 'x-api-key: your_api_key_here' ``` ### Request with UTM Events ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contacts?days=30&with_utm_events=true' \ --header 'x-api-key: your_api_key_here' ``` ## Example Response The response below assumes `with_utm_events=true` was passed — without it, the `utm_events` key is omitted from every contact entirely. ```json theme={null} [ { "id": "df980fc8-b6db-4820-bf22-2969482d106d", "name": "Maria Rodriguez", "phone": "+56912345678", "email": "maria.rodriguez@example.com", "platform": "whatsapp", "last_message_at": "2024-09-30T14:25:33.000Z", "chat_status": "ATTENDED", "created_at": "2024-01-15T10:00:00.000Z", "client_id": "550e8400-e29b-41d4-a716-446655440000", "ai_customer_id": "660e8400-e29b-41d4-a716-446655440001", "default_stage_id": "770e8400-e29b-41d4-a716-446655440002", "blocked": false, "is_chat_read": true, "active_ticket_v2": { "id": "bb0e8400-e29b-41d4-a716-446655440006", "current_stage_id": "cc0e8400-e29b-41d4-a716-446655440007" }, "utm_events": [ { "id": "ee0e8400-e29b-41d4-a716-446655440009", "created_at": "2024-01-14T22:05:11.000Z", "customer_id": "660e8400-e29b-41d4-a716-446655440001", "integration_type": "facebook", "ad_id": "23854715623450123", "referrer_url": "https://example.com/landing?utm_campaign=spring", "search_keyword": null } ] }, { "id": "880e8400-e29b-41d4-a716-446655440003", "name": "Carlos Silva", "phone": "+56987654321", "email": null, "platform": "instagram", "last_message_at": "2024-09-29T18:10:22.000Z", "chat_status": "UNATTENDED", "created_at": "2024-03-20T09:30:00.000Z", "client_id": "550e8400-e29b-41d4-a716-446655440000", "ai_customer_id": "990e8400-e29b-41d4-a716-446655440004", "default_stage_id": "aa0e8400-e29b-41d4-a716-446655440005", "blocked": false, "is_chat_read": false, "active_ticket_v2": { "id": "dd0e8400-e29b-41d4-a716-446655440008", "current_stage_id": null }, "utm_events": [] } ] ``` ## Common Use Cases ### 1. Get Contacts from Last 7 Days ```javascript theme={null} const getRecentContacts = async () => { const response = await fetch( 'https://api.vambe.me/api/public/contacts?days=7', { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); console.log(`Found ${contacts.length} contacts active in the last 7 days`); return contacts; }; ``` ### 2. Track Engagement by Channel ```javascript theme={null} const getContactsByChannel = async (days) => { const response = await fetch( `https://api.vambe.me/api/public/contacts?days=${days}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); // Group by platform const byChannel = contacts.reduce((acc, contact) => { const channel = contact.platform || 'unknown'; if (!acc[channel]) acc[channel] = []; acc[channel].push(contact); return acc; }, {}); console.log('Contacts by channel:', { whatsapp: byChannel.whatsapp?.length || 0, instagram: byChannel.instagram?.length || 0, webchat: byChannel.webchat?.length || 0, }); return byChannel; }; ``` ### 3. Find Unattended Contacts ```javascript theme={null} const getUnattendedContacts = async (days) => { const response = await fetch( `https://api.vambe.me/api/public/contacts?days=${days}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); // Filter unattended const unattended = contacts.filter( (c) => c.chat_status === 'UNATTENDED' && !c.is_chat_read, ); console.log(`${unattended.length} unattended contacts need attention`); return unattended; }; ``` ### 4. Re-engagement Campaign Data ```javascript theme={null} const getContactsForReengagement = async () => { // Get contacts from 30-60 days ago (active before but not recently) const recent30 = await fetch( 'https://api.vambe.me/api/public/contacts?days=30', { headers: { 'x-api-key': 'your_api_key_here' }, }, ).then((r) => r.json()); const recent60 = await fetch( 'https://api.vambe.me/api/public/contacts?days=60', { headers: { 'x-api-key': 'your_api_key_here' }, }, ).then((r) => r.json()); // Contacts in 60 days but not in 30 days const recent30Ids = new Set(recent30.map((c) => c.id)); const reengageTargets = recent60.filter((c) => !recent30Ids.has(c.id)); console.log(`${reengageTargets.length} contacts for re-engagement campaign`); return reengageTargets; }; ``` ### 5. Export to External CRM ```javascript theme={null} const exportRecentContactsToCRM = async (days) => { const response = await fetch( `https://api.vambe.me/api/public/contacts?days=${days}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); // Export to external CRM for (const contact of contacts) { await fetch('https://external-crm.com/api/contacts/sync', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer crm_token', }, body: JSON.stringify({ external_id: contact.id, name: contact.name, phone: contact.phone, email: contact.email, platform: contact.platform, last_activity: contact.last_message_at, status: contact.chat_status, }), }); } console.log(`Exported ${contacts.length} contacts to CRM`); }; ``` ### 6. Filter Contacts by Pipeline Stage ```javascript theme={null} const getContactsByStage = async (days, stageId) => { const response = await fetch( `https://api.vambe.me/api/public/contacts?days=${days}&stage_id=${stageId}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); console.log(`Found ${contacts.length} contacts in stage ${stageId}`); return contacts; }; // Example: Get all leads from the last 30 days const leadStageId = '123e4567-e89b-12d3-a456-426614174000'; const leads = await getContactsByStage(30, leadStageId); ``` ### 7. Activity Dashboard ```javascript theme={null} const buildActivityDashboard = async () => { const periods = [ { label: 'Today', days: 1 }, { label: 'Last 7 days', days: 7 }, { label: 'Last 30 days', days: 30 }, { label: 'Last 90 days', days: 90 }, ]; const dashboard = {}; for (const period of periods) { const response = await fetch( `https://api.vambe.me/api/public/contacts?days=${period.days}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); dashboard[period.label] = { total: contacts.length, unattended: contacts.filter((c) => c.chat_status === 'UNATTENDED').length, attended: contacts.filter((c) => c.chat_status === 'ATTENDED').length, byChannel: contacts.reduce((acc, c) => { acc[c.platform] = (acc[c.platform] || 0) + 1; return acc; }, {}), }; } console.log('Activity Dashboard:', dashboard); return dashboard; }; ``` ## Query Parameters Details ### Days Parameter The `days` parameter filters contacts where `last_message_at` is within the specified number of days from now: | Days Value | Description | Use Case | | - | - | - | | `1` | Last 24 hours | Today's activity | | `7` | Last week | Weekly engagement report | | `30` | Last month | Monthly active contacts | | `90` | Last quarter | Quarterly analysis | | `180` | Last 6 months | Semi-annual review | | `365` | Last year (maximum allowed) | Annual customer base analysis | ### Stage ID Parameter The optional `stage_id` parameter filters contacts by their current pipeline stage. Only contacts with an active ticket in the specified stage will be returned. | Parameter | Type | Required | Description | | - | - | - | - | | `stage_id` | string | No | UUID of the pipeline stage to filter by | > [!NOTE] > > **Stage Filtering**: When `stage_id` is provided, only contacts with an active > ticket (`active_ticket_v2`) in that specific stage are returned. Contacts > without an active ticket or in a different stage are excluded. ### Pipeline ID Parameter The optional `pipeline_id` parameter filters contacts by the pipeline of their active ticket's current stage. | Parameter | Type | Required | Description | | - | - | - | - | | `pipeline_id` | string | No | UUID of the pipeline to filter by | > [!NOTE] > > **Pipeline Filtering**: When `pipeline_id` is provided, only contacts with an active > ticket whose current stage belongs to that pipeline are returned. You can combine > `pipeline_id` with `stage_id` to filter by both. ## Response Ordering Contacts are returned ordered by `last_message_at` in **descending order** (most recent first). ## Cross-Channel Support This endpoint returns contacts from **all channels**: | Platform | Description | | - | - | | `whatsapp` | WhatsApp Business API | | `web-whatsapp` | WhatsApp Web (QR) | | `instagram` | Instagram Direct Messages | | `webchat` | Web chat widget | | `sms` | SMS messages | | `messenger` | Facebook Messenger | | `tiktok` | TikTok Direct Messages | | `voice` | Voice calls | | `playground` | Test/playground channel | ## Error Responses | Status Code | Description | | - | - | | 400 | Bad Request - Invalid days parameter (must be 1-365) | | 401 | Unauthorized - Invalid or missing API key | | 500 | Internal Server Error - Something went wrong | ## Important Notes * **Days Range**: Must be between 1 and 365 days * **Null Values**: Some fields like `email` or `phone` may be null * **Performance**: Response time increases with larger `days` values * **All Channels**: Unlike the deprecated WhatsApp-specific endpoint, this returns contacts from ALL channels * **Contact Count**: No pagination - returns all contacts matching the criteria * **Stage Filtering**: When `stage_id` is provided, only contacts with an active ticket in that stage are returned * **Pipeline Filtering**: When `pipeline_id` is provided, only contacts with an active ticket in a stage belonging to that pipeline are returned * **Combined Filters**: `days`, `stage_id`, and `pipeline_id` can be used together to narrow down results * **Active Ticket**: The `active_ticket_v2` object contains the current ticket's `id` and `current_stage_id` ## Performance Considerations * **Cache Results**: Consider caching responses for frequently used `days` values * **Large Datasets**: For `days` values > 90, expect larger response sizes * **Rate Limiting**: Be mindful of rate limits when making frequent requests ## Comparison with Deprecated Endpoint | Feature | New Endpoint (This) | Deprecated Endpoint | | - | - | - | | **Path** | `/api/public/contacts` | `/api/public/whatsapp/contact/contacts` | | **Channels** | All channels | WhatsApp only | | **Response** | AI Contact objects | WhatsApp Contact objects | | **Ordering** | By last\_message\_at DESC | Not specified | | **Future Support** | ✅ Active development | ❌ Deprecated | ## Related Endpoints * [GET /api/public/contact//info](/reference/contact/get-info-of-an-ai-contact) - Get detailed contact info * [POST /api/public/customer/upsert/info](/reference/customer/upsert-customer-info) - Create or update contact * [POST /api/public/contact//update-metadata](/reference/contact/update-contact-metadata) - Update contact metadata ## Best Practices ### 1. Choose Appropriate Days Range ```javascript theme={null} // Good: Specific use case const getWeeklyActive = () => fetch('...?days=7'); const getMonthlyActive = () => fetch('...?days=30'); // Avoid: Unnecessarily large range const getAll = () => fetch('...?days=365'); // Only if you need a full year ``` ### 2. Handle Empty Results ```javascript theme={null} const contacts = await fetch('...?days=7').then((r) => r.json()); if (contacts.length === 0) { console.log('No contacts in the last 7 days'); } else { console.log(`Found ${contacts.length} active contacts`); } ``` ### 3. Filter on Client Side ```javascript theme={null} const contacts = await fetch('...?days=30').then((r) => r.json()); // Filter by platform const whatsappContacts = contacts.filter((c) => c.platform === 'whatsapp'); // Filter by status const unread = contacts.filter((c) => !c.is_chat_read); // Filter by date range const thisWeek = contacts.filter((c) => { const msgDate = new Date(c.last_message_at); const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); return msgDate > sevenDaysAgo; }); ``` # Retrieve conversations by AI contact Source: https://docs.vambe.me/reference/contact/get-conversations get /api/public/contact/{aiContactId}/conversations ## Overview Retrieve conversations with a contact, automatically grouped into conversation threads. Messages are intelligently organized by time gaps and context, making it easy to understand the flow of communication. This endpoint is ideal when you want to display conversation history in a chat-like interface with messages grouped into distinct conversation sessions. ## Use Cases * **Chat Interface**: Display conversation history in a threaded chat UI * **Conversation Analysis**: Analyze conversation patterns and engagement * **Context Building**: Get conversation context for AI or agent responses * **Support Ticket View**: Show conversation threads for support tickets * **Activity Timeline**: Display communication timeline with grouped sessions * **Export Conversations**: Export conversation history for records ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `aiContactId` | string (UUID) | Yes | Unique identifier of the contact | ## Query Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `daysBack` | number | No | Number of days back to retrieve conversations | > [!NOTE] > > **Days Back**: If not provided, retrieves all conversations. Use this to limit > results to recent conversations only. ## Response Structure Returns an array of conversation objects. Each conversation represents a grouped thread of messages: ### Conversation Object | Field | Type | Description | | - | - | - | | `conversation_id` | number | Unique numeric identifier for the conversation | | `conversation_date` | string (ISO) | Timestamp when the conversation started | | `stage_id` | string (UUID) | Pipeline stage during this conversation | | `conversation_channel` | string (UUID) | Channel/phone identifier | | `platform` | string | Communication channel (whatsapp, web-whatsapp, etc.) | | `phone_number_channel` | string | Your WhatsApp phone number (with +) | | `conversation_detail` | array | Array of message objects in this conversation | ### Message Object Each message in the `conversation_detail` array contains: | Field | Type | Description | | - | - | - | | `id` | string | Unique message identifier (numeric string) | | `body` | string | Message content/text | | `created_at` | string (ISO) | Message timestamp | | `direction` | string | "inbound" (from contact) or "outbound" (to contact) | | `platform_contact_id` | string (UUID) | Platform-specific contact identifier | | `status` | string | Message status (read, sent, delivered) | | `type` | string | Message type (text, image, video, reaction, etc.) | | `user_id` | string \| null | Agent who sent the message (if outbound by human) | | `assistant_id` | string \| null | AI assistant that sent the message (if AI-generated) | ## Example Request ### Get All Conversations ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contact/df980fc8-b6db-4820-bf22-2969482d106d/conversations' \ --header 'x-api-key: your_api_key_here' ``` ### Get Last 7 Days of Conversations ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contact/df980fc8-b6db-4820-bf22-2969482d106d/conversations?daysBack=7' \ --header 'x-api-key: your_api_key_here' ``` ## Example Response ```json theme={null} [ { "conversation_id": 1, "conversation_date": "2024-09-30T10:00:00.000Z", "stage_id": "550e8400-e29b-41d4-a716-446655440000", "conversation_channel": "ccfe327c-e5df-4063-b99f-9795033b0be3", "platform": "web-whatsapp", "phone_number_channel": "+56999315943", "conversation_detail": [ { "id": "46964423", "created_at": "2024-09-30T10:02:00.000Z", "body": "Es el #12345", "direction": "inbound", "platform_contact_id": "2b52e5a6-f290-4678-9138-882c39d94b92", "status": "read", "type": "text", "user_id": null, "assistant_id": null }, { "id": "46964282", "created_at": "2024-09-30T10:01:30.000Z", "body": "Por supuesto! ¿Cuál es tu número de pedido?", "direction": "outbound", "platform_contact_id": "2b52e5a6-f290-4678-9138-882c39d94b92", "status": "sent", "type": "text", "user_id": "c6382bff-da3a-44c6-90b7-65038be5725c", "assistant_id": null }, { "id": "46964114", "created_at": "2024-09-30T10:00:00.000Z", "body": "Hola! Necesito ayuda con mi pedido", "direction": "inbound", "platform_contact_id": "2b52e5a6-f290-4678-9138-882c39d94b92", "status": "read", "type": "text", "user_id": null, "assistant_id": null } ] }, { "conversation_id": 2, "conversation_date": "2024-09-29T15:30:00.000Z", "stage_id": "660e8400-e29b-41d4-a716-446655440001", "conversation_channel": "ccfe327c-e5df-4063-b99f-9795033b0be3", "platform": "whatsapp", "phone_number_channel": "+56999315943", "conversation_detail": [ { "id": "46950000", "created_at": "2024-09-29T15:30:00.000Z", "body": "Gracias por la ayuda!", "direction": "inbound", "platform_contact_id": "2b52e5a6-f290-4678-9138-882c39d94b92", "status": "read", "type": "text", "user_id": null, "assistant_id": null } ] } ] ``` ## Common Use Cases ### 1. Display Chat Interface ```javascript theme={null} const displayConversations = async (contactId) => { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/conversations`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const conversations = await response.json(); conversations.forEach((conv) => { console.log(`\n--- Conversation ${conv.conversation_id} ---`); console.log( `Started: ${new Date(conv.conversation_date).toLocaleString()}`, ); console.log(`Messages: ${conv.conversation_detail.length}`); console.log(`Platform: ${conv.platform}`); conv.conversation_detail.forEach((msg) => { const label = msg.direction === 'inbound' ? 'Customer' : 'Agent/AI'; const timestamp = new Date(msg.created_at).toLocaleTimeString(); const sender = msg.user_id ? 'Agent' : msg.assistant_id ? 'AI' : 'Customer'; console.log(`[${timestamp}] ${sender}: ${msg.body}`); }); }); return conversations; }; ``` ### 2. Get Recent Conversations Only ```javascript theme={null} const getRecentConversations = async (contactId, days = 30) => { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/conversations?daysBack=${days}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const conversations = await response.json(); console.log( `Found ${conversations.length} conversations in last ${days} days`, ); return conversations; }; ``` ### 3. Analyze Conversation Patterns ```javascript theme={null} const analyzeConversations = async (contactId) => { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/conversations`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const conversations = await response.json(); const stats = { totalConversations: conversations.length, totalMessages: conversations.reduce( (sum, conv) => sum + conv.conversation_detail.length, 0, ), averageMessagesPerConversation: conversations.reduce( (sum, conv) => sum + conv.conversation_detail.length, 0, ) / conversations.length, mostRecentConversation: conversations[0]?.conversation_date, messagesByAgent: conversations.reduce((sum, conv) => { return ( sum + conv.conversation_detail.filter((m) => m.user_id !== null).length ); }, 0), messagesByAI: conversations.reduce((sum, conv) => { return ( sum + conv.conversation_detail.filter((m) => m.assistant_id !== null).length ); }, 0), messagesByCustomer: conversations.reduce((sum, conv) => { return ( sum + conv.conversation_detail.filter((m) => m.direction === 'inbound').length ); }, 0), }; console.log('Conversation Analysis:', stats); return stats; }; ``` ### 4. Export Conversation History ```javascript theme={null} const exportConversationHistory = async (contactId) => { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/conversations`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const conversations = await response.json(); // Convert to readable format const transcript = conversations .map((conv) => { const header = `\n===== Conversation ${conv.conversation_id} =====\nDate: ${new Date(conv.conversation_date).toLocaleString()}\nPlatform: ${conv.platform}\nMessages: ${conv.conversation_detail.length}\n\n`; const messages = conv.conversation_detail .reverse() // Most recent last for readability .map((msg) => { const timestamp = new Date(msg.created_at).toLocaleTimeString(); let sender = 'Customer'; if (msg.direction === 'outbound') { sender = msg.user_id ? 'Agent' : msg.assistant_id ? 'AI Assistant' : 'System'; } return `[${timestamp}] ${sender}: ${msg.body}`; }) .join('\n'); return header + messages; }) .join('\n\n'); return transcript; }; ``` ## Key Features ### Agent vs AI Detection This endpoint provides visibility into who sent each outbound message: * **`user_id` present**: Message was sent by a human agent * **`assistant_id` present**: Message was sent by AI assistant * **Both null**: Message sent by customer (inbound) ```javascript theme={null} conv.conversation_detail.forEach((msg) => { if (msg.direction === 'outbound') { if (msg.user_id) { console.log('Sent by human agent'); } else if (msg.assistant_id) { console.log('Sent by AI assistant'); } else { console.log('System message'); } } }); ``` ### Message Types The endpoint supports various message types: * **`text`**: Regular text messages * **`image`**: Image messages * **`video`**: Video messages * **`audio`**: Audio/voice messages * **`reaction`**: Emoji reactions to messages * **`document`**: File/document attachments ## How Conversations Are Grouped Messages are automatically grouped into conversations based on: 1. **Time Gaps**: Messages separated by long periods are in different conversations 2. **Context Changes**: Stage changes or significant topic shifts create new conversations 3. **Chronological Order**: Conversations are ordered by most recent first Each conversation has a unique `conversation_id` (numeric) that you can use for reference. ## When to Use This Endpoint **✅ Use `/conversations` when**: * Building a chat interface with conversation threads * You want messages automatically grouped * Displaying conversation history to users * Analyzing conversation patterns * Exporting readable conversation transcripts **❌ Don't use when**: * You need all messages in a flat list → Use `/v2/{aiContactId}/messages` * You need pagination for large message sets → Use `/v2/{aiContactId}/messages` * You want to process messages sequentially → Use `/v2/{aiContactId}/messages` ## Error Responses | Status Code | Description | | - | - | | 401 | Unauthorized - Invalid or missing API key | | 404 | Not Found - Contact not found | | 500 | Internal Server Error - Something went wrong | ## Performance Considerations * **All Messages**: Without `daysBack`, returns all conversations (can be large) * **Use daysBack**: For better performance, limit to recent conversations * **No Pagination**: All matching conversations returned at once * **Grouped Data**: Response is larger than flat message list due to grouping ## Related Endpoints * [GET /api/public/contact/v2//messages](/reference/contact/get-messages-paginated) - Get messages with pagination (recommended for large datasets) * [GET /api/public/contact//info](/reference/contact/get-info-of-an-ai-contact) - Get contact info * [POST /api/public/contact//update-metadata](/reference/contact/update-contact-metadata) - Update contact metadata ## Comparison with Messages Endpoint | Feature | Conversations (This) | Messages v2 | | - | - | - | | **Structure** | Grouped: `conversation_detail` arrays | Flat list of messages | | **Grouping Logic** | Auto-grouped by time gaps & context | No grouping | | **Pagination** | No pagination | Required (`page` parameter) | | **Time Filtering** | `daysBack` parameter | Via page iteration | | **Agent/AI Detection** | ✅ `user_id` & `assistant_id` fields | Limited info | | **Conversation Context** | ✅ `conversation_id`, `stage_id` per thread | No conversation grouping | | **Response Size** | Larger (nested structure) | Smaller (flat structure) | | **Best For** | Chat UI, conversation threads | Bulk processing, exports, analytics | | **Field Names** | `conversation_detail`, `direction` lowercase | Different structure | | **Message Order** | Within conversations | Global chronological | # Get info of an AI contact Source: https://docs.vambe.me/reference/contact/get-info-of-an-ai-contact get /api/public/contact/{aiContactId}/info ## Overview Retrieve comprehensive information about a specific contact, including their profile data, active ticket, last closed ticket, and custom metadata. This endpoint is essential for getting the complete context of a contact's current state and interaction history. ## Use Cases * **Contact Profile Display**: Show detailed contact information in your CRM or dashboard * **Ticket Management**: Access current and historical ticket data for support workflows * **Custom Data Integration**: Retrieve custom metadata fields for personalized experiences * **Contact Status Tracking**: Monitor contact engagement status and last interaction * **Support Agent Context**: Provide agents with full contact history before responding * **Agent Assignment Tracking**: See which team members are currently assigned to a contact ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `aiContactId` | string (UUID) | Yes | Unique identifier of the contact to retrieve | ## Response Structure The endpoint returns a contact object with the following structure: ### Contact Object | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier for the contact | | `name` | string | Contact's full name | | `email` | string \| null | Contact's email address | | `phone` | string \| null | Contact's phone number | | `platform` | string | Communication channel (e.g., "whatsapp", "instagram", "webchat") | | `created_at` | string (ISO) | Timestamp when the contact was created | | `last_message_at` | string (ISO) | Timestamp of the last message sent or received | | `last_message_content` | string \| null | Content of the last message | | `chat_status` | string | Current chat status (e.g., "UNATTENDED", "ATTENDED", "CLOSED") | | `is_chat_read` | boolean | Whether the chat has been read by an agent | | `blocked` | boolean | Whether the contact is blocked | | `client_id` | string (UUID) | ID of the client/owner account | | `ai_customer_id` | string (UUID) | Associated customer profile ID | | `default_stage_id` | string \| null | ID of the contact's current pipeline stage | | `active_ticket_v2_id` | string \| null | ID of the currently active ticket | | `last_closed_ticket_v2_id` | string \| null | ID of the most recently closed ticket | | `current_integration_data` | object \| null | Integration-specific data (e.g., CRM sync info) | | `metadata` | object | Custom key-value pairs for additional contact data | | `active_ticket` | object \| null | Details of the currently active ticket | | `last_closed_ticket` | object \| null | Details of the last closed ticket | | `assigned_agents` | array | List of team members assigned to this contact | ### Assigned Agent Object Each item in the `assigned_agents` array contains: | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier of the assigned team member | | `name` | string | Full name of the team member (first name + last name) | | `email` | string | Email address of the team member | ### Active Ticket Object When a contact has an active ticket, the `active_ticket` field contains: | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique ticket identifier | | `ai_contact_id` | string (UUID) | Associated contact ID | | `status` | string | Ticket status (e.g., "OPEN", "IN\_PROGRESS") | | `created_at` | string (ISO) | Ticket creation timestamp | | `updated_at` | string (ISO) | Last update timestamp | | `ticket_summary` | string \| null | AI-generated or human summary of the ticket | | `metadata` | object | Custom ticket metadata | ### Last Closed Ticket Object The `last_closed_ticket` field has the same structure as `active_ticket` but represents the most recently closed ticket. ## Example Response ```json theme={null} { "id": "df980fc8-b6db-4820-bf22-2969482d106d", "name": "Maria Rodriguez", "email": "maria.rodriguez@example.com", "phone": "+56912345678", "platform": "whatsapp", "created_at": "2024-01-15T10:30:00.000Z", "last_message_at": "2024-09-30T14:25:33.000Z", "last_message_content": "Gracias por tu ayuda!", "chat_status": "ATTENDED", "is_chat_read": true, "blocked": false, "client_id": "550e8400-e29b-41d4-a716-446655440000", "ai_customer_id": "660e8400-e29b-41d4-a716-446655440001", "default_stage_id": "770e8400-e29b-41d4-a716-446655440002", "active_ticket_v2_id": "880e8400-e29b-41d4-a716-446655440003", "last_closed_ticket_v2_id": "990e8400-e29b-41d4-a716-446655440004", "current_integration_data": { "crm_id": "12345", "last_sync": "2024-09-30T12:00:00.000Z" }, "metadata": { "company": "Acme Corp", "plan": "Premium", "customer_since": "2024-01-15", "preferred_language": "es" }, "active_ticket": { "id": "880e8400-e29b-41d4-a716-446655440003", "ai_contact_id": "df980fc8-b6db-4820-bf22-2969482d106d", "status": "IN_PROGRESS", "created_at": "2024-09-30T10:00:00.000Z", "updated_at": "2024-09-30T14:25:33.000Z", "ticket_summary": "Customer inquiring about premium plan upgrade options and pricing", "metadata": { "priority": "high", "category": "sales", "assigned_agent": "John Doe" } }, "last_closed_ticket": { "id": "990e8400-e29b-41d4-a716-446655440004", "ai_contact_id": "df980fc8-b6db-4820-bf22-2969482d106d", "status": "CLOSED", "created_at": "2024-09-25T09:00:00.000Z", "updated_at": "2024-09-25T15:30:00.000Z", "ticket_summary": "Billing inquiry resolved - payment processed successfully", "metadata": { "priority": "medium", "category": "billing", "resolution_time": "6.5 hours" } }, "assigned_agents": [ { "id": "228d7a0d-9072-4ca8-939b-959b75cc606a", "name": "John Doe", "email": "john.doe@example.com" }, { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "name": "Jane Smith", "email": "jane.smith@example.com" } ] } ``` ## Common Use Cases ### 1. Display Contact Profile in Dashboard ```javascript theme={null} const contactId = 'df980fc8-b6db-4820-bf22-2969482d106d'; const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/info`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contact = await response.json(); // Display in UI console.log(`Name: ${contact.name}`); console.log(`Email: ${contact.email}`); console.log(`Phone: ${contact.phone}`); console.log(`Platform: ${contact.platform}`); console.log(`Status: ${contact.chat_status}`); ``` ### 2. Check for Active Tickets ```javascript theme={null} const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/info`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contact = await response.json(); if (contact.active_ticket) { console.log('Active ticket found:', contact.active_ticket.ticket_summary); console.log('Ticket status:', contact.active_ticket.status); console.log( 'Created:', new Date(contact.active_ticket.created_at).toLocaleString(), ); } else { console.log('No active tickets for this contact'); } ``` ### 3. Access Custom Metadata ```javascript theme={null} const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/info`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contact = await response.json(); // Access custom metadata const company = contact.metadata?.company; const plan = contact.metadata?.plan; const customerSince = contact.metadata?.customer_since; console.log( `${contact.name} from ${company} has been a ${plan} customer since ${customerSince}`, ); ``` ### 4. Get Last Interaction Info ```javascript theme={null} const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/info`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contact = await response.json(); const lastMessageDate = new Date(contact.last_message_at); const daysSinceLastMessage = Math.floor( (Date.now() - lastMessageDate.getTime()) / (1000 * 60 * 60 * 24), ); console.log(`Last message: ${contact.last_message_content}`); console.log(`${daysSinceLastMessage} days ago`); console.log(`Read status: ${contact.is_chat_read ? 'Read' : 'Unread'}`); ``` ## Chat Status Values The `chat_status` field can have the following values: | Status | Description | | - | - | | `UNATTENDED` | New message received, not yet attended by an agent | | `ATTENDED` | Agent is actively working on the conversation | | `CLOSED` | Conversation has been closed/resolved | | `PENDING` | Waiting for customer response or additional information | ## Platform Values The `platform` field indicates the communication channel: | Platform | Description | | - | - | | `whatsapp` | WhatsApp (API or QR) | | `instagram` | Instagram Direct Messages | | `webchat` | Web chat widget | | `tiktok` | TikTok Direct Messages | | `sms` | SMS messages | | `messenger` | Facebook Messenger | | `voice` | Voice calls | ## Error Responses | Status Code | Description | | - | - | | 400 | Bad Request - Invalid contact ID format | | 401 | Unauthorized - Invalid or missing API key | | 404 | Not Found - Contact does not exist | | 500 | Internal Server Error - Something went wrong | ## Tips * **Contact ID Format**: Always use the UUID format for `aiContactId` * **Null Values**: Many fields can be `null` - always check before accessing nested properties * **Metadata Structure**: Custom metadata fields vary by organization - check your specific fields * **Ticket History**: Only the last closed ticket is returned, not all historical tickets * **Real-time Data**: This endpoint returns current data - for historical conversation data, use the messages endpoint * **Backward Compatibility**: The response includes both `active_ticket_v2` and `active_ticket` for compatibility # Retrieve messages by AI contact with pagination Source: https://docs.vambe.me/reference/contact/get-messages-paginated get /api/public/contact/v2/{aiContactId}/messages Replaces the old endpoint /public/ai-message/:aiContactId ## Overview Retrieve messages from a contact with pagination support. This endpoint returns a flat list of messages in chronological order, perfect for processing large message histories efficiently. This is the recommended endpoint for accessing message history when you need pagination, sequential processing, or want to handle large datasets. ## Use Cases * **Message Processing**: Process messages sequentially for analytics or exports * **Large Message Histories**: Handle contacts with thousands of messages efficiently * **Data Export**: Export all messages in chunks * **Message Analytics**: Analyze message patterns, response times, sentiment * **Search & Filter**: Build custom message search and filtering * **Audit Logs**: Create audit trails of all communications ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `aiContactId` | string (UUID) | Yes | Unique identifier of the contact | ## Query Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `page` | number | Yes | Page number to retrieve (starts at 1) | > [!NOTE] > > **Pagination**: Each page returns a fixed number of messages. Keep > incrementing `page` until you receive an empty array. ## Response Structure Returns an object with pagination information and messages: | Field | Type | Description | | - | - | - | | `messages` | array | Array of message objects for this page | | `page` | number | Current page number | | `hasMore` | boolean | Whether there are more pages available | | `total` | number | Total number of messages (optional) | ### Message Object | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique message identifier | | `body` | string | Message content/text | | `created_at` | string (ISO) | Message timestamp | | `direction` | string | "INBOUND" or "OUTBOUND" | | `from` | string | Sender identifier (phone/username) | | `to` | string | Recipient identifier | | `type` | string | Message type (text, image, video, audio, etc.) | | `status` | string | Delivery status (sent, delivered, read, failed) | | `media_url` | string \| null | URL to media file (if applicable) | | `client_id` | string (UUID) | Your organization ID | | `ai_contact_id` | string (UUID) | Associated contact ID | ## Example Requests ### Get First Page ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contact/v2/df980fc8-b6db-4820-bf22-2969482d106d/messages?page=1' \ --header 'x-api-key: your_api_key_here' ``` ### Get Second Page ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contact/v2/df980fc8-b6db-4820-bf22-2969482d106d/messages?page=2' \ --header 'x-api-key: your_api_key_here' ``` ## Example Response ```json theme={null} { "messages": [ { "id": "msg-001", "body": "Hola! Necesito ayuda con mi pedido", "created_at": "2024-09-30T10:00:00.000Z", "direction": "INBOUND", "from": "+56912345678", "to": "+56987654321", "type": "text", "status": "delivered", "media_url": null, "client_id": "550e8400-e29b-41d4-a716-446655440000", "ai_contact_id": "df980fc8-b6db-4820-bf22-2969482d106d" }, { "id": "msg-002", "body": "Por supuesto! ¿Cuál es tu número de pedido?", "created_at": "2024-09-30T10:01:30.000Z", "direction": "OUTBOUND", "from": "+56987654321", "to": "+56912345678", "type": "text", "status": "read", "media_url": null, "client_id": "550e8400-e29b-41d4-a716-446655440000", "ai_contact_id": "df980fc8-b6db-4820-bf22-2969482d106d" } ], "page": 1, "hasMore": true, "total": 127 } ``` ## Common Use Cases ### 1. Fetch All Messages with Pagination ```javascript theme={null} const getAllMessages = async (contactId) => { let allMessages = []; let page = 1; let hasMore = true; while (hasMore) { const response = await fetch( `https://api.vambe.me/api/public/contact/v2/${contactId}/messages?page=${page}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const data = await response.json(); allMessages = allMessages.concat(data.messages); hasMore = data.hasMore; page++; console.log( `Fetched page ${page - 1}, total messages: ${allMessages.length}`, ); } console.log(`Retrieved all ${allMessages.length} messages`); return allMessages; }; ``` ### 2. Export Messages to CSV ```javascript theme={null} const exportMessagesToCSV = async (contactId) => { const allMessages = await getAllMessages(contactId); const csvRows = [ 'Timestamp,Direction,From,To,Message,Type,Status', ...allMessages.map((msg) => { const timestamp = new Date(msg.created_at).toISOString(); const message = msg.body.replace(/"/g, '""'); // Escape quotes return `"${timestamp}","${msg.direction}","${msg.from}","${msg.to}","${message}","${msg.type}","${msg.status}"`; }), ]; const csvContent = csvRows.join('\n'); console.log('CSV export ready'); return csvContent; }; ``` ### 3. Calculate Response Time Metrics ```javascript theme={null} const calculateResponseMetrics = async (contactId) => { const allMessages = await getAllMessages(contactId); const responseTimes = []; for (let i = 0; i < allMessages.length - 1; i++) { const current = allMessages[i]; const next = allMessages[i + 1]; // If customer message followed by agent message if (current.direction === 'INBOUND' && next.direction === 'OUTBOUND') { const responseTime = new Date(next.created_at) - new Date(current.created_at); responseTimes.push(responseTime); } } const averageResponseTime = responseTimes.reduce((sum, time) => sum + time, 0) / responseTimes.length; const metrics = { totalMessages: allMessages.length, inboundMessages: allMessages.filter((m) => m.direction === 'INBOUND') .length, outboundMessages: allMessages.filter((m) => m.direction === 'OUTBOUND') .length, averageResponseTimeMinutes: (averageResponseTime / 1000 / 60).toFixed(2), fastestResponseMinutes: (Math.min(...responseTimes) / 1000 / 60).toFixed(2), slowestResponseMinutes: (Math.max(...responseTimes) / 1000 / 60).toFixed(2), }; console.log('Response Metrics:', metrics); return metrics; }; ``` ### 4. Find Messages with Specific Content ```javascript theme={null} const findMessagesContaining = async (contactId, searchTerm) => { const allMessages = await getAllMessages(contactId); const matches = allMessages.filter((msg) => msg.body.toLowerCase().includes(searchTerm.toLowerCase()), ); console.log(`Found ${matches.length} messages containing "${searchTerm}"`); return matches; }; // Usage const orderMentions = await findMessagesContaining('contact-id', 'order'); const urgentMessages = await findMessagesContaining('contact-id', 'urgent'); ``` ### 5. Get Latest Messages Only ```javascript theme={null} const getLatestMessages = async (contactId, limit = 20) => { const response = await fetch( `https://api.vambe.me/api/public/contact/v2/${contactId}/messages?page=1`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const data = await response.json(); const latestMessages = data.messages.slice(0, limit); console.log(`Retrieved ${latestMessages.length} latest messages`); return latestMessages; }; ``` ## Pagination Details ### Page Size * Each page typically returns 20-50 messages (exact number may vary) * Pages are numbered starting from 1 * Messages are ordered chronologically (oldest to newest or newest to oldest) ### Fetching All Pages ```javascript theme={null} // Helper function to fetch all pages const fetchAllPages = async (contactId) => { let currentPage = 1; let allMessages = []; let hasMore = true; while (hasMore) { const response = await fetch( `https://api.vambe.me/api/public/contact/v2/${contactId}/messages?page=${currentPage}`, { headers: { 'x-api-key': 'your_api_key_here' }, }, ); const data = await response.json(); if (data.messages.length === 0) { hasMore = false; } else { allMessages.push(...data.messages); currentPage++; } } return allMessages; }; ``` ## Error Responses | Status Code | Description | | - | - | | 400 | Bad Request - Invalid page parameter | | 401 | Unauthorized - Invalid or missing API key | | 404 | Not Found - Contact not found | | 500 | Internal Server Error - Something went wrong | ## Important Notes * **Pagination Required**: The `page` parameter is mandatory * **Page Starts at 1**: First page is 1, not 0 * **No Total Count**: Response may not include total message count * **Check hasMore**: Use `hasMore` field to determine if more pages exist * **Cross-Channel**: Works with all communication channels * **Include Stage History**: Messages include stage change events ## When to Use This vs Conversations | Requirement | Use This Endpoint (Messages v2) | Use Conversations | | - | - | - | | **Need pagination** | ✅ Yes | ❌ No | | **Large message history** | ✅ Yes | ❌ No | | **Flat message list** | ✅ Yes | ❌ No | | **Sequential processing** | ✅ Yes | ❌ No | | **Chat UI with threads** | ❌ No | ✅ Yes | | **Conversation view** | ❌ No | ✅ Yes | | **Human-readable format** | ❌ No | ✅ Yes | | **Filter by recent days** | Use pagination | ✅ `daysBack` parameter | ## Related Endpoints * [GET /api/public/contact//conversations](/reference/contact/get-conversations) - Get conversations grouped (better for chat UI) * [GET /api/public/contact//info](/reference/contact/get-info-of-an-ai-contact) - Get contact info * [GET /api/public/contacts/search](/reference/contact/search-contacts) - Search contacts by phone/email ## Best Practices ### 1. Handle Empty Pages ```javascript theme={null} const getMessagesPage = async (contactId, page) => { const response = await fetch( `https://api.vambe.me/api/public/contact/v2/${contactId}/messages?page=${page}`, { headers: { 'x-api-key': 'your_api_key_here' }, }, ); const data = await response.json(); if (data.messages.length === 0) { console.log('No more messages'); return null; } return data; }; ``` ### 2. Implement Rate Limiting ```javascript theme={null} const fetchWithDelay = async (contactId, maxPages) => { const allMessages = []; for (let page = 1; page <= maxPages; page++) { const data = await getMessagesPage(contactId, page); if (!data || data.messages.length === 0) break; allMessages.push(...data.messages); // Add delay to avoid rate limiting await new Promise((resolve) => setTimeout(resolve, 100)); } return allMessages; }; ``` ### 3. Cache Pages ```javascript theme={null} const messageCache = new Map(); const getCachedMessagesPage = async (contactId, page) => { const cacheKey = `${contactId}-${page}`; if (messageCache.has(cacheKey)) { return messageCache.get(cacheKey); } const response = await fetch( `https://api.vambe.me/api/public/contact/v2/${contactId}/messages?page=${page}`, { headers: { 'x-api-key': 'your_api_key_here' }, }, ); const data = await response.json(); messageCache.set(cacheKey, data); return data; }; ``` # Retrieve messages by AI contact with pagination Source: https://docs.vambe.me/reference/contact/get-messages-paginated-v3 get /api/public/contact/v3/{aiContactId}/messages Paginated message history, newest first. Prefer this over v2: `page` is 1-based and echoed back unchanged, `page_size` is configurable, and `total`/`pages` describe exactly what `data` contains — `data.length` never exceeds `page_size`, and summing `data` across all pages equals `total`. Unlike v2, the response contains only real messages: the synthetic "stage" and "interactive_note" entries that v2 injects are not messages and are not returned here. Also unlike v2, this endpoint is side-effect free: reading messages does NOT mark the conversation as read. Requesting a page beyond the last one returns an empty `data` with `has_next_page: false`. ## Overview Retrieve a contact's messages with pagination, **newest first**. This is the recommended endpoint for reading message history. Use this instead of [v2](/reference/contact/get-messages-paginated): `page` is 1-based and echoed back unchanged, `page_size` is configurable, and the counters describe exactly what you receive. ## Authentication Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `aiContactId` | string (UUID) | Yes | Unique identifier of the contact | ## Query Parameters | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `page` | number | No | `1` | Page number, **1-based**. Page 1 = newest messages | | `page_size` | number | No | `15` | Messages per page, between `1` and `100` | Both parameters must be integers. `page` below 1, `page_size` outside 1–100, and fractional values are rejected with `400`. ## Response Structure | Field | Type | Description | | - | - | - | | `data` | array | Messages for this page, ordered newest first | | `page` | number | The page you requested, echoed back | | `page_size` | number | The page size in effect | | `pages` | number | Total number of pages. Valid values for `page` are `1..pages` | | `total` | number | Total messages for this contact across all pages | | `has_next_page` | boolean | Whether a page after this one exists | > [!NOTE] > > The counters are self-consistent: `data` never holds more than `page_size` > items, and summing `data` across all pages equals `total`. ### Message Object This list is **exhaustive** and identical on every channel — the response carries these fields and nothing else: | Field | Type | Description | | - | - | - | | `id` | string | Message identifier, always a string (some channels store it as an integer internally) | | `created_at` | string (ISO) | Message timestamp | | `body` | string | Message text | | `direction` | string | `inbound`, `outbound`, `internal_note`, `ai_note` or `task` | | `type` | string | Channel message type, e.g. `text`, `image`, `audio`, `document` | | `content` | object \| array \| null | Structured payload for non-text messages, as delivered by the channel. Channel-defined shape — WhatsApp template messages carry an array of components. Do not assume a fixed shape | | `provider_message_id` | string \| null | Channel provider's own message id | | `attribution_id` | string \| null | Attribution identifier, when set | | `user` | object \| null | Human sender (`first_name`, `last_name`) when sent by an agent | | `assistant` | object \| null | AI sender (`id`, `name`) when sent by an assistant | | `campaign` | object \| null | `{ title }` when the message came from a campaign | | `ticket_id` | string \| null | Ticket this message belongs to, when there is one | > [!NOTE] > > v3 returns a **fixed projection**, so integrating once works for every > channel. v2 instead returns the raw channel row — on WhatsApp that means the > whole message record nested under `whatsapp_message` on top of the flattened > fields, plus the ticket, summary and activity graph. If you depend on a field > that only exists there, tell us and we will consider adding it to v3 rather > than exposing the internal row. > [!NOTE] > > Unlike v2, the response contains **only real messages**. The synthetic `stage` > and `interactive_note` entries that v2 mixes into its list are not messages > and are not returned here. ## Example Request ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contact/v3/df980fc8-b6db-4820-bf22-2969482d106d/messages?page=1&page_size=15' \ --header 'x-api-key: your_api_key_here' ``` ## Example Response ```json theme={null} { "data": [ { "id": "9f1c2b3a-5d6e-4f70-8a91-2b3c4d5e6f70", "created_at": "2024-09-30T10:01:30.000Z", "body": "¡Por supuesto! ¿Cuál es tu número de pedido?", "direction": "outbound", "type": "text", "content": null, "provider_message_id": "wamid.HBgLNTY5MTIzNDU2NzgVAgARGBI5QTND", "attribution_id": null, "user": null, "assistant": { "id": "123e4567-e89b-12d3-a456-426614174000", "name": "Vambe" }, "campaign": null, "ticket_id": "7c3e4f21-9b8a-4d5e-8f60-1a2b3c4d5e6f" }, { "id": "6b0d8e1f-2a34-4c56-9d78-0e1f2a3b4c56", "created_at": "2024-09-30T10:00:00.000Z", "body": "Hola, necesito ayuda con mi pedido", "direction": "inbound", "type": "text", "content": null, "provider_message_id": "wamid.HBgLNTY5ODc2NTQzMjEVAgASGBQzQjJE", "attribution_id": null, "user": null, "assistant": null, "campaign": null, "ticket_id": "7c3e4f21-9b8a-4d5e-8f60-1a2b3c4d5e6f" } ], "page": 1, "page_size": 15, "pages": 9, "total": 127, "has_next_page": true } ``` ## Fetching the Full History ```javascript theme={null} const getAllMessages = async (contactId, apiKey) => { const all = []; let page = 1; while (true) { const response = await fetch( `https://api.vambe.me/api/public/contact/v3/${contactId}/messages?page=${page}&page_size=100`, { headers: { 'x-api-key': apiKey } }, ); const result = await response.json(); all.push(...result.data); if (!result.has_next_page) { return all; // all.length === result.total } page += 1; } }; ``` Requesting a page past the last one is not an error: it returns an empty `data` with `has_next_page: false`. ## Error Responses | Status Code | Description | | - | - | | 400 | Invalid `page` or `page_size` | | 401 | Unauthorized — invalid or missing API key | | 404 | Contact not found for this API key's account | | 500 | Internal Server Error | ## Important Notes * **Order is newest first.** Page 1 holds the most recent messages. * **Reading is side-effect free.** Unlike v2, fetching messages here does **not** mark the conversation as read, so polling this endpoint never changes what your agents see as unread. * **Deleted Instagram messages are excluded** from `data`, `total` and `pages`. * **Cross-channel**: works for every channel a contact may use. ## Related Endpoints * [GET /api/public/contact/v2//messages](/reference/contact/get-messages-paginated) — legacy paginated history * [GET /api/public/contact//conversations](/reference/contact/get-conversations) — messages grouped into conversations * [GET /api/public/contact//info](/reference/contact/get-info-of-an-ai-contact) — contact info # Retrieve info by channel identifier Source: https://docs.vambe.me/reference/contact/retrieve-info-by-channel-identifier get /api/public/contact/whatsapp/{channelIdentifier}/info Replaces the old endpoint /public/ai-message/whatsapp/:channelIdentifier/info # Retrieve messages by AI contact Source: https://docs.vambe.me/reference/contact/retrieve-messages-by-ai-contact get /api/public/contact/{aiContactId}/messages Replaces the old endpoint /public/ai-message/:aiContactId # Retrieve messages by conversation Source: https://docs.vambe.me/reference/contact/retrieve-messages-by-conversation get /api/public/contact/whatsapp/{channelIdentifier}/messages Replaces the old endpoint /public/ai-message/whatsapp/:channelIdentifier # Search contacts by phone or email Source: https://docs.vambe.me/reference/contact/search-contacts get /api/public/contacts/search Find contacts by phone number or email address. Searches across all channels. At least one search parameter is required. ## Overview Search for contacts using their phone number or email address. This endpoint performs fuzzy matching across all communication channels, making it easy to find contacts even with partial information. Perfect for implementing search functionality, verifying contact existence, or looking up customer information before taking action. ## Use Cases * **Contact Lookup**: Find a contact before creating a ticket or sending a message * **Duplicate Detection**: Check if a contact already exists before importing * **Search Interface**: Power search bars in your CRM or dashboard * **Customer Verification**: Verify customer identity during support interactions * **Data Enrichment**: Find existing contact data to enrich external records * **Phone Validation**: Check if a phone number is already in your system ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Query Parameters **phone** `string` Phone number to search (partial match supported). Numbers are automatically sanitized. Examples: `"+56912345678"`, `"56912345678"`, `"12345678"` **email** `string` Email address to search (partial match supported, case-insensitive). Examples: `"john@example.com"`, `"@example.com"`, `"john"` **with\_utm\_events** `boolean` Set to `true` to include the per-contact `utm_events` array (marketing attribution). Off by default — the key is omitted entirely unless requested. > [!NOTE] > > **At least one parameter required**: You must provide either `phone` or > `email` (or both). ## Response Structure Returns an array of matching contact objects (maximum 50 results): | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier for the contact | | `name` | string | Contact's full name | | `phone` | string \| null | Contact's phone number | | `email` | string \| null | Contact's email address | | `platform` | string | Communication channel (whatsapp, instagram, etc.) | | `last_message_at` | string (ISO) | Timestamp of the last message sent/received | | `chat_status` | string | Current chat status (UNATTENDED, ATTENDED, etc.) | | `created_at` | string (ISO) | Contact creation timestamp | | `client_id` | string (UUID) | Your organization ID | | `ai_customer_id` | string (UUID) | Associated customer profile ID | | `default_stage_id` | string (UUID) | Current pipeline stage | | `blocked` | boolean | Whether the contact is blocked | | `is_chat_read` | boolean | Whether the chat has been read by an agent | | `utm_events` | array | Marketing attribution events for this contact (see below) | ### UTM Event Object (`utm_events[]`) Marketing attribution events recorded for the contact, ordered oldest first. Empty array when the contact has no attribution events. | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier for the UTM event | | `created_at` | string (ISO) \| null | When the attribution event was recorded | | `customer_id` | string (UUID) \| null | Associated customer profile ID | | `integration_type` | string \| null | Ad platform (facebook, google, tiktok, etc.) | | `ad_id` | string \| null | Ad identifier | | `referrer_url` | string \| null | Landing / referrer URL that captured the contact | | `search_keyword` | string \| null | Search keyword that triggered the ad | ## Example Requests ### Search by Phone Number ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contacts/search?phone=%2B56912345678' \ --header 'x-api-key: your_api_key_here' ``` ### Search by Email ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contacts/search?email=john%40example.com' \ --header 'x-api-key: your_api_key_here' ``` ### Search by Both ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contacts/search?phone=%2B56912345678&email=john%40example.com' \ --header 'x-api-key: your_api_key_here' ``` ### Search with UTM Events ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/public/contacts/search?phone=%2B56912345678&with_utm_events=true' \ --header 'x-api-key: your_api_key_here' ``` ## Example Response The response below assumes `with_utm_events=true` was passed — without it, the `utm_events` key is omitted from every contact entirely. ```json theme={null} [ { "id": "df980fc8-b6db-4820-bf22-2969482d106d", "name": "John Doe", "phone": "+56912345678", "email": "john.doe@example.com", "platform": "whatsapp", "last_message_at": "2024-09-30T14:25:33.000Z", "chat_status": "ATTENDED", "created_at": "2024-01-15T10:00:00.000Z", "client_id": "550e8400-e29b-41d4-a716-446655440000", "ai_customer_id": "660e8400-e29b-41d4-a716-446655440001", "default_stage_id": "770e8400-e29b-41d4-a716-446655440002", "blocked": false, "is_chat_read": true, "utm_events": [ { "id": "ee0e8400-e29b-41d4-a716-446655440009", "created_at": "2024-01-14T22:05:11.000Z", "customer_id": "660e8400-e29b-41d4-a716-446655440001", "integration_type": "facebook", "ad_id": "23854715623450123", "referrer_url": "https://example.com/landing?utm_campaign=spring", "search_keyword": null } ] } ] ``` ## Common Use Cases ### 1. Check if Contact Exists Before Creating ```javascript theme={null} const checkContactExists = async (phone) => { const response = await fetch( `https://api.vambe.me/api/public/contacts/search?phone=${encodeURIComponent(phone)}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); if (contacts.length > 0) { console.log('Contact already exists:', contacts[0]); return contacts[0]; } else { console.log('Contact not found - can create new'); return null; } }; ``` ### 2. Search Bar Implementation ```javascript theme={null} const searchContacts = async (searchTerm) => { // Detect if search term is email or phone const isEmail = searchTerm.includes('@'); const queryParam = isEmail ? `email=${encodeURIComponent(searchTerm)}` : `phone=${encodeURIComponent(searchTerm)}`; const response = await fetch( `https://api.vambe.me/api/public/contacts/search?${queryParam}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const results = await response.json(); console.log(`Found ${results.length} matching contacts`); return results; }; ``` ### 3. Verify Customer Before Action ```javascript theme={null} const verifyAndSendMessage = async (customerPhone) => { // First, search for the contact const searchResponse = await fetch( `https://api.vambe.me/api/public/contacts/search?phone=${encodeURIComponent(customerPhone)}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await searchResponse.json(); if (contacts.length === 0) { throw new Error('Contact not found. Please create contact first.'); } const contact = contacts[0]; // Verify not blocked if (contact.blocked) { throw new Error('Contact is blocked. Cannot send message.'); } console.log(`Found contact: ${contact.name} (${contact.id})`); // Now safe to send message or perform action return contact; }; ``` ### 4. Find All Contacts from Same Domain ```javascript theme={null} const findContactsByDomain = async (domain) => { const response = await fetch( `https://api.vambe.me/api/public/contacts/search?email=${encodeURIComponent(`@${domain}`)}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); console.log(`Found ${contacts.length} contacts from ${domain}`); return contacts; }; // Usage findContactsByDomain('example.com'); // Finds all @example.com contacts ``` ### 5. Deduplicate Before Import ```javascript theme={null} const importWithDedupe = async (customersToImport) => { const results = { created: 0, skipped: 0, updated: 0 }; for (const customer of customersToImport) { // Check if exists const searchResponse = await fetch( `https://api.vambe.me/api/public/contacts/search?phone=${encodeURIComponent(customer.phone)}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const existing = await searchResponse.json(); if (existing.length > 0) { console.log(`Skipping ${customer.phone} - already exists`); results.skipped++; } else { // Create new contact await createContact(customer); results.created++; } } console.log('Import results:', results); return results; }; ``` ### 6. Multi-criteria Search ```javascript theme={null} const searchByPhoneOrEmail = async (phone, email) => { const params = new URLSearchParams(); if (phone) params.append('phone', phone); if (email) params.append('email', email); const response = await fetch( `https://api.vambe.me/api/public/contacts/search?${params.toString()}`, { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const contacts = await response.json(); // Contacts matching either phone OR email console.log(`Found ${contacts.length} contacts`); return contacts; }; ``` ## Search Behavior ### Phone Number Matching * **Automatic Sanitization**: Non-numeric characters are removed (`+`, `-`, spaces, etc.) * **Partial Match**: Finds contacts where phone contains the search term * **Flexible Format**: Works with or without country code **Examples**: * Search `"12345678"` finds `"+56912345678"` * Search `"+569"` finds all numbers with that prefix * Search `"56912345"` finds `"+56912345678"` ### Email Matching * **Case Insensitive**: `"JOHN@EXAMPLE.COM"` matches `"john@example.com"` * **Partial Match**: Finds contacts where email contains the search term * **Domain Search**: Search `"@company.com"` finds all contacts from that domain **Examples**: * Search `"john@example.com"` finds exact match * Search `"@example.com"` finds all contacts from that domain * Search `"john"` finds `"john.doe@anywhere.com"`, `"johnny@test.com"`, etc. ### Combined Search When both `phone` and `email` are provided, returns contacts matching **either** criteria (OR logic): ``` phone="+56912345678" AND email="john@example.com" → Returns contacts with THAT phone OR THAT email ``` ## Result Limit * **Maximum 50 results**: The endpoint returns up to 50 matching contacts * **Ordered by recent activity**: Results sorted by `last_message_at` descending * **Refine search**: If you get 50 results, narrow your search criteria ## Error Responses | Status Code | Description | | - | - | | 400 | Bad Request - Neither phone nor email provided | | 401 | Unauthorized - Invalid or missing API key | | 500 | Internal Server Error - Something went wrong | ## Important Notes * **At Least One Required**: Must provide `phone`, `email`, or both * **Partial Matching**: Both phone and email support partial/fuzzy matching * **Cross-Channel**: Searches across ALL channels (WhatsApp, Instagram, SMS, etc.) * **Case Insensitive**: Email search is case-insensitive * **URL Encoding**: Remember to URL-encode parameters (especially `+` in phone numbers and `@` in emails) * **50 Result Limit**: Only first 50 matches returned ## URL Encoding When using phone numbers with `+` or emails with `@`, make sure to URL-encode: | Character | URL Encoded | Example | | - | - | - | | `+` | `%2B` | `+56912345678` → `%2B56912345678` | | `@` | `%40` | `john@example.com` → `john%40example.com` | | Space | `%20` | `john doe` → `john%20doe` | Most HTTP libraries handle this automatically with `encodeURIComponent()`. ## Related Endpoints * [GET /api/public/contact//info](/reference/contact/get-info-of-an-ai-contact) - Get detailed contact info by ID * [POST /api/public/customer/upsert/info](/reference/customer/upsert-customer-info) - Create or update contact * [GET /api/public/contacts?days=](/reference/contact/get-contacts-by-days) - Get contacts by activity ## Best Practices ### 1. Normalize Input Before Search ```javascript theme={null} const normalizePhone = (phone) => { return phone.replace(/[^\d+]/g, ''); }; const normalizeEmail = (email) => { return email.trim().toLowerCase(); }; const searchContact = async (phone, email) => { const params = new URLSearchParams(); if (phone) { params.append('phone', normalizePhone(phone)); } if (email) { params.append('email', normalizeEmail(email)); } return await fetch( `https://api.vambe.me/api/public/contacts/search?${params}`, { headers: { 'x-api-key': 'your_api_key_here' }, }, ).then((r) => r.json()); }; ``` ### 2. Handle Multiple Results ```javascript theme={null} const findExactMatch = async (phone, email) => { const results = await searchContact(phone, email); if (results.length === 0) { return null; } if (results.length === 1) { return results[0]; } // Multiple matches - find exact match const exactMatch = results.find( (c) => c.phone === phone && c.email === email, ); return exactMatch || results[0]; // Return exact or first result }; ``` ### 3. Search with Fallback ```javascript theme={null} const findContactWithFallback = async (phone, email) => { // Try phone first if (phone) { const byPhone = await fetch( `https://api.vambe.me/api/public/contacts/search?phone=${encodeURIComponent(phone)}`, { headers: { 'x-api-key': 'your_api_key_here' }, }, ).then((r) => r.json()); if (byPhone.length > 0) { console.log('Found by phone'); return byPhone[0]; } } // Fallback to email if (email) { const byEmail = await fetch( `https://api.vambe.me/api/public/contacts/search?email=${encodeURIComponent(email)}`, { headers: { 'x-api-key': 'your_api_key_here' }, }, ).then((r) => r.json()); if (byEmail.length > 0) { console.log('Found by email'); return byEmail[0]; } } console.log('Contact not found'); return null; }; ``` ## Performance Tips * **Be Specific**: More specific searches return faster results * **Exact Match**: Use full phone/email when possible * **Avoid Wildcards**: Searching `"@"` alone will match too many results * **Cache Results**: Cache frequent searches to reduce API calls ## Notes * **Fuzzy Matching**: Uses `ILIKE` for flexible matching * **No Wildcards Needed**: Partial matching built-in * **Ordered Results**: Most recent activity first * **All Channels**: Returns contacts from any platform # Update metadata to an AI contact Source: https://docs.vambe.me/reference/contact/update-contact-metadata post /api/public/contact/{aiContactId}/update-metadata ## Overview Update or add custom metadata fields to a contact. Metadata allows you to store any additional information about a contact beyond the standard fields (name, email, phone). This endpoint is intelligent - it processes unstructured data and automatically fills custom field definitions if they exist in your account. Field keys are automatically converted to snake\_case for consistency. ## Use Cases * **E-commerce Data**: Store order history, lifetime value, preferred products * **Customer Segmentation**: Add custom attributes for targeting and personalization * **CRM Integration**: Sync custom fields from external CRM systems * **Lead Scoring**: Store qualification scores, lead source, conversion probability * **Business Context**: Add company info, industry, decision maker status * **Behavioral Data**: Track user actions, preferences, interaction history * **Support Information**: Store account tier, support plan, SLA requirements ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `aiContactId` | string (UUID) | Yes | Unique identifier of the contact | ## Request Body The request body is a flexible object where you can include any key-value pairs: | Field | Type | Required | Description | | - | - | - | - | | `{any}` | any | No | Any custom field as key-value pair | You can send any metadata fields as a JSON object. Common examples: ```json theme={null} { "company": "Acme Corp", "industry": "Technology", "employeeCount": "500-1000", "annualRevenue": "5000000", "leadScore": "85", "source": "website", "interests": "AI, Automation", "custom_field_1": "value1" } ``` ## Response Structure The endpoint returns an array of updated custom field values: | Field | Type | Description | | - | - | - | | Array | array | Array of custom field value objects that were updated | Each item in the response array contains information about the updated field. ## Example Request ```bash theme={null} curl --request POST \ 'https://api.vambe.me/api/public/contact/1937bd2c-a13c-4365-af06-43af9a988e36/update-metadata' \ --header 'Content-Type: application/json' \ --header 'x-api-key: your_api_key_here' \ --data-raw '{ "company": "Acme Corporation", "position": "CEO", "industry": "Technology", "employeeCount": "100-500", "annualRevenue": "2000000", "leadScore": 95, "leadSource": "LinkedIn Campaign", "interestedProducts": "Enterprise Plan, API Access", "notes": "Very interested in automation features", "budget": "50000-100000", "decisionMaker": true, "expectedCloseDate": "2024-12-31" }' ``` ## Example Response ```json theme={null} [ { "id": 123, "key": "company", "value": "Acme Corporation", "custom_field_definition_id": 45 }, { "id": 124, "key": "position", "value": "CEO", "custom_field_definition_id": 46 }, { "id": 125, "key": "lead_score", "value": "95", "custom_field_definition_id": 47 } ] ``` ## Common Use Cases ### 1. Update E-commerce Customer Data ```javascript theme={null} const updateEcommerceData = async (contactId, orderData) => { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ totalOrders: orderData.orderCount.toString(), lifetimeValue: orderData.totalSpent.toString(), averageOrderValue: orderData.averageValue.toString(), lastPurchaseDate: orderData.lastPurchase, favoriteCategory: orderData.topCategory, customerSince: orderData.firstOrderDate, vipStatus: orderData.isVIP ? 'Yes' : 'No', }), }, ); const result = await response.json(); console.log(`Updated ${result.length} metadata fields`); return result; }; ``` ### 2. Lead Qualification Data ```javascript theme={null} const updateLeadQualification = async (contactId, qualificationData) => { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ leadScore: qualificationData.score, leadGrade: qualificationData.grade, // A, B, C, D qualificationDate: new Date().toISOString(), budgetRange: qualificationData.budget, timeframe: qualificationData.timeframe, // Immediate, 1-3 months, 3-6 months authority: qualificationData.isDecisionMaker ? 'Decision Maker' : 'Influencer', need: qualificationData.painPoints, source: qualificationData.leadSource, }), }, ); return await response.json(); }; ``` ### 3. Sync from External CRM ```javascript theme={null} const syncFromExternalCRM = async (contactId, crmData) => { // Map CRM fields to Vambe metadata const metadata = { crmContactId: crmData.id, accountType: crmData.account_type, industry: crmData.industry, companySize: crmData.employee_count, annualRevenue: crmData.revenue, territory: crmData.sales_territory, accountOwner: crmData.owner_name, lastActivityDate: crmData.last_activity, stage: crmData.sales_stage, probability: crmData.win_probability, }; const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify(metadata), }, ); return await response.json(); }; ``` ### 4. Add Support Plan Information ```javascript theme={null} const updateSupportPlan = async (contactId, planDetails) => { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ supportPlan: planDetails.tier, // Basic, Premium, Enterprise planStartDate: planDetails.startDate, planExpiryDate: planDetails.expiryDate, slaLevel: planDetails.sla, // 24h, 12h, 4h dedicatedManager: planDetails.hasManager ? 'Yes' : 'No', maxTicketsPerMonth: planDetails.ticketLimit.toString(), supportChannels: planDetails.channels.join(', '), // Email, Phone, Chat }), }, ); return await response.json(); }; ``` ### 5. Update Form Submission Data ```javascript theme={null} const saveFormSubmission = async (contactId, formData) => { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ formName: formData.formType, submissionDate: new Date().toISOString(), utmSource: formData.utm_source, utmMedium: formData.utm_medium, utmCampaign: formData.utm_campaign, referrer: formData.referrer, landingPage: formData.landingPage, message: formData.userMessage, }), }, ); return await response.json(); }; ``` ### 6. Bulk Update Multiple Contacts ```javascript theme={null} const bulkUpdateMetadata = async (contactIds, metadata) => { const results = []; for (const contactId of contactIds) { try { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify(metadata), }, ); const result = await response.json(); results.push({ contactId, success: true, fieldsUpdated: result.length }); } catch (error) { results.push({ contactId, success: false, error: error.message }); } // Add small delay to avoid rate limiting await new Promise((resolve) => setTimeout(resolve, 100)); } return results; }; // Usage: Apply same metadata to multiple contacts bulkUpdateMetadata(['contact-id-1', 'contact-id-2'], { campaignParticipant: 'Summer Sale 2024', enrolled: new Date().toISOString(), }); ``` ## Key Behavior & Features ### Automatic Snake Case Conversion Field keys are automatically converted to snake\_case: **You send**: `{ "companyName": "Acme Corp" }` **Stored as**: `{ "company_name": "Acme Corp" }` **You send**: `{ "LeadScore": "95" }` **Stored as**: `{ "lead_score": "95" }` ### Intelligent Field Processing The endpoint uses AI to process unstructured data and match it to your custom field definitions: * If a custom field definition exists for a key, it will be used * Data types are automatically formatted based on field definitions * Missing fields are created as needed * All fields are updated (not merged) ### Update Behavior * **Additive**: New metadata fields are added to existing ones * **Overwrite**: If a field already exists, its value is updated * **Flexible Types**: Values can be strings, numbers, booleans, or objects (converted to strings) * **No Validation**: You can send any fields - they don't need to be pre-defined ## Data Type Handling Metadata values should generally be sent as strings for consistency: | Data Type You Send | How It's Stored | Example | | - | - | - | | String | As is | `"Acme Corp"` | | Number | Converted to string | `95` → `"95"` | | Boolean | Converted to string | `true` → `"true"` | | Object | JSON string | Converted to JSON | | Array | Joined string | `["a","b"]` → `"a, b"` | **Best Practice**: Send everything as strings for predictable behavior. ## Error Responses | Status Code | Description | | - | - | | 400 | Bad Request - Invalid metadata format | | 401 | Unauthorized - Invalid or missing API key | | 404 | Not Found - Contact not found | | 500 | Internal Server Error - Something went wrong | ## Important Notes * **No Field Limit**: You can send as many metadata fields as needed * **Size Limit**: Very large metadata objects may be rejected (keep under 1MB) * **Field Names**: Use descriptive, consistent naming (prefer snake\_case or camelCase) * **Retrieve Metadata**: Use GET `/api/public/contact/{aiContactId}/info` to see all metadata * **Type Coercion**: All values are ultimately stored as strings in custom fields * **Activity Logging**: Metadata updates are logged in contact activity ## Best Practices ### 1. Use Consistent Field Names ```javascript theme={null} // Good: Consistent naming convention const goodMetadata = { leadSource: 'Website', leadScore: '85', companyName: 'Acme Corp', isQualified: 'true', }; // Avoid: Inconsistent naming const badMetadata = { 'Lead Source': 'Website', // Has spaces LeadScore: '85', // Mixed case company_name: 'Acme Corp', // Different convention qualified: 'true', // Missing is prefix }; ``` ### 2. Include Timestamps ```javascript theme={null} const metadataWithTimestamps = { lastUpdated: new Date().toISOString(), dataSource: 'API Import', importBatch: 'batch-2024-09-30', // ... other fields }; ``` ### 3. Validate Before Sending ```javascript theme={null} const validateAndUpdateMetadata = (contactId, metadata) => { // Remove null/undefined values const cleanMetadata = Object.entries(metadata).reduce((acc, [key, value]) => { if (value !== null && value !== undefined && value !== '') { acc[key] = String(value); // Ensure all values are strings } return acc; }, {}); return fetch( `https://api.vambe.me/api/public/contact/${contactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify(cleanMetadata), }, ); }; ``` ### 4. Handle Errors Gracefully ```javascript theme={null} const safeUpdateMetadata = async (contactId, metadata) => { try { const response = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify(metadata), }, ); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${await response.text()}`); } return await response.json(); } catch (error) { console.error('Failed to update metadata:', error); // Maybe retry or log to error tracking throw error; } }; ``` ## Related Endpoints * [GET /api/public/contact//info](/reference/contact/get-info-of-an-ai-contact) - Get contact info including metadata * [POST /api/public/ticket/open/web-whatsapp/](/reference/ticket/open-ticket-web-whatsapp) - Create ticket with metadata * [PATCH /api/public/contact/tags/](/reference/tags/update-contact-tags) - Update contact tags ## Complete Workflow Example ```javascript theme={null} // Complete workflow: Create ticket with metadata, then update it const createAndEnrichContact = async (phoneNumber, initialData) => { // 1. Create ticket/contact const createResponse = await fetch( 'https://api.vambe.me/api/public/ticket/open/web-whatsapp/your_phone_id', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ to_phone_number: phoneNumber, stage_id: 'your_stage_id', contact_name: initialData.name, contact_metadata: { source: initialData.source, }, }), }, ); const { aiContactId } = await createResponse.json(); // 2. Enrich with additional metadata after qualification const enrichResponse = await fetch( `https://api.vambe.me/api/public/contact/${aiContactId}/update-metadata`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ company: initialData.company, industry: initialData.industry, employeeCount: initialData.size, leadScore: calculateLeadScore(initialData), enrichedAt: new Date().toISOString(), dataQuality: 'High', }), }, ); const metadata = await enrichResponse.json(); console.log(`Created and enriched contact ${aiContactId}`); console.log(`Updated ${metadata.length} metadata fields`); return { aiContactId, metadata }; }; ``` ## Metadata vs Tags | Feature | Metadata (This Endpoint) | Tags | | - | - | - | | **Purpose** | Store detailed data | Categorize/label contacts | | **Format** | Key-value pairs | Simple labels | | **Quantity** | Unlimited fields | Multiple tags | | **Search** | By field name and value | By tag name | | **Use Case** | Customer details, scores, history | Segments, categories, flags | Use **metadata** for detailed information and **tags** for simple categorization. # List capability checks Source: https://docs.vambe.me/reference/custom-ecommerce-apps-management/list-capability-checks get /api/ecommerce-app/{id}/checks Status of every readiness check (OAuth, outbound capabilities, inbound webhooks) used to gate submission. # Test an outbound capability Source: https://docs.vambe.me/reference/custom-ecommerce-apps-management/test-an-outbound-capability post /api/ecommerce-app/{id}/checks/capability/{capability} Calls the provider URL for the capability with the OAuth token of the connected test store and records the result. # Upsert a contact Source: https://docs.vambe.me/reference/customer/upsert-customer-info post /api/public/customer/upsert/info Creates or finds an existing contact for whatsapp, web-whatsapp, or webchat channels. For whatsapp/web-whatsapp, the contact is identified by phone number. For webchat, the contact is identified by external_user_id. Optionally assigns an agent, updates metadata, sets a stage, and upserts custom field values on the associated customer. ## Overview Create or update a customer contact with intelligent AI-powered data processing. This endpoint automatically creates the contact if it doesn't exist, or updates it if it does, along with optional metadata, custom field values, stage assignment, and agent assignment - all in a single request. Supports **WhatsApp**, **Web-WhatsApp**, and **Webchat** channels. For WhatsApp-based channels the contact is identified by phone number; for webchat, the contact is identified by an external user ID you provide. ## Use Cases * **CRM Data Import**: Bulk import customer data from external CRM systems * **Form Submissions**: Create customers from web form submissions with flexible data * **E-commerce Integration**: Sync customer data from your e-commerce platform * **Lead Capture**: Capture leads with any structure of data * **Customer Onboarding**: Create customer profiles during signup flows * **Data Migration**: Migrate customer data from legacy systems * **Webchat User Tracking**: Create contacts for authenticated webchat users with your own external IDs ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Request Body ### Common Fields | Field | Type | Required | Description | | - | - | - | - | | `channel` | string | Yes | Channel type: `"whatsapp"`, `"web-whatsapp"`, or `"webchat"` | | `contact_name` | string | No | Customer's display name | | `contact_email` | string | No | Customer's email address | | `stageId` | string | No | Pipeline stage UUID to assign the customer to | | `agentId` | string | No | Team member UUID to assign as responsible agent | | `meta_data` | object | No | Any additional customer data (AI will structure it) | | `custom_field_values` | array | No | Custom field values to set on the customer (see below) | ### WhatsApp / Web-WhatsApp Fields Required when `channel` is `"whatsapp"` or `"web-whatsapp"`: | Field | Type | Required | Description | | - | - | - | - | | `channel_phone_number` | string | Yes | Your WhatsApp channel phone number (the sender) | | `contact_phone_number` | string | Yes | Customer's phone number | ### Webchat Fields Required when `channel` is `"webchat"`: | Field | Type | Required | Description | | - | - | - | - | | `channel_id` | string | Yes | UUID of your webchat channel | | `external_user_id` | string | Yes | Your unique identifier for the user (used to find or create the contact) | ### Custom Field Values The `custom_field_values` array lets you set values on the associated customer using custom field definition keys. Each entry has: | Field | Type | Required | Description | | - | - | - | - | | `key` | string | Yes | The custom field definition key | | `value` | string | Yes | The value to set | If a custom field definition is marked as an **identifier**, the value will participate in customer deduplication automatically. ```json theme={null} "custom_field_values": [ { "key": "rut", "value": "12345678-9" }, { "key": "company_name", "value": "Acme Corp" } ] ``` ## Response Structure Returns the created or updated AI contact object: | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier for the contact | | `name` | string | Contact's name | | `phone` | string | Contact's phone number | | `email` | string | Contact's email | | `platform` | string | Channel platform (whatsapp, web-whatsapp, webchat) | | `client_id` | string (UUID) | Your organization ID | | `ai_customer_id` | string (UUID) | Associated customer profile ID | | `created_at` | string (ISO) | Contact creation timestamp | | `default_stage_id` | string (UUID) | Current pipeline stage (if assigned) | ## Example Requests ### WhatsApp Contact ```bash theme={null} curl --request POST \ 'https://api.vambe.me/api/public/customer/upsert/info' \ --header 'Content-Type: application/json' \ --header 'x-api-key: your_api_key_here' \ --data-raw '{ "channel_phone_number": "+56987654321", "channel": "whatsapp", "contact_phone_number": "+56912345678", "contact_name": "Maria Rodriguez", "contact_email": "maria.rodriguez@example.com", "stageId": "550e8400-e29b-41d4-a716-446655440000", "agentId": "228d7a0d-9072-4ca8-939b-959b75cc606a", "meta_data": { "company": "Acme Corp", "position": "CEO", "industry": "Technology", "source": "LinkedIn Campaign" }, "custom_field_values": [ { "key": "company_name", "value": "Acme Corp" }, { "key": "rut", "value": "12345678-9" } ] }' ``` ### Webchat Contact ```bash theme={null} curl --request POST \ 'https://api.vambe.me/api/public/customer/upsert/info' \ --header 'Content-Type: application/json' \ --header 'x-api-key: your_api_key_here' \ --data-raw '{ "channel": "webchat", "channel_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "external_user_id": "user-abc-123", "contact_name": "Jane Doe", "contact_email": "jane@example.com", "custom_field_values": [ { "key": "plan", "value": "premium" }, { "key": "account_id", "value": "ACC-9876" } ] }' ``` ## Example Response ```json theme={null} { "id": "df980fc8-b6db-4820-bf22-2969482d106d", "name": "Maria Rodriguez", "phone": "+56912345678", "email": "maria.rodriguez@example.com", "platform": "whatsapp", "client_id": "550e8400-e29b-41d4-a716-446655440000", "ai_customer_id": "660e8400-e29b-41d4-a716-446655440001", "created_at": "2024-09-30T10:00:00.000Z", "default_stage_id": "550e8400-e29b-41d4-a716-446655440000", "blocked": false, "chat_status": "UNATTENDED", "is_chat_read": false } ``` ## Common Use Cases ### 1. Import CRM Data with Custom Fields ```javascript theme={null} const importCRMCustomer = async (crmData) => { const response = await fetch( 'https://api.vambe.me/api/public/customer/upsert/info', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ channel_phone_number: '+56987654321', channel: 'whatsapp', contact_name: crmData.full_name, contact_phone_number: crmData.phone, contact_email: crmData.email, stageId: 'your_initial_stage_id', custom_field_values: [ { key: 'company_name', value: crmData.company_name }, { key: 'industry', value: crmData.industry_sector }, { key: 'lead_score', value: String(crmData.qualification_score) }, ], meta_data: { source: crmData.lead_source, notes: crmData.internal_notes, }, }), }, ); const contact = await response.json(); console.log(`Imported customer: ${contact.name} (${contact.id})`); return contact; }; ``` ### 2. Create Webchat Contact from Authenticated User ```javascript theme={null} const createWebchatContact = async (authenticatedUser) => { const response = await fetch( 'https://api.vambe.me/api/public/customer/upsert/info', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ channel: 'webchat', channel_id: 'your_webchat_channel_uuid', external_user_id: authenticatedUser.id, contact_name: authenticatedUser.displayName, contact_email: authenticatedUser.email, custom_field_values: [ { key: 'plan', value: authenticatedUser.plan }, { key: 'account_id', value: authenticatedUser.accountId }, ], }), }, ); return await response.json(); }; ``` ### 3. Process Form Submission ```javascript theme={null} const processContactForm = async (formData) => { const response = await fetch( 'https://api.vambe.me/api/public/customer/upsert/info', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ channel_phone_number: process.env.WHATSAPP_PHONE, channel: 'whatsapp', contact_name: formData.name, contact_phone_number: formData.phone, contact_email: formData.email, stageId: 'your_leads_stage_id', agentId: formData.assignToAgent || null, meta_data: { formType: 'Contact Form', submittedAt: new Date().toISOString(), subject: formData.subject, message: formData.message, source: formData.utm_source, campaign: formData.utm_campaign, }, }), }, ); return await response.json(); }; ``` ### 4. E-commerce Customer Sync ```javascript theme={null} const syncEcommerceCustomer = async (order) => { const response = await fetch( 'https://api.vambe.me/api/public/customer/upsert/info', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ channel_phone_number: '+56987654321', channel: 'whatsapp', contact_name: `${order.customer.first_name} ${order.customer.last_name}`, contact_phone_number: order.customer.phone, contact_email: order.customer.email, stageId: 'your_customers_stage_id', meta_data: { orderId: order.id, orderNumber: order.order_number, orderTotal: order.total_price, currency: order.currency, products: order.line_items.map((item) => item.title).join(', '), }, }), }, ); return await response.json(); }; ``` ### 5. Bulk Customer Import ```javascript theme={null} const bulkImportCustomers = async (customers) => { const results = []; for (const customer of customers) { try { const response = await fetch( 'https://api.vambe.me/api/public/customer/upsert/info', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ channel_phone_number: process.env.WHATSAPP_PHONE, channel: 'whatsapp', contact_name: customer.name, contact_phone_number: customer.phone, contact_email: customer.email, custom_field_values: customer.customFields || [], meta_data: customer.additionalData, }), }, ); const result = await response.json(); results.push({ phone: customer.phone, success: true, id: result.id }); } catch (error) { results.push({ phone: customer.phone, success: false, error: error.message, }); } // Add delay to avoid rate limiting await new Promise((resolve) => setTimeout(resolve, 200)); } console.log( `Imported ${results.filter((r) => r.success).length} of ${customers.length} customers`, ); return results; }; ``` ## Key Features ### Upsert Behavior The contact lookup depends on the channel: | Channel | Identified by | | - | - | | `whatsapp` | `contact_phone_number` on the given channel | | `web-whatsapp` | `contact_phone_number` on the given channel | | `webchat` | `external_user_id` on the given `channel_id` | * **If contact exists**: Returns the existing contact and applies any updates (name, agent, stage, metadata, custom fields) * **If contact doesn't exist**: Creates a new contact and customer * **Idempotent**: Safe to call multiple times with the same data ### Custom Field Values * Values are set on the **customer** (not the contact), so they are shared across all contacts for that customer * Fields are identified by their definition **key** (e.g. `"rut"`, `"company_name"`) * If a field definition is marked as an **identifier**, the value participates in automatic customer deduplication * All custom field definition keys must exist beforehand; the endpoint returns a `400` error listing any missing keys * Supported field types: `text`, `number`, `date`, `boolean`, `options` ### AI-Powered Data Processing The `meta_data` field uses AI to: * **Extract structured data** from unstructured metadata * **Match fields** to your custom field definitions * **Convert data types** automatically * **Handle flexible formats** for phone numbers, dates, etc. ### Automatic Processing All in one request: 1. Create/update contact 2. Assign to pipeline stage 3. Assign to agent 4. Process and save metadata 5. Upsert custom field values ## Channel Types | Channel | Description | Required Fields | | - | - | - | | `whatsapp` | WhatsApp Business API | `channel_phone_number`, `contact_phone_number` | | `web-whatsapp` | WhatsApp Web (QR Code) | `channel_phone_number`, `contact_phone_number` | | `webchat` | Webchat widget | `channel_id`, `external_user_id` | ## Error Responses | Status Code | Description | | - | - | | 400 | Bad Request - Missing required fields for the channel, or invalid custom field keys | | 401 | Unauthorized - Invalid or missing API key | | 500 | Internal Server Error - Something went wrong | ## Important Notes * **Channel Phone Number**: Must be a WhatsApp number/channel you own and have configured * **Channel ID**: Must be a webchat channel UUID you own * **External User ID**: Your own unique identifier for the webchat user; used to deduplicate contacts * **Phone Format**: Automatically cleaned (spaces, dashes, etc. are removed) * **Custom Field Keys**: Must match existing custom field definitions; create definitions first in the Vambe dashboard * **AI Processing**: Metadata is processed asynchronously with AI * **Immediate Response**: Returns contact immediately, metadata processing continues in background ## Best Practices ### 1. Use Custom Fields for Structured Data Prefer `custom_field_values` over `meta_data` when you have well-defined fields. Custom fields are typed, searchable, and can be marked as identifiers for deduplication. ```javascript theme={null} // Preferred: structured custom fields { "custom_field_values": [ { "key": "company_name", "value": "Acme Corp" }, { "key": "rut", "value": "12345678-9" }, { "key": "plan", "value": "enterprise" } ] } // Use meta_data for unstructured/dynamic data { "meta_data": { "notes": "Met at conference, interested in premium plan", "source": "Trade Show 2025" } } ``` ### 2. Include Source Information ```javascript theme={null} meta_data: { source: 'LinkedIn Campaign', importedAt: new Date().toISOString(), importedBy: 'CRM Sync Script', } ``` ### 3. Validate Data Before Sending ```javascript theme={null} const validateAndUpsert = async (customerData) => { if (!customerData.phone || !customerData.name) { throw new Error('Phone and name are required'); } const cleanPhone = customerData.phone.replace(/[^\d+]/g, ''); return await fetch('https://api.vambe.me/api/public/customer/upsert/info', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ channel_phone_number: process.env.WHATSAPP_PHONE, channel: 'whatsapp', contact_phone_number: cleanPhone, contact_name: customerData.name, contact_email: customerData.email, custom_field_values: customerData.customFields || [], meta_data: customerData.additionalData, }), }).then((r) => r.json()); }; ``` ## Related Endpoints * [POST /api/public/contact//update-metadata](/reference/contact/update-contact-metadata) - Update metadata for existing contact * [POST /api/public/ticket/open/web-whatsapp/](/reference/ticket/open-ticket-web-whatsapp) - Create ticket for contact * [GET /api/public/contact//info](/reference/contact/get-info-of-an-ai-contact) - Get contact details ## Migration from Deprecated Endpoint If you're migrating from the deprecated `POST /api/public/whatsapp/message/note/send` endpoint: **Old**: ```javascript theme={null} POST /api/public/whatsapp/message/note/send { "to_phone": "+56912345678", "from_phone": "your_phone", "note": "Internal note", "contact_name": "John Doe", "meta_data": { ... } } ``` **New** (This endpoint): ```javascript theme={null} POST /api/public/customer/upsert/info { "channel_phone_number": "your_phone", "channel": "whatsapp", "contact_phone_number": "+56912345678", "contact_name": "John Doe", "meta_data": { "internal_note": "Internal note", ... } } ``` The new endpoint provides better structure and automatic AI processing of all metadata! # Create an email channel Source: https://docs.vambe.me/reference/email-channel/create-an-email-channel post /api/public/email-channel Registers a sender on a domain and starts SendGrid domain authentication. After creation, fetch the DNS records and add them to your DNS provider, then call /verify. # Delete an email channel Source: https://docs.vambe.me/reference/email-channel/delete-an-email-channel delete /api/public/email-channel/{id} Soft-deletes the channel and removes the verified sender from SendGrid. If no other channel uses the domain, the domain authentication is also removed. # Get a single email channel Source: https://docs.vambe.me/reference/email-channel/get-a-single-email-channel get /api/public/email-channel/{id} Includes domain validation status and DNS records. # Get DNS records for a channel Source: https://docs.vambe.me/reference/email-channel/get-dns-records-for-a-channel get /api/public/email-channel/dns-records/{id} Returns the CNAME / TXT / MX records that must be added to your DNS provider to validate the domain. # List email channels Source: https://docs.vambe.me/reference/email-channel/list-email-channels get /api/public/email-channel # Verify domain DNS Source: https://docs.vambe.me/reference/email-channel/verify-domain-dns post /api/public/email-channel/verify/{id} Asks SendGrid to re-check the DNS records for this channel's domain and, if inbound parse has been configured, also checks the MX. Returns the channel with the updated outbound_validation_status and inbound_validation_status. # Send an email Source: https://docs.vambe.me/reference/email/send-an-email post /api/public/email/send Sends an email to one or more contacts identified by their email address ("to" accepts a single email or an array of up to 20), from one of the account verified email channels. Use a saved template ("template_id" or "template_name", plus "variables") or free-form content ("subject" and "html_body"). If no contact exists for a recipient address, one is created. When the account has more than one verified channel, "from" is required to pick the sender address. Single-recipient sends also accept "cc" and "bcc" (up to 10 each): one message is sent where cc recipients are visible to everyone. Multi-recipient "to" arrays instead send an individual private copy per recipient. The response contains a per-recipient result list; "success" is true only when every recipient succeeded. # Ingest a custom event Source: https://docs.vambe.me/reference/events-api/ingest-a-customer-event post /api/v1/events Accepts a customer event (e.g. "purchase", "new_account_created") and stores it for downstream processing. The event is associated with a contact (resolved via `aiContactId` or `phone`) on a specific channel (resolved via `channelId` or `channelPhone`); a contact is created when none matches. The event is persisted synchronously and the response carries its id; enrichment and automations run in the background. Rate limited to 1000 requests per hour per client. # Create a comment automation Source: https://docs.vambe.me/reference/instagram-comment-automations/create-a-comment-automation post /api/public/instagram/accounts/{instagramAccountId}/automations Pass postId (an Instagram media id) to scope the automation to a single post, or omit it for a global automation that applies to every post. # Delete a comment automation Source: https://docs.vambe.me/reference/instagram-comment-automations/delete-a-comment-automation delete /api/public/instagram/automations/{id} # Get a comment automation by id Source: https://docs.vambe.me/reference/instagram-comment-automations/get-a-comment-automation-by-id get /api/public/instagram/automations/{id} # List comment automations Source: https://docs.vambe.me/reference/instagram-comment-automations/list-comment-automations get /api/public/instagram/accounts/{instagramAccountId}/automations Without postId, returns a paginated list of all automations for the account. With postId (an Instagram media id), returns the automations that apply to that post as { postSpecific, global }. # List connected Instagram accounts Source: https://docs.vambe.me/reference/instagram-comment-automations/list-connected-instagram-accounts get /api/public/instagram/accounts Returns the Instagram accounts connected to your workspace. Use an account id as :instagramAccountId in the other endpoints. # List execution history for a post Source: https://docs.vambe.me/reference/instagram-comment-automations/list-execution-history-for-a-post get /api/public/instagram/accounts/{instagramAccountId}/posts/{postId}/history Returns the log of comments that triggered automations on this post and the actions taken (public reply / DM / delete). # List pipeline stages Source: https://docs.vambe.me/reference/instagram-comment-automations/list-pipeline-stages get /api/public/instagram/stages Stages can be referenced via stageId when creating an automation to move the commenter into a CRM stage. Optional. # List posts of an Instagram account Source: https://docs.vambe.me/reference/instagram-comment-automations/list-posts-of-an-instagram-account get /api/public/instagram/accounts/{instagramAccountId}/posts # Update a comment automation Source: https://docs.vambe.me/reference/instagram-comment-automations/update-a-comment-automation put /api/public/instagram/automations/{id} # Create a new folder Source: https://docs.vambe.me/reference/knowledge-base/create-folder post /api/documents/assistant/folders Create a new knowledge base folder to organize documents. ## Overview Create a new knowledge base folder to organize your documents. Folders help structure your AI assistant's knowledge, making it easier to manage, update, and maintain your content. Folders can be nested to create hierarchical organizations that match your business structure. ## Use Cases * **Organize by Topic**: Create folders for different product lines, services, or topics * **Department Structure**: Organize knowledge by department (Sales, Support, HR) * **Content Type**: Separate FAQs, policies, guides, and procedures * **Nested Organization**: Create parent folders with subfolders for detailed organization * **Team Collaboration**: Structure shared knowledge bases for team access * **Version Control**: Maintain different versions in separate folders ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `name` | string | Yes | Folder name (must be unique per client) | | `icon` | string | No | Emoji/icon for the folder | | `sort_order` | number | No | Display order (default: 0) | | `parent_folder_id` | string (UUID) | No | Parent folder ID for nested folders | > [!NOTE] > > **Unique Names**: Folder names must be unique within your organization. ## Response Structure Returns the created folder object: | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique folder identifier | | `name` | string | Folder name | | `icon` | string \| null | Folder icon/emoji | | `sort_order` | number | Display order | | `client_id` | string (UUID) | Your organization ID | | `parent_folder_id` | string \| null | Parent folder ID (null for root folders) | | `created_at` | string (ISO) | Creation timestamp | | `updated_at` | string (ISO) | Last update timestamp | ## Example Requests ### Create Root Folder ```bash theme={null} curl --request POST \ 'https://api.vambe.me/api/documents/assistant/folders' \ --header 'Content-Type: application/json' \ --header 'x-api-key: your_api_key_here' \ --data-raw '{ "name": "Product Documentation", "icon": "📚", "sort_order": 0 }' ``` ### Create Nested Folder ```bash theme={null} curl --request POST \ 'https://api.vambe.me/api/documents/assistant/folders' \ --header 'Content-Type: application/json' \ --header 'x-api-key: your_api_key_here' \ --data-raw '{ "name": "Advanced Features", "icon": "🚀", "parent_folder_id": "550e8400-e29b-41d4-a716-446655440000" }' ``` ## Example Response ```json theme={null} { "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Product Documentation", "icon": "📚", "sort_order": 0, "client_id": "660e8400-e29b-41d4-a716-446655440001", "parent_folder_id": null, "source_url": null, "source_type": null, "is_public": false, "created_at": "2024-09-30T10:00:00.000Z", "updated_at": "2024-09-30T10:00:00.000Z" } ``` ## Common Use Cases ### 1. Create Folder Structure ```javascript theme={null} const createFolderStructure = async () => { // Create main folder const mainFolder = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ name: 'Support Documentation', icon: '📖', }), }, ).then((r) => r.json()); // Create subfolders const subfolder1 = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ name: 'FAQs', icon: '❓', parent_folder_id: mainFolder.id, }), }, ).then((r) => r.json()); const subfolder2 = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ name: 'Troubleshooting', icon: '🔧', parent_folder_id: mainFolder.id, }), }, ).then((r) => r.json()); console.log('Created folder structure:'); console.log(`- ${mainFolder.name}`); console.log(` - ${subfolder1.name}`); console.log(` - ${subfolder2.name}`); return { mainFolder, subfolders: [subfolder1, subfolder2] }; }; ``` ### 2. Create Folder with Sort Order ```javascript theme={null} const createOrderedFolders = async () => { const folderData = [ { name: 'Getting Started', icon: '🚀', sort_order: 1 }, { name: 'Advanced Topics', icon: '🎓', sort_order: 2 }, { name: 'API Reference', icon: '📚', sort_order: 3 }, ]; const createdFolders = []; for (const data of folderData) { const folder = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify(data), }, ).then((r) => r.json()); createdFolders.push(folder); console.log(`Created: ${folder.name} (order: ${folder.sort_order})`); } return createdFolders; }; ``` ### 3. Create and Use Folder Immediately ```javascript theme={null} const createFolderAndAddDocument = async (folderName, documentData) => { // 1. Create folder const folder = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ name: folderName, icon: '📁', }), }, ).then((r) => r.json()); console.log(`Created folder: ${folder.name} (${folder.id})`); // 2. Upload document to the new folder const document = await fetch( 'https://api.vambe.me/api/documents/assistant/raw', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ content: documentData.content, fileName: documentData.fileName, externalId: documentData.externalId, folderId: folder.id, // Use newly created folder icon: '📄', }), }, ).then((r) => r.json()); console.log(`Added document: ${documentData.fileName}`); return { folder, document }; }; ``` ## Sort Order The `sort_order` field determines display order: * Lower numbers appear first * Default is 0 if not specified * Can be negative for priority items * Used for consistent UI ordering Example: ```javascript theme={null} { name: 'Important', sort_order: -1 } // Shows first { name: 'Main Docs', sort_order: 0 } // Default position { name: 'Archive', sort_order: 10 } // Shows last ``` ## Nested Folders Create folder hierarchies by setting `parent_folder_id`: ```javascript theme={null} // Level 1 const level1 = await createFolder({ name: 'Documentation', icon: '📚' }); // Level 2 const level2 = await createFolder({ name: 'User Guides', icon: '📖', parent_folder_id: level1.id, }); // Level 3 const level3 = await createFolder({ name: 'Getting Started', icon: '🚀', parent_folder_id: level2.id, }); ``` Result: `Documentation > User Guides > Getting Started` ## Error Responses | Status Code | Description | | - | - | | 400 | Bad Request - Invalid data or duplicate name | | 401 | Unauthorized - Invalid or missing API key | | 500 | Internal Server Error - Something went wrong | ## Important Notes * **Unique Names**: Folder names must be unique within your organization * **UUID Parent**: `parent_folder_id` must be a valid UUID of an existing folder * **Icon Format**: Icons are typically emoji characters (optional) * **Sort Order**: Use integers for consistent ordering * **Auto-generated ID**: Folder ID is automatically generated (UUID) ## Folder Icons Common folder icon examples: | Icon | Use Case | | - | - | | 📚 | General documentation | | 📁 | Generic folder | | 🏢 | Company/business folders | | 🛍️ | Product folders | | 💡 | Ideas/knowledge | | 🔧 | Technical documentation | | 👥 | Team/HR folders | | 📋 | Policies/procedures | | 🎓 | Training materials | | 🌐 | Public/external content | ## Related Endpoints * [GET /api/documents/assistant/folders](/reference/knowledge-base/get-folders) - List all folders * [POST /api/documents/assistant/raw](/reference/knowledge-base/upload-document) - Upload document to folder * [DELETE /api/documents/assistant/](/reference/knowledge-base/delete-document) - Delete a document ## Workflow Example Complete workflow for organizing knowledge base: ```javascript theme={null} // 1. Create folder structure const supportFolder = await createFolder({ name: 'Support', icon: '🆘' }); const faqFolder = await createFolder({ name: 'FAQs', icon: '❓', parent_folder_id: supportFolder.id, }); // 2. Upload documents to folders await uploadDocument({ folderId: faqFolder.id, content: 'Q: How to reset password?\nA: ...', fileName: 'password-reset.md', }); // 3. List folders to verify const allFolders = await getFolders(); console.log('Knowledge base organized!'); ``` # Delete a document from a given assistant Source: https://docs.vambe.me/reference/knowledge-base/delete-document delete /api/documents/assistant/{externalId} Delete a document from a given assistant. ## Overview Delete a document from your AI assistant's knowledge base using its external ID. This removes the document from both Ragie (AI platform) and your database, ensuring your assistant no longer uses this content. Use this endpoint to remove outdated, incorrect, or sensitive information from your AI's knowledge. ## Use Cases * **Content Updates**: Remove old versions before uploading new ones * **Data Cleanup**: Remove outdated or deprecated documentation * **Compliance**: Delete sensitive information that shouldn't be in AI knowledge * **Content Management**: Remove documents that are no longer relevant * **Error Correction**: Delete incorrectly uploaded documents * **Bulk Cleanup**: Programmatically remove multiple outdated documents ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `externalId` | string | Yes | The external ID you assigned when uploading | > [!NOTE] > > **External ID**: This is the same `externalId` you provided when uploading the > document with `POST /api/documents/assistant/raw`. ## Response Structure | Field | Type | Description | | - | - | - | | `status` | string | Deletion status (e.g., "deleted") | ## Example Request ```bash theme={null} curl --request DELETE \ 'https://api.vambe.me/api/documents/assistant/ext-product-faq-001' \ --header 'x-api-key: your_api_key_here' ``` ## Example Response ```json theme={null} { "status": "deleted" } ``` ## Common Use Cases ### 1. Delete Single Document ```javascript theme={null} const deleteDocument = async (externalId) => { const response = await fetch( `https://api.vambe.me/api/documents/assistant/${externalId}`, { method: 'DELETE', headers: { 'x-api-key': 'your_api_key_here', }, }, ); const result = await response.json(); if (result.status === 'deleted') { console.log(`✅ Document ${externalId} deleted successfully`); } return result; }; ``` ### 2. Update Document (Delete + Upload) ```javascript theme={null} const updateDocument = async (externalId, newContent, folderId) => { // 1. Delete old version await fetch(`https://api.vambe.me/api/documents/assistant/${externalId}`, { method: 'DELETE', headers: { 'x-api-key': 'your_api_key_here', }, }); console.log('Old version deleted'); // 2. Upload new version with same external ID const response = await fetch( 'https://api.vambe.me/api/documents/assistant/raw', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your_api_key_here', }, body: JSON.stringify({ content: newContent, fileName: 'updated-document.md', externalId: externalId, // Same ID for tracking folderId: folderId, icon: '📄', }), }, ); const result = await response.json(); console.log('New version uploaded'); return result; }; ``` ### 3. Bulk Delete Documents ```javascript theme={null} const bulkDeleteDocuments = async (externalIds) => { const results = []; for (const externalId of externalIds) { try { const response = await fetch( `https://api.vambe.me/api/documents/assistant/${externalId}`, { method: 'DELETE', headers: { 'x-api-key': 'your_api_key_here', }, }, ); const result = await response.json(); results.push({ externalId, success: true, status: result.status }); console.log(`✅ Deleted: ${externalId}`); } catch (error) { results.push({ externalId, success: false, error: error.message }); console.error(`❌ Failed to delete: ${externalId}`); } // Small delay to avoid rate limiting await new Promise((resolve) => setTimeout(resolve, 100)); } console.log( `Deleted ${results.filter((r) => r.success).length} of ${externalIds.length} documents`, ); return results; }; ``` ### 4. Clean Up Old Documents ```javascript theme={null} const cleanupOldDocuments = async (olderThanDays = 30) => { // Get all folders with documents const foldersResponse = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const folders = await foldersResponse.json(); // Find documents to delete (this would need metadata about age) // For example, if your external IDs include timestamps const oldDocumentIds = []; const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - olderThanDays); // Your logic to identify old documents // e.g., external IDs with dates: 'doc-2024-01-15-product' // Delete old documents for (const externalId of oldDocumentIds) { await deleteDocument(externalId); } console.log(`Cleaned up ${oldDocumentIds.length} old documents`); }; ``` ### 5. Safe Delete with Confirmation ```javascript theme={null} const safeDeleteDocument = async (externalId) => { try { // Optional: Get folder info to show what's being deleted const foldersResponse = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { headers: { 'x-api-key': 'your_api_key_here' }, }, ); const folders = await foldersResponse.json(); // Find the document in folders (for confirmation) let foundDoc = null; for (const folder of folders) { foundDoc = folder.documents.find((d) => d.id === externalId); if (foundDoc) break; } if (foundDoc) { console.log(`About to delete: ${foundDoc.name}`); } // Delete const response = await fetch( `https://api.vambe.me/api/documents/assistant/${externalId}`, { method: 'DELETE', headers: { 'x-api-key': 'your_api_key_here', }, }, ); const result = await response.json(); console.log('✅ Document deleted'); return result; } catch (error) { console.error('Delete failed:', error); throw error; } }; ``` ## What Gets Deleted When you delete a document: 1. ✅ **Ragie Document**: Removed from AI knowledge platform 2. ✅ **Database Record**: Removed from knowledge\_base\_document table 3. ✅ **AI Knowledge**: Assistant will no longer use this content 4. ❌ **Folder**: The containing folder is NOT deleted 5. ❌ **Assistant Link**: Assistant-folder link remains (only document removed) ## Error Responses | Status Code | Description | | - | - | | 400 | Bad Request - Invalid external ID | | 401 | Unauthorized - Invalid or missing API key | | 404 | Not Found - Document not found | | 500 | Internal Server Error - Something went wrong | ## Important Notes * **Uses External ID**: Delete by YOUR external ID, not Ragie's internal ID * **Permanent**: Deletion is permanent and cannot be undone * **Both Systems**: Deletes from both Ragie and your database * **Folder Intact**: Only document is deleted, folder remains * **Immediate Effect**: AI will stop using this content immediately * **Not Found OK**: Deleting non-existent document returns 404 ## External ID Format Your external ID can be any string: * ✅ `"product-guide-v2"` * ✅ `"cms-article-12345"` * ✅ `"faq-${Date.now()}"` * ✅ `"user-manual-en"` Make sure to track these IDs in your system! ## Related Endpoints * [POST /api/documents/assistant/raw](/reference/knowledge-base/upload-document) - Upload a new document * [GET /api/documents/assistant/folders](/reference/knowledge-base/get-folders) - List folders and documents * [POST /api/documents/assistant/folders](/reference/knowledge-base/create-folder) - Create folders ## Best Practices ### 1. Track External IDs ```javascript theme={null} // Keep a mapping of your documents const documentRegistry = { 'product-guide-v1': { uploaded: '2024-01-15', active: false }, 'product-guide-v2': { uploaded: '2024-09-30', active: true }, }; // Delete old version await deleteDocument('product-guide-v1'); ``` ### 2. Confirm Before Delete ```javascript theme={null} const confirmAndDelete = async (externalId, documentName) => { const confirmed = confirm(`Delete "${documentName}"?`); if (confirmed) { return await deleteDocument(externalId); } console.log('Deletion cancelled'); return null; }; ``` ### 3. Handle Not Found Gracefully ```javascript theme={null} const safeDelete = async (externalId) => { try { return await deleteDocument(externalId); } catch (error) { if (error.status === 404) { console.log('Document already deleted or never existed'); return { status: 'already_deleted' }; } throw error; } }; ``` # Get all folders Source: https://docs.vambe.me/reference/knowledge-base/get-folders get /api/documents/assistant/folders Retrieve all knowledge base folders for your organization. ## Overview Retrieve all knowledge base folders for your organization. Folders help organize documents used by your AI assistants, making it easy to manage and structure your knowledge base. This endpoint returns a hierarchical structure of folders with their associated documents and subfolders. ## Use Cases * **Folder Selection**: Display available folders when uploading documents * **Knowledge Base Browser**: Build a file explorer interface * **Organization Overview**: See how your knowledge base is structured * **Document Count**: Understand content distribution across folders * **Assistant Configuration**: Show folders linked to specific assistants ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Response Structure Returns an array of folder objects with hierarchical structure: ### Folder Object | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique folder identifier | | `name` | string | Folder name | | `icon` | string \| null | Emoji/icon for the folder | | `sort_order` | number | Display order (lower numbers first) | | `client_id` | string (UUID) | Your organization ID | | `parent_folder_id` | string \| null | Parent folder ID (null for root folders) | | `source_url` | string \| null | Source URL if synced from external source | | `source_type` | string \| null | Type of source (e.g., 'confluence', 'gdrive') | | `is_public` | boolean | Whether folder is publicly accessible | | `created_at` | string (ISO) | Folder creation timestamp | | `updated_at` | string (ISO) | Last update timestamp | | `documents` | array | Array of document objects in this folder | | `subfolders` | array | Array of nested folder objects | ### Document Object (Simplified) | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Document identifier | | `name` | string | Document name | | `icon` | string | Document icon/emoji | ## Example Request ```bash theme={null} curl --request GET \ 'https://api.vambe.me/api/documents/assistant/folders' \ --header 'x-api-key: your_api_key_here' ``` ## Example Response ```json theme={null} [ { "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Product Documentation", "icon": "📚", "sort_order": 0, "client_id": "660e8400-e29b-41d4-a716-446655440001", "parent_folder_id": null, "source_url": null, "source_type": null, "is_public": false, "created_at": "2024-01-15T10:00:00.000Z", "updated_at": "2024-01-15T10:00:00.000Z", "documents": [ { "id": "doc-001", "name": "Getting Started Guide", "icon": "📄" }, { "id": "doc-002", "name": "API Reference", "icon": "📋" } ], "subfolders": [ { "id": "770e8400-e29b-41d4-a716-446655440002", "name": "Advanced Features", "icon": "🚀", "sort_order": 0, "client_id": "660e8400-e29b-41d4-a716-446655440001", "parent_folder_id": "550e8400-e29b-41d4-a716-446655440000", "source_url": null, "source_type": null, "is_public": false, "created_at": "2024-02-01T10:00:00.000Z", "updated_at": "2024-02-01T10:00:00.000Z", "documents": [], "subfolders": [] } ] }, { "id": "880e8400-e29b-41d4-a716-446655440003", "name": "Company Policies", "icon": "📋", "sort_order": 1, "client_id": "660e8400-e29b-41d4-a716-446655440001", "parent_folder_id": null, "source_url": null, "source_type": null, "is_public": false, "created_at": "2024-01-20T10:00:00.000Z", "updated_at": "2024-01-20T10:00:00.000Z", "documents": [ { "id": "doc-003", "name": "Privacy Policy", "icon": "🔒" } ], "subfolders": [] } ] ``` ## Common Use Cases ### 1. Display Folder Tree ```javascript theme={null} const displayFolderTree = async () => { const response = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const folders = await response.json(); const renderFolder = (folder, indent = 0) => { const spaces = ' '.repeat(indent); console.log( `${spaces}${folder.icon || '📁'} ${folder.name} (${folder.documents.length} docs)`, ); folder.documents.forEach((doc) => { console.log(`${spaces} ${doc.icon} ${doc.name}`); }); folder.subfolders.forEach((subfolder) => { renderFolder(subfolder, indent + 1); }); }; folders.forEach((folder) => renderFolder(folder)); return folders; }; ``` ### 2. Find Folder by Name ```javascript theme={null} const findFolderByName = async (folderName) => { const response = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const folders = await response.json(); const findRecursive = (folders, name) => { for (const folder of folders) { if (folder.name.toLowerCase() === name.toLowerCase()) { return folder; } if (folder.subfolders.length > 0) { const found = findRecursive(folder.subfolders, name); if (found) return found; } } return null; }; const folder = findRecursive(folders, folderName); if (folder) { console.log(`Found folder: ${folder.name} (ID: ${folder.id})`); console.log(`Contains ${folder.documents.length} documents`); return folder; } else { console.log(`Folder "${folderName}" not found`); return null; } }; ``` ### 3. Build Folder Dropdown ```javascript theme={null} const buildFolderDropdown = async () => { const response = await fetch( 'https://api.vambe.me/api/documents/assistant/folders', { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const folders = await response.json(); const flattenFolders = (folders, prefix = '') => { let result = []; folders.forEach((folder) => { result.push({ value: folder.id, label: `${prefix}${folder.icon || '📁'} ${folder.name}`, documentCount: folder.documents.length, }); if (folder.subfolders.length > 0) { result = result.concat( flattenFolders(folder.subfolders, `${prefix} `), ); } }); return result; }; const options = flattenFolders(folders); return options; }; // Use in a select component // ({ value: m.id, label: m.name }))} /> // // 3. On selection, assign const handleAssignment = async (selectedAgentId, shouldReplace = false) => { const url = new URL( `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${selectedAgentId}`, ); if (shouldReplace) { url.searchParams.append('removeExistingAgents', 'true'); } await fetch(url.toString(), { method: 'POST', headers: { 'x-api-key': 'your_api_key_here' }, }); // 4. Refresh contact info const updatedContact = await fetch( `https://api.vambe.me/api/public/contact/${contactId}/info`, { headers: { 'x-api-key': 'your_api_key_here' }, }, ).then((r) => r.json()); console.log('Contact updated:', updatedContact); }; ``` # Get all team members Source: https://docs.vambe.me/reference/team-members/get-all-team-members get /api/public/team-members/all ## Overview Retrieve a complete list of all team members (agents) in your organization. This endpoint returns essential information about each team member including their ID, name, email, and phone number. Use this endpoint to display team members in dropdowns, build agent assignment interfaces, or sync team data with external systems. ## Use Cases * **Agent Assignment UI**: Populate dropdowns for assigning conversations to specific agents * **Team Directory**: Display a list of all team members in your application * **Reporting & Analytics**: Get agent IDs for filtering analytics by team member * **External Integrations**: Sync team member data with external CRM or HR systems * **Automated Workflows**: Programmatically assign tasks or tickets to specific team members * **Team Management**: Build custom team management interfaces ## Authentication This endpoint requires authentication using an API key. Include your API key in the request header: ``` x-api-key: your_api_key_here ``` ## Response Structure The endpoint returns an array of team member objects: ### Team Member Object | Field | Type | Description | | - | - | - | | `id` | string (UUID) | Unique identifier for the team member | | `name` | string | Full name (first name + last name) | | `first_name` | string | Team member's first name | | `last_name` | string | Team member's last name | | `email` | string | Team member's email address | | `phone` | string | Team member's phone number | ## Example Response ```json theme={null} [ { "id": "228d7a0d-9072-4ca8-939b-959b75cc606a", "name": "Maria Rodriguez", "first_name": "Maria", "last_name": "Rodriguez", "email": "maria.rodriguez@company.com", "phone": "+56912345678" }, { "id": "338e8b1e-8183-5db9-a4ab-a6ab86dd717b", "name": "Carlos Silva", "first_name": "Carlos", "last_name": "Silva", "email": "carlos.silva@company.com", "phone": "+56987654321" }, { "id": "448f9c2f-9294-6eca-b5bc-b7bc97ee828c", "name": "Ana Martinez", "first_name": "Ana", "last_name": "Martinez", "email": "ana.martinez@company.com", "phone": "+56911223344" } ] ``` ## Common Use Cases ### 1. Populate Agent Selection Dropdown ```javascript theme={null} const loadTeamMembers = async () => { const response = await fetch( 'https://api.vambe.me/api/public/team-members/all', { headers: { 'x-api-key': 'your_api_key_here', }, }, ); const teamMembers = await response.json(); // Convert to dropdown options const agentOptions = teamMembers.map((member) => ({ value: member.id, label: member.name, email: member.email, })); return agentOptions; }; // Use in a select component //