# Meteor inside

**Meteor inside** is what your merchant sees when you give them WhatsApp from your platform: they connect their number, and their chats show up in an inbox inside your page, with a Met that answers and your team or the merchant taking over the conversation when needed. **The merchant never leaves your product and needs no Meteor user.**

This page is the end-to-end path, in four steps, with the minimum code for each. Every step links to its full detail in [WhatsApp for platforms](whatsapp-for-platforms.html), and the reference app puts them together in a single project you can run.

## Before you start

- **A live partner API key** from an approved Tech Partner. Steps 1, 2 and 4 only work with it: a workspace key doesn't have those permissions, and neither does a test key (`met_test_`), because they connect real numbers.
- **Your origins registered.** The https origin from which your page opens the connection and the inbox has to be on your partner's list; otherwise the API answers `403 origin_not_allowed`. Ask your Meteor contact to add it.
- **Your partner linked to a Met account of yours**, so you get the line notices of all your merchants on a single endpoint (step 3).

| Step | What it does | With | Scope |
|---|---|---|---|
| 1 | Creates the merchant's account | `met.workspaces.create()` | `workspaces:provision` |
| 2 | Connects their WhatsApp | `met.workspaces.whatsappConnectSession()` + `connectWhatsapp()` | `channels:connect` |
| 3 | Confirms the line by webhook | `met.webhooks.subscriptions.create()` + `constructEvent()` | `webhooks:manage` (on your Met account) |
| 4 | Mounts their embedded inbox | `met.workspaces.inboxSession()` + `postMessage` | `inbox:embed` |

## 1. Create the merchant's account

Your backend creates the account with the partner key. It is born on the Tech Partner plan, attributed to you and **with no energy**: top it up before its first message, or the Met does not answer.

```ts
import Met from '@meteor.ia/sdk';

const met = new Met(process.env.MET_PARTNER_KEY!);

const account = await met.workspaces.create(
  { business_name: 'Restaurante La Esquina', owner_email: 'owner@laesquina.co', owner_name: 'Carlos Ruiz', owner_phone: '+573001234567' },
  { idempotencyKey: `signup-${merchant.id}` }, // a retry returns the same account
);
```

Steps 2 and 4 only work on accounts attributed to you; on any other, `403 workspace_not_attributed`. Quotas, top-ups and handover: [Account provisioning](account-provisioning.html).

## 2. Connect their WhatsApp with `connectWhatsapp()`

Your backend requests the connect session; your page opens it with `connectWhatsapp()`, from the SDK's browser subpath, **inside the merchant's click**. The key never goes to the browser.

```ts
// Backend: POST /api/whatsapp/session
const session = await met.workspaces.whatsappConnectSession(account.id, { return_origin: 'https://app.yourplatform.com' });
return { session_id: session.session_id, connect_url: session.connect_url }; // the connect_url works once: don't store it
```

```ts
// Page, at https://app.yourplatform.com
import { connectWhatsapp, MetWhatsappConnectError } from '@meteor.ia/sdk/browser';

button.onclick = async () => {
  try {
    const r = await connectWhatsapp(() => fetch('/api/whatsapp/session', { method: 'POST' }).then((res) => res.json()));
    show(`${r.phone_number} connected. Confirming…`); // a notice: the confirmation is the webhook
  } catch (e) {
    if (e instanceof MetWhatsappConnectError) showNotice(e.message); // e.code: popup_blocked, popup_closed…
  }
};
```

`return_origin` has to be the origin of the page that calls `connectWhatsapp()`, and that page can't send `Cross-Origin-Opener-Policy: same-origin`: in either case the notice doesn't arrive. By default it connects by coexistence: the merchant keeps using the WhatsApp Business app on their phone.

> **`@meteor.ia/sdk/browser` ships with SDK 0.18.0**, which is not on npm yet. Until then, open the `connect_url` with `window.open` and listen for the `meteor.whatsapp.connect` `postMessage`, as the detail guide explains.

