# Let SaaS customers connect their own WhatsApp number

> Embedded Signup or a provider connect flow, then the per-tenant data model, webhook routing by number ID and disconnect handling for each customer number.

Published 2026-11-25. Z-API Omni team.

A SaaS has two ways to let each customer connect their own WhatsApp number. You can become a Meta Tech Provider and run Embedded Signup inside your app, or use a provider whose connect flow runs the signup for you. Either way, the rest is yours: one channel row per tenant number, inbound webhooks routed by number ID, a handler for disconnect events, and billing per number.

What breaks in production is a tenant number that dropped last night while your app kept queuing sends, or a webhook that reached the wrong tenant. This page covers that loop: connect, route, detect the drop, update the tenant record.

## Pick the connection path

| | Your own Embedded Signup | A provider's connect flow | QR connection |
|---|---|---|---|
| What the tenant does | Logs in to Meta in a popup from your app | Same Meta popup, launched by the provider's SDK | Scans a QR code with their phone |
| Meta setup on your side | Tech Provider, business verification, App Review | Depends on the provider | None |
| Who holds the Meta token | You | Whoever exchanges the signup code | No Meta token involved |
| Meta's per-message fees | Billed to the tenant's own account | Depends on the provider; Omni's docs bill the tenant's own account | None |
| Status with Meta | Meta's official API | Meta's official API | Not official; based on WhatsApp Web |

The trade-offs of each path are in [QR code, Embedded Signup or coexistence](/academy/articles/whatsapp-qr-embedded-signup-coexistence-compared/). The QR row carries terms-of-service risk for the tenant's number, covered in [QR connection ban risk](/academy/articles/whatsapp-qr-connection-ban-risk-terms-of-service/).

## Meta's own path, in short

Embedded Signup itself is covered step by step in [onboard clients with Embedded Signup](/academy/articles/whatsapp-embedded-signup-onboarding-clients/). That post handles the launch code, the session events, the code exchange, `subscribed_apps`, registration and the payment method. The order of business verification and App Review is in [Meta Tech Provider steps in order](/academy/articles/meta-tech-provider-whatsapp-steps-order/). Three Meta facts shape the multi-tenant design.

### Meta bills the tenant, you bill your service

