# Customer Onboarding

Canonical: https://docs.bluehola.com/docs/guides/customer-onboarding
OpenAPI: https://docs.bluehola.com/openapi.yaml

With a customer API Key you can onboard your own WhatsApp assets. Identify the ownership target by **exactly one** of `customerEntityId` (recommended — no Business Portfolio is needed in advance) or `portfolioId` (an existing BlueHola Business Portfolio record); then choose the hosted invitation page or submit the result from your own Meta SDK authorization page. Both routes use the same onboarding state machine.

Creating invitations and onboarding operations requires `onboarding:write`; reading invitations and operations requires `onboarding:read`. Every target must remain inside the Key’s current authorization scope. All credentials and links below are placeholders.

## 1. Confirm your identity and check existing records

```bash
curl "https://api.bluehola.com/whoami" \
  -H "Authorization: Bearer <API_KEY>"
```

Read `customerEntityId` from the response and pass it when listing assets. A customer Key must include its own customer entity filter on the Portfolio, WABA and phone number lists; omitting it returns `403`.

```bash
curl "https://api.bluehola.com/v1/business-portfolios?customerEntityId=cust_01923abc" \
  -H "Authorization: Bearer <API_KEY>"
```

An HTTP 200 with `[]` means no Portfolio is registered for this customer yet. If you plan to identify onboarding by `portfolioId`, create a record in the next step; with `customerEntityId`, records are created automatically after authorization.

## 2. (Optional) Create an internal onboarding record

Skip this step when you identify onboarding by `customerEntityId`.

```bash
curl -X POST "https://api.bluehola.com/v1/business-portfolios" \
  -H "Authorization: Bearer <API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Example Company"
  }'
```

```json title="201 Created (excerpt)"
{
  "id": "bm_01923abc",
  "name": "Example Company",
  "customerEntityId": "cust_01923abc",
  "metaBmId": null
}
```

Save the returned `id` and use it as `portfolioId`. With a customer Key, ownership is derived from the Key: `customerEntityId` may be omitted, and specifying another customer returns `403`. Omit `metaBmId`; supplying it with a customer Key returns `400`. This creates a local onboarding record, without creating or authorizing any Meta asset. See [Create Portfolio](../assets-phone-numbers/post-v1-business-portfolios.md).

| Identifier | Meaning |
| --- | --- |
| `customerEntityId`, such as `cust_01923abc` | Your customer entity, read from `GET /whoami`. Passing it to an onboarding or invitation call needs no Portfolio in advance. |
| `portfolioId`, such as `bm_01923abc` | BlueHola’s internal Business Portfolio record ID. It identifies one specific record and is not required when you use `customerEntityId`. |
| `metaBmId`, such as `1234567890123456` | The numeric Meta Business Portfolio ID, determined by Meta from the authorized WABA. It cannot replace `portfolioId`. |

## 3. Choose an authorization route

| Route | When to use it |
| --- | --- |
| Hosted invitation page | You want a ready-made page for the customer to complete Meta authorization. |
| Your own Meta SDK page | You already run an authorization page and can submit Meta’s result from your backend. |

### A. Generate a hosted invitation link

```bash
curl -X POST "https://api.bluehola.com/v1/onboarding/invitations" \
  -H "Authorization: Bearer <API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "customerEntityId": "cust_01923abc"
  }'
```

Pass exactly one of `customerEntityId` or `portfolioId`; both or neither returns 400. With `customerEntityId`, the response’s `portfolioName` is empty because the Portfolio does not exist until the customer authorizes.

The HTTP 201 response contains `url`, `expiresAt` and an initial `status: pending`. Save the URL when it is returned: the plaintext link appears only once. The link expires after 1800 seconds (30 minutes) by default; `expiresInSeconds` accepts 300–86400. Open the returned URL on the customer’s device.

A person with access to the intended Meta Business Portfolio signs in to Meta and selects the business, WABA and, when applicable, phone number. The page submits the authorization result automatically using its invitation token; it needs no API Key from the person opening it. You do not separately call `POST /v1/onboarding/embedded-signup` for this route.

`mode` can be `splbv` (default), `alipay` or `standard`. Alipay verification requires the legal representative’s participation. See [Create Onboarding Link](../onboarding/post-v1-onboarding-invitations.md) for verification options.

### B. Submit the result from your own SDK page

Read the non-confidential SDK settings from [`GET /v1/onboarding/config`](../onboarding/get-v1-onboarding-config.md). After your page completes Meta authorization, submit the returned code and asset IDs from your backend:

```bash
curl -X POST "https://api.bluehola.com/v1/onboarding/embedded-signup" \
  -H "Authorization: Bearer <API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "customerEntityId": "cust_01923abc",
    "code": "<META_OAUTH_CODE>",
    "wabaId": "<META_WABA_ID>",
    "phoneNumberId": "<META_PHONE_NUMBER_ID>",
    "esVersion": "v4"
  }'
```

Use Meta’s actual return values. Pass exactly one of `customerEntityId` or `portfolioId`. `phoneNumberId` is optional for a WABA-only completion; also forward `sessionInfo` from the ES message event when available. `POST /v1/onboarding/embedded-signup` consumes a completed authorization result and returns an operation; it does not generate an authorization URL. An empty `{}` body is invalid. See [Complete Onboarding](../onboarding/post-v1-onboarding-embedded-signup.md).

## 4. Confirm the binding and operation status