The link variant, the error codes and the `postMessage` without the SDK: [Generate the link to connect WhatsApp](whatsapp-for-platforms.html#2-generate-the-link-to-connect-whatsapp).

## 3. Receive and verify the webhook

The browser's result may never arrive: the merchant closes the window too early. The truth is the webhook. Register your endpoint **once** on your own Met account, with a workspace key of that account:

```ts
const metMyAccount = new Met(process.env.MET_MY_ACCOUNT_KEY!);
const sub = await metMyAccount.webhooks.subscriptions.create({
  url: 'https://app.yourplatform.com/met/events',
  enabled_events: ['channel.line.connected', 'channel.line.failed'],
});
// sub.secret is shown ONLY once: store it
```

On your endpoint, verify the `X-Met-Signature` signature over the **raw** body, before parsing it:

```ts
import { constructEvent, MetSignatureVerificationError } from '@meteor.ia/sdk';

// `raw`: the body exactly as it arrived, as text or a Buffer
try {
  const event = constructEvent(raw, String(req.headers['x-met-signature'] ?? ''), process.env.MET_WEBHOOK_SECRET!);
  if (event.type === 'channel.line.connected') {
    const { workspace_id, connect_session_id, line_id, phone_number } = event.data;
    // connect_session_id is the session_id from step 2; keep the line_id for step 4
  }
  res.status(200).end();
} catch (e) {
  if (e instanceof MetSignatureVerificationError) res.status(400).end();
  else throw e;
}
```

`channel.line.failed` carries `error_code`, never Meta's raw message. A delivery retry carries the same event `id`: use it so you don't process it twice. The full body of the events: [Learn about each line by webhook](whatsapp-for-platforms.html#3-learn-about-each-line-by-webhook); signatures and retries: [Webhooks](webhooks.html).

## 4. Mount their embedded inbox

Your backend requests an inbox session **every time** you are about to show it, and your page puts the `inbox_url` in an iframe served from `parent_origin`:

```ts
const inbox = await met.workspaces.inboxSession(account.id, {
  parent_origin: 'https://app.yourplatform.com', // exact origin, registered
  line_id: lineId,                                  // the one from the webhook; without it, every chat on the account
  language: 'en',
  theme: 'system',
  brand_color: '#0F7B6C',
  hide: ['search'],
});
// inbox.inbox_url → into the iframe's src. It works once and lasts 10 minutes unopened.
```

```html
<iframe id="inbox" src="INBOX_URL" title="WhatsApp inbox" style="width:100%;height:640px;border:0"></iframe>
```

There the merchant reads and replies, takes a chat (the Met goes quiet), hands it back and pauses the AI. It is built from the same pieces as Met's Chat: when Met improves its inbox, yours improves with it. Your page is only the host, and talks to it by `postMessage` with the `meteor.inbox:` prefix and the `nonce` the inbox announces in its first message:

```ts
const ORIGIN = new URL(inbox.inbox_url).origin;
const frame = document.getElementById('inbox') as HTMLIFrameElement;
let nonce: string | null = null;
const send = (event: string, payload = {}) =>
  nonce && frame.contentWindow!.postMessage('meteor.inbox:' + JSON.stringify({ version: 1, nonce, event, payload }), ORIGIN);

window.addEventListener('message', (e) => {
  if (e.origin !== ORIGIN || e.source !== frame.contentWindow) return;
  if (typeof e.data !== 'string' || !e.data.startsWith('meteor.inbox:')) return;
  let m;
  try { m = JSON.parse(e.data.slice('meteor.inbox:'.length)); } catch { return; }
  if (m.version !== 1) return;
  nonce ??= m.nonce;
  if (m.nonce !== nonce) return;
  if (m.event === 'ready') send('init', { theme: 'dark', brand_color: '#0F7B6C' });
  if (m.event === 'session.expired') requestAnotherSession(); // never reuse the URL
});
```

**What you customize:**

| What | When creating the session | Live, by `postMessage` |
|---|---|---|
| Theme | `theme`: `light`, `dark` or `system` | `set_theme` |
| Brand color | `brand_color` as `#RRGGBB` | `set_theme` |
| Language | `language`: `es` or `en` | `set_language` |
| Bubble and button style | `style` (closed list, no free CSS) | `init` |
| Hide sections | `hide`: `search`, `ai_controls`, `attachments`, `new_chat`, `sort` | — fixed when the session is created |

To close it before it expires, revoke it with `met.workspaces.revokeInboxSession(account.id, inbox.session_id)`. The full host with reconnection, the customer panel with your actions and relations, and every style variable: [Open the inbox inside your product](whatsapp-for-platforms.html#4-open-the-inbox-inside-your-product) and [Customize the inbox](whatsapp-for-platforms.html#5-customize-the-inbox).

## The reference app

The reference app (the `examples/meteor-adentro/` folder of the TypeScript SDK, which ships with 0.18.0) does the four steps in a single project: a Node server with no dependencies beyond the SDK (`servidor.ts`), a script that registers the webhook once (`registrar-webhook.ts`) and a page with no bundler that uses `connectWhatsapp()` and mounts the inbox with its host. Credentials go in environment variables (`MET_PARTNER_KEY`, `MET_WEBHOOK_SECRET`, `APP_ORIGIN`, and `MET_MI_CUENTA_KEY` to register), with an optional `DEMO_TOKEN` that protects its `/api` routes, and its README explains how to run it. It keeps state in memory: it is a reference, not a product.

## Try it first with a test key

Until you have your live key, a partner test key (`met_test_`) lets you check that your backend authenticates and handles every error along the path. It doesn't touch real numbers or chats.

| What you call | What a `met_test_` key gets |
|---|---|
| Your partner business: `GET /partner/clients`, `/partner/leads` and `/partner/commissions` on `api.partners.meteor.com.co` | `200` if your key carries the `partner:*:read` scopes. With no attributed accounts, the lists come back empty |
| Steps 1, 2 and 4 | `403 missing_scope` if your test key doesn't carry the step's scope; `403 test_mode_restricted` if it does. They create accounts, connect numbers and answer real chats: they never run with a test key |
| Step 3 | It's registered in your own Met account, with a workspace key of that account, not with the partner key |
| Any other route on an account that isn't attributed to you | `403 workspace_not_attributed` |

If your code already tells those three `403`s apart and shows you the `message`, switching to the live key is just the environment variable, with a live key that carries the scopes of the steps in the table.

## What it doesn't include yet

- **Chat with a Met.** What you can embed today is the WhatsApp inbox. A conversation with a Met can't be put in your page.
- **New numbers by API.** The API doesn't create or buy WhatsApp numbers. The merchant connects a number they already have, in Meta's signup in step 2, either by coexistence or as a dedicated number.

> **The inbox is in pilot.** It works end to end. Write to us before rolling it out to all your merchants.