Tech Providers "do not have credit lines". Each client adds their own payment method, and "Meta will then bill these clients for API usage, and the Tech Provider will bill for other services" ([Meta partners overview](https://developers.facebook.com/documentation/business-messaging/whatsapp/solution-providers/overview), accessed 2026-11-25). Your per-number price is your business. Meta's fees land on each tenant's own account, so a tenant with no valid payment method can't send templates, whatever your plan says.

### Account-level webhooks ignore your per-tenant URL

Meta lets you override the callback URL per WhatsApp Business Account or per number ([webhook override](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/override), accessed 2026-11-25). Per account, call `POST /<WABA_ID>/subscribed_apps` with `override_callback_uri` (at most 200 characters) and `verify_token`. Per number, call `POST /<PHONE_NUMBER_ID>` with `webhook_configuration`. The number wins over the account, and the account wins over the app.

Overrides don't apply to account events. In Meta's words, "Template webhooks and account-level webhooks always go to your app's default callback URL." That includes `account_update`, which is where disconnects arrive. Every tenant's offboarding signal reaches one URL even when their messages are split. One URL that routes by ID is usually simpler than [overrides](/academy/articles/whatsapp-webhook-not-receiving-messages-troubleshooting/). Routing by `entry[].id` and `phone_number_id` is in [multi-tenant webhook routing](/academy/articles/multi-tenant-whatsapp-webhook-routing-agencies/).

### The offboarding signals

The `account_update` reference lists the events that end or pause a tenant's connection ([account_update reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/account_update), accessed 2026-11-25).

| `event` | Meta's description | What to do with the tenant |
|---|---|---|
| `PARTNER_APP_UNINSTALLED` | "a business customer deauthenticated or uninstalled the app" | Mark every number of that account disconnected |
| `PARTNER_REMOVED` | the account "has been unshared with a Solution Partner" | Same, and stop all sends |
| `ACCOUNT_DELETED` | "the Messaging account was deleted" | Close the channel rows |
| `ACCOUNT_OFFBOARDED` | offboarded "due to a device change or phone number reregistration" | Pause sends |
| `ACCOUNT_RECONNECTED` | reconnected after that change | Resume sends |

The reference also lists `ACCOUNT_RESTRICTION`, `ACCOUNT_VIOLATION` and `DISABLED_UPDATE`. The `PARTNER_REMOVED` and `PARTNER_APP_UNINSTALLED` samples identify the account by `waba_info.waba_id` and carry no phone number field. Your mapping from account to numbers has to live in your own tables. Offboard and reconnect recovery is in [coexistence disconnected and reconnect](/academy/articles/whatsapp-coexistence-disconnected-reconnect/).

## The per-tenant data model

This schema is our own design, not from Meta or any provider. One row per connected number, a column for the provider's channel ID when you use one, and a table that remembers webhook deliveries so retries don't run twice.

```sql
-- PostgreSQL 13+
CREATE TABLE tenants (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  name        text NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE channels (
  id                           uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id                    uuid NOT NULL REFERENCES tenants(id),
  provider_channel_id          text UNIQUE,          -- null on your own Embedded Signup
  type                         text NOT NULL,        -- e.g. whatsapp_official, whatsapp_qr, instagram
  waba_id                      text,
  phone_number_id              text UNIQUE,
  coexistence                  boolean NOT NULL DEFAULT false,
  status                       text NOT NULL DEFAULT 'pending', -- pending, connected, paused, disconnected
  connected_at                 timestamptz,
  last_disconnect_reason_code  text,
  last_disconnect_origin       text,
  last_disconnect_at           timestamptz
);
CREATE INDEX channels_waba_idx ON channels (waba_id);

CREATE TABLE webhook_deliveries (
  delivery_id  text PRIMARY KEY,                     -- message id, event id or delivery header
  received_at  timestamptz NOT NULL DEFAULT now()    -- keep at least 24 hours
);
```

To keep tenants apart, reject any inbound event whose number or channel ID isn't in `channels`. Check that a channel belongs to the signed-in tenant before any call that touches it, including the connect step.

## Route inbound events to the tenant

This service takes Meta's webhooks on one URL, verifies `X-Hub-Signature-256`, and routes by `phone_number_id` for messages and by WABA ID for `account_update`. The in-memory Maps mirror the `channels` and `webhook_deliveries` tables above.

```js
// tenant-router.js. Node 18+, Express 4. npm install express. Run: node tenant-router.js
const crypto = require("crypto");
const express = require("express");

const { APP_SECRET, VERIFY_TOKEN, PORT = 3000 } = process.env;

// Mirrors the channels table. Seed one row so you can test with your own IDs.
const channels = new Map([
  [process.env.TEST_PHONE_NUMBER_ID || "PHONE_NUMBER_ID", {
    tenantId: "tenant_a", wabaId: process.env.TEST_WABA_ID || "WABA_ID", status: "connected",
  }],
]);
const deliveries = new Set();

const STOP_EVENTS = new Set(["PARTNER_APP_UNINSTALLED", "PARTNER_REMOVED", "ACCOUNT_DELETED"]);

function setStatusForWaba(wabaId, status, reason) {
  for (const [phoneId, ch] of channels) {
    if (ch.wabaId !== wabaId) continue;
    ch.status = status;
    if (status !== "connected") {
      ch.lastDisconnectReason = reason;
      ch.lastDisconnectAt = new Date().toISOString();
    }
    console.log("tenant channel", ch.tenantId, phoneId, "->", status, reason);
  }
}

function handleMessage(phoneId, msg) {
  if (deliveries.has(msg.id)) return;
  deliveries.add(msg.id);
  const ch = channels.get(phoneId);
  if (!ch) return console.warn("unknown phone_number_id, dropped", phoneId);
  // Hand off to the tenant's inbox or queue here.
  console.log("message for", ch.tenantId, msg.from, msg.type);
}

const app = express();

app.get("/webhook", (req, res) => {
  if (req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN) {
    return res.send(req.query["hub.challenge"]);
  }
  res.sendStatus(403);
});

app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex");
  const got = req.get("x-hub-signature-256") || "";
  const ok = Buffer.byteLength(got) === Buffer.byteLength(expected) &&
    crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected));
  if (!ok) return res.sendStatus(401);
  res.sendStatus(200);

  const body = JSON.parse(req.body);
  for (const entry of body.entry ?? []) {
    for (const change of entry.changes ?? []) {
      const value = change.value ?? {};
      if (change.field === "messages") {
        const phoneId = value.metadata?.phone_number_id;
        for (const msg of value.messages ?? []) handleMessage(phoneId, msg);
      } else if (change.field === "account_update") {
        const wabaId = value.waba_info?.waba_id ?? entry.id;
        if (STOP_EVENTS.has(value.event)) setStatusForWaba(wabaId, "disconnected", value.event);
        else if (value.event === "ACCOUNT_OFFBOARDED") setStatusForWaba(wabaId, "paused", value.event);
        else if (value.event === "ACCOUNT_RECONNECTED") setStatusForWaba(wabaId, "connected", value.event);
        else console.log("account_update not handled", value.event, wabaId);
      }
    }
  }
});

app.listen(PORT, () => console.log(`listening on ${PORT}`));
```

Your send path should read `channels.status` before every send and refuse anything not `connected`. A tenant whose number dropped should see that in your UI with the reason, not discover it from a customer complaint.

## The provider path, step by step with Z-API Omni

A provider's connect flow replaces your Embedded Signup integration with an SDK call and a backend call. Omni's documented flow is below. None of these requests has been run for this article, so test each one in your workspace first. The docs don't say whether a SaaS using this flow also needs its own Tech Provider status or App Review. Ask before you plan around either answer.

### Create one channel per tenant number

`POST https://api.omni.z-api.io/v1/channels` takes a `name` and a `type`: `META_WHATSAPP`, `Z_API_WHATSAPP`, `META_INSTAGRAM`, `META_MESSENGER` or `BOT_TELEGRAM` ([create channel](https://developer.omni.z-api.io/en/channels/create-channel)). A `201` returns `id` and `token`. The token comes back only when you call with the Secret Key; with an OAuth app token you get "only `id`".

Names must be unique among active channels, ignoring case, surrounding spaces and channel type. A clash returns `409 {"error":"channel_name_in_use"}`. "A canceled channel that was not deleted still holds its name." The page gives the start date of this rule as still to be confirmed. Put your tenant ID in the name so names never collide.

<!-- TODO:test Omni snippet: create channel with the Secret Key returns 201 with id and token; 409 on a duplicate name -->
```bash
curl -X POST 'https://api.omni.z-api.io/v1/channels' \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H 'Content-Type: application/json' \
  -d '{ "name": "tenant_a-main", "type": "META_WHATSAPP" }'
```

Store the returned `id` in `channels.provider_channel_id` before you show the tenant a Connect button.

### Connect from the tenant's browser

The `@omnizapi/connect` package (v1.1.1 on npm, MIT) "reads the channel type and dispatches the right flow" ([connect introduction](https://developer.omni.z-api.io/en/connect/introduction)). For `META_WHATSAPP` that flow is Meta's Embedded Signup. The Public Key (`pk_…`) is safe in the frontend, with "limited permissions for channel connection only" ([authentication](https://developer.omni.z-api.io/en/authentication)).

<!-- TODO:test Omni snippet: connect() called directly in the click handler opens the popup; response object shape for META_WHATSAPP -->
```js
import OmniZapi from '@omnizapi/connect';

const client = OmniZapi.newClient({ publicKey: 'YOUR_PUBLIC_KEY' });

document.querySelector('#connect').addEventListener('click', () => {
  // Call connect() first. An await before it can get the popup blocked.
  client.connect({ channelId: 'CHANNEL_ID' }).then((response) => {
    // Forward the whole object as-is; do not pick fields out of it.
    return fetch('/api/channels/CHANNEL_ID/connect', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(response),
    });
  });
});
```

For Meta the response carries `success`, `channelId`, `code`, `wabaId`, `phoneId` and `coexistence`. The docs say "Do not handle these fields manually". Meta's side still requires a Business Portfolio and an admin on that business account. The number must receive an SMS or a call, and templates need a payment method ([connect Meta WhatsApp](https://developer.omni.z-api.io/en/connect/meta-whatsapp)).

The SDK "resolves `{ success: false }` **without saying why**" ([SDK info](https://developer.omni.z-api.io/en/channels/sdk-info)). There are two documented causes. One is a page origin missing from `allowOrigins`, which you register in the dashboard under Security, SDK Configuration; "There is no public endpoint for it." Register staging and localhost too. Wildcards such as `https://*.yourcompany.com` need SDK 1.1.1 or later. The other cause is the popup block from an `await` before `connect()`. Check the origin list with the Public Key, sent without `Bearer`:

<!-- TODO:test Omni snippet: sdk-info with the Public Key and no Bearer prefix lists the allowed origins -->
```bash
curl 'https://api.omni.z-api.io/instances/CHANNEL_ID/sdk-info' \
  -H "Authorization: $OMNI_PUBLIC_KEY"
```

For a QR connection the SDK uses `getQRCode`. Your backend proxies `GET /v1/channels/{id}/zapi/qr-code/image` with the Secret Key and returns `{qrcode, connected}` ([connect WhatsApp Web](https://developer.omni.z-api.io/en/connect/whatsapp-web)). The page says to "Check the user's session and that the channel belongs to them **before** calling the API". Without a subscription the call returns `422` with `NEED_SIGN_ZAPI`.

### Finish on your backend

Your backend checks that `CHANNEL_ID` belongs to the signed-in tenant, then forwards the body to `POST /v1/channels/{channelId}/connect` with the Secret Key ([connect channel](https://developer.omni.z-api.io/en/channels/connect-channel)). `wabaId`, `phoneId`, `code` and `coexistence` are all required. Success is `200 {"success": true}`.

<!-- TODO:test Omni snippet: connect returns 200 success; 409 channel_already_connected on a second call with the same number -->
```bash
curl -X POST 'https://api.omni.z-api.io/v1/channels/CHANNEL_ID/connect' \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H 'Content-Type: application/json' \
  -d '{ "wabaId": "WABA_ID", "phoneId": "PHONE_ID", "code": "CODE_FROM_SDK", "coexistence": false }'
```

The same number twice returns `409 {"error":"channel_already_connected"}`. To renew a connection, call `PUT /v1/channels/{channelId}/disconnect` first; "The channel is offline between the two calls." A different `phoneId` "switches the number", so treat that as a tenant action, not a retry. Write `waba_id`, `phone_number_id`, `coexistence` and `connected_at` to the channel row on success.

### One webhook for every tenant

There's one Public Key and one Secret Key per workspace, and no per-tenant keys. Multi-tenancy is your mapping from channel ID to tenant. The workspace default webhook fits that model. `POST /v1/default-instance-webhooks` "applies to every channel in the workspace that has no active webhook of its own, including channels created after it" ([default webhooks](https://developer.omni.z-api.io/en/webhooks/default-webhooks)).

<!-- TODO:test Omni snippet: default webhook creation; new channels inherit it; channel id field in MESSAGE_RECEIVED payloads -->
```bash
curl -X POST 'https://api.omni.z-api.io/v1/default-instance-webhooks' \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H 'Content-Type: application/json' \
  -d '{ "url": "https://app.example.com/webhooks/omni", "events": ["MESSAGE_RECEIVED", "MESSAGE_STATUS"], "signing": true }'
```

A workspace can hold 5 default webhooks, and changes apply "within 5 minutes". The ENTERPRISE role is not required. The default webhook doesn't fill gaps either: "The channel webhook is not topped up by the default webhook." A tenant channel with its own webhook subscribed only to `MESSAGE_STATUS` stops sending `MESSAGE_RECEIVED` anywhere. Route each payload by its channel ID to the tenant, and verify `x-webhook-signature` as the HMAC signing page describes.

### Disconnects with a reason code

Subscribe the global webhook to `CHANNEL_DISCONNECTED` ([channel disconnected](https://developer.omni.z-api.io/en/webhooks/channel-disconnected)). It is "Global webhook only": channel and default webhooks reject it with `422`.

<!-- TODO:test Omni snippet: global webhook subscription to CHANNEL_DISCONNECTED -->
```bash
curl -X POST 'https://api.omni.z-api.io/v1/webhooks' \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"url":"https://channels.example.com/hook","events":["CHANNEL_DISCONNECTED"]}'
```

This is the documented body:

```json
{
  "id": "0b8e5f0e-4a3c-5d1b-9c2e-7f6a5b4c3d2e",
  "type": "CHANNEL_DISCONNECTED",
  "occurredAt": "2026-10-21T18:00:00Z",
  "data": {
    "instanceId": "<instance id>",
    "channelType": "META_WHATSAPP",
    "reasonCode": "PARTNER_REMOVED",
    "reason": "WABA disconnected due to primary device inactivity",
    "origin": "EXTERNAL",
    "initiatedBy": "SYSTEM",
    "disconnectedAt": "2026-10-21T18:00:00Z"
  }
}
```

| `reasonCode` | What happened |
|---|---|
| `PHONE_BANNED` | The number was banned or blocked by the platform |
| `ACCOUNT_DISABLED` | The account on that platform was disabled or deleted |
| `PARTNER_REMOVED` | The WhatsApp Business account removed Omni as a partner |
| `APP_UNINSTALLED` | Omni's app was uninstalled from the account |
| `PHONE_REMOVED` | The number was removed from the WhatsApp Business account |
| `TOKEN_REVOKED` | The Telegram bot token was revoked, or the bot was deleted |
| `PERMISSION_REVOKED`, `REPEATED_SEND_FAILURE` | "Reserved: not sent yet" |
| `null` | No code, and always `null` when `origin` is `USER` or `BILLING` |

`origin` is `USER`, `BILLING` or `EXTERNAL`. Write `reasonCode`, `origin` and `disconnectedAt` to the channel row by `data.instanceId`. Order isn't guaranteed, so sort by `disconnectedAt` and dedupe by `id`. "New codes may appear", so treat an unknown code as a generic disconnect. A whole-account drop sends one notice per channel. Some WhatsApp Web drops send no notice at all, and `GET /v1/channels/{id}` never returns the reason code.

The body "never carries a phone number", but the `reason` text may contain one on WhatsApp Web. Don't show `reason` to other tenants or put it in shared logs unchecked.

### Billing and channel management

Channel management routes need the ENTERPRISE role, or they return `403 plan_required`. Support enables it, and it can take "up to **4 hours** to take effect" ([channels introduction](https://developer.omni.z-api.io/en/channels/introduction)). The routes are `GET /v1/channels/{channelId}/subscribe`, `DELETE /v1/channels/{channelId}/cancel`, `DELETE /v1/channels/{channelId}`, `GET /v1/channels` and `GET /v1/channels/{channelId}`. Subscribe "Links the channel to the account's active Stripe subscription", prorated, and the payment is made beforehand in the dashboard. Create and connect don't mention the role.

Two events about your own Omni subscription behave differently ([account events](https://developer.omni.z-api.io/en/webhooks/account-events)). With `BILLING_INSTANCE_SUSPENDED`, "The channel stays linked". With `BILLING_INSTANCE_RELEASED`, "the channel must be reconnected", and a `CHANNEL_DISCONNECTED` with origin `BILLING` arrives too. Meta's fees on the official connection go to each tenant's own WhatsApp Business Account payment method ([payment](https://developer.omni.z-api.io/en/whatsapp-official/payment)). That page is written for Brazil and tells you to set the country to Brazil.

## Where Z-API Omni fits

Z-API Omni fits a SaaS that wants each tenant to connect a number without building its own Embedded Signup integration. One subscription covers WhatsApp, Messenger, Instagram and Telegram, and each tenant can pick the QR connection or Meta's official API in the same account. Webhooks are included without limit.

Price is per number, which maps onto per-tenant billing. It is US$29 a month for 1 to 10 numbers, US$26 for 11 to 50, US$23 for 51 to 100 and US$20 above 100. There's no per-message cost on the QR connection, and Meta's fees are passed through on the official one. The docs, in Portuguese, English and Spanish, don't cover white-label, sub-accounts or per-tenant keys, so plan your tenant mapping on your side.

[View documentation](https://developer.omni.z-api.io/en)

*Z-API Omni team*