The backend exchanges the code, checks the grant against the submitted WABA and phone number, and reads the WABA owner from Meta before binding `metaBmId`. Merely creating a record or holding a numeric Meta BM ID does not establish that binding.

When you passed `customerEntityId`, the Portfolio is found from the WABA owner and reused or created at this point, and the operation’s `portfolioId` is backfilled. If that Meta BM already belongs to another customer or another BU, the operation fails with `lastErrorCode: ONBOARDING_META_BM_ALREADY_CONNECTED` and `requiredInput: null`: the binding is not reassigned and retrying cannot fix it — start a new onboarding for the Business Portfolio that already holds that Meta BM. A customer entity that does not exist returns 404 before the authorization code is used.

When you passed `portfolioId`, an existing `metaBmId` that disagrees with the authorized WABA owner is rejected with `403`.

```bash
curl "https://api.bluehola.com/v1/onboarding/embedded-signup?limit=20" \
  -H "Authorization: Bearer <API_KEY>"
```

The list returns `{ "data": [...] }`, automatically filtered to your customer’s current Portfolios. `GET /v1/onboarding/invitations?limit=20` has the same customer filtering. Neither list requires `customerEntityId`. Use the operation’s `id` (`onb_...`) with `GET /v1/onboarding/embedded-signup/{operationId}` for detailed progress.

Check `status: completed`; HTTP 201 from the direct endpoint or HTTP 202 from an invitation completion alone does not mean onboarding succeeded. On failure, use the matching retry endpoint for the existing operation. You can read the resulting Meta binding with `GET /v1/business-portfolios/{id}`.

## The five orchestration stages

An onboarding run is a **persisted, resumable** state machine. The `steps` array returned by a single-operation query always contains these five steps, each with a status of `pending`, `running`, `completed`, `failed` or `skipped`:

| Step id          | What it does                                                                                                          |
| ---------------- | --------------------------------------------------------------------------------------------------------------------- |
| `exchange_token` | Exchanges the Meta OAuth code for the credential needed to reach that customer's Meta resources later, and stores it encrypted with AES-256-GCM.                      |
| `subscribe_app`  | Subscribes the app with Meta so that WABA message and status callbacks flow into the platform's webhook pipeline.                                            |
| `register_phone` | Registers the number with the Cloud API. When no phone registration was requested, the whole step is marked `skipped`; the registration PIN is generated by the platform and stored encrypted, so the customer does not need to supply one. |
| `sync_resources` | Pulls the latest WABA and phone number details from Meta (display name, quality rating and so on).                                                        |
| `persist_assets` | Persists the assets and ownership relationships (WABA, phone number, cross-account reverse index).                                                            |

A failure in any step halts the whole run: `currentStep` and `lastError*` stop at the point of failure and the status becomes `failed`. At that point call `POST .../embedded-signup/{operationId}/retry` to **resume from where it stopped**, rather than POSTing to the create endpoint again — that would create a brand-new operation. The `code` parameter on retry is optional: omit it if the old token is still valid (it simply resumes), and only have the customer re-authorize for a fresh code once the token has expired. An operation that completed without registering a phone number at the time can also use retry to run just that registration step later.

```mermaid
flowchart TB
    S([triggered by complete or retry]) --> T1["exchange_token<br/>exchange for credentials, store AES-256-GCM encrypted"]
    T1 --> T2["subscribe_app<br/>subscribe the app, open the webhook pipeline"]
    T2 --> T3["register_phone<br/>register the number with the Cloud API"]
    T3 --> T4["sync_resources<br/>pull the latest WABA / phone number details"]
    T4 --> T5["persist_assets<br/>persist assets and ownership"]
    T5 --> OK([completed])
    T3 -. whole step skipped if no registration was requested .-> T4
    T1 -. any step fails .-> F
    T2 -. fails .-> F
    T3 -. fails .-> F
    T4 -. fails .-> F
    T5 -. fails .-> F
    F["failed<br/>currentStep and lastError stop at the failure"] -->|"POST .../retry resumes from there"| S
```

## Customer-side endpoints (no authentication)

The group of endpoints beginning `/v1/onboarding/invitations/{token}` deliberately carries **no API Key auth** — the token in the link is itself the credential (rate-limited per source IP).

| Endpoint                        | Purpose                                                                                                                                                                |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET .../{token}`           | Landing page initialization: returns non-confidential information such as the customer name and the Meta appId/configId. Invalid, expired and revoked all resolve to the same "invitation is no longer valid" outcome, without revealing which.                                                      |
| `POST .../{token}/complete` | Submits the Meta authorization result (code + wabaId + phoneNumberId) and triggers the orchestration. It claims the invitation atomically (pending and unexpired) before executing, so a double-click on submit cannot produce two sets of assets. A 202 only means it was accepted — you must poll status. |
| `POST .../{token}/retry`    | After a first failure, resumes the same operation with a **fresh code**. Only the code may change — wabaId and phoneNumberId were bound on first submission, and pointing at different target assets on retry is rejected.                                |
| `GET .../{token}/status`    | Polls progress. Before complete has been called it returns a placeholder structure (with empty steps) rather than an error; once started it returns the same redacted step view that complete/retry produce.                                                    |

The `requiredInput` field in a failure response tells the customer what to do next: `authorization_code` means they need to go through Meta authorization again for a fresh code; `null` means they cannot recover on their own and should contact their account manager. **Onboarding success and credit line sharing are two independent states** — a credit line that has not synced will not cause onboarding to be reported as failed.
