# WhatsApp Embedded Signup — Implementation Guide

This document explains how **WhatsApp Embedded Signup (login)** is implemented in this
project, which Meta/Facebook permissions (scopes) are required, the full request flow,
and the exact steps to port the same functionality into another Laravel project.

> Embedded Signup lets a client connect their own WhatsApp Business Account (WABA) and
> phone number to the platform with a single "Connect WhatsApp" button — no manual
> copy/pasting of access tokens, phone number IDs, or WABA IDs. Meta's JS SDK pops up a
> guided flow, returns a short-lived `code`, and the backend exchanges it for an access
> token and auto-configures the webhook + templates.

---

## 1. Where the code lives

The whole feature is a self-contained addon under [`app/Addons/EmbeddedSignup/`](app/Addons/EmbeddedSignup/):

| File | Responsibility |
|------|----------------|
| [`EmbeddedSignupAddon.php`](app/Addons/EmbeddedSignup/EmbeddedSignupAddon.php) | Addon bootstrap — registers views & routes |
| [`config.json`](app/Addons/EmbeddedSignup/config.json) | Addon manifest (`addon_identifier: embedded_signup`) |
| [`routes.php`](app/Addons/EmbeddedSignup/routes.php) | Client-side routes (connect / store / sync / delete / profile) |
| [`Controllers/EmbeddedSignupController.php`](app/Addons/EmbeddedSignup/Controllers/EmbeddedSignupController.php) | Thin controller, demo-mode guard, delegates to repo |
| [`Repository/EmbeddedSignupRepository.php`](app/Addons/EmbeddedSignup/Repository/EmbeddedSignupRepository.php) | Core logic: token exchange, validation, persist, profile sync |
| [`views/index.blade.php`](app/Addons/EmbeddedSignup/views/index.blade.php) | The connect page + **Facebook JS SDK + `FB.login` flow** |
| `views/partials/*` | Business-profile card, update-profile modal, common-issues modal |

Shared (non-addon) dependencies it relies on:

| File | Responsibility |
|------|----------------|
| [`app/Services/MetaService.php`](app/Services/MetaService.php) | All Graph API calls (phone numbers, profile, subscribe app, webhook override, register number) |
| [`resources/views/backend/admin/system_setting/whatsapp_api.blade.php`](resources/views/backend/admin/system_setting/whatsapp_api.blade.php) | Admin screen to enter Meta App ID / Secret / Configuration ID / status |
| [`routes/web.php`](routes/web.php) | WhatsApp webhook endpoints (`whatsapp.webhook`, `webhook.whatsapp-webhook`) |

---

## 2. Meta App prerequisites & permissions (scopes)

### Permissions requested during login

The `FB.login()` call requests these **scopes** (see [`index.blade.php:246`](app/Addons/EmbeddedSignup/views/index.blade.php#L246)):

```js
scope: "business_management, whatsapp_business_management, whatsapp_business_messaging"
```

| Scope | Why it's needed |
|-------|-----------------|
| `business_management` | Read/manage the user's Meta Business portfolio (the WABA lives under a business) |
| `whatsapp_business_management` | Manage the WABA: read phone numbers, account review status, business profile, subscribe the app, override the webhook callback URL, register the number |
| `whatsapp_business_messaging` | Send/receive WhatsApp messages on behalf of the connected number |

### Meta App configuration needed (one-time, in Meta App Dashboard)

1. A **Meta App** of type *Business* with the **WhatsApp** product added.
2. **Facebook Login for Business** product added, with an **Embedded Signup Configuration**
   → this generates the **Configuration ID** used as `config_id`.
3. App must be **Live** (and the relevant permissions Advanced-Access approved) for
   external clients to use it; in Dev mode only app roles can connect.
4. The platform domain added to **Allowed Domains for the JavaScript SDK**.
5. A **Privacy Policy** and **Terms** URL (the app exposes `page/privacy-policy` and
   `page/terms-and-conditions`).

### App credentials stored in the platform (admin settings)

Entered by the admin on the *WhatsApp API Setup* screen and read via the `setting()` helper:

| Setting key | Used as | Read in |
|-------------|---------|---------|
| `meta_app_id` | FB SDK `appId` + OAuth `client_id` | view + repo |
| `meta_app_secret` | OAuth `client_secret` + app access token | repo |
| `meta_configuration_id` | `FB.login` `config_id` (the Embedded Signup config) | view |
| `meta_app_name` | display only | admin view |
| `meta_access_token` | system token (other features) | admin view |
| `is_embedded_signup_active` | feature toggle | admin view |
| `webhook_verify_token` | webhook verify token | webhook |

App access token used for token debugging is built as `meta_app_id|meta_app_secret`
(see [`EmbeddedSignupRepository.php:173`](app/Addons/EmbeddedSignup/Repository/EmbeddedSignupRepository.php#L173)).

### Application-level permissions & access control

Creating a new WhatsApp account via embedded signup works end-to-end only after these
**in-app permission gates** all pass. Replicate every layer in the target project:

| Layer | Where | What it enforces |
|-------|-------|------------------|
| **Addon activation gate** | Controller constructor — `if (!addon_is_activated('embedded_signup')) abort(403)` ([EmbeddedSignupController.php:15](app/Addons/EmbeddedSignup/Controllers/EmbeddedSignupController.php#L15)) | Every action 403s unless the `embedded_signup` addon is installed/active |
| **Admin feature toggle** | `setting('is_embedded_signup_active')` + `addon_is_activated('embedded_signup')` checked in the connect view ([index.blade.php:13](app/Addons/EmbeddedSignup/views/index.blade.php#L13)) | The "Connect WhatsApp" button only renders when the feature is on *and* no number is already connected |
| **Route middleware** | `['web', 'auth', 'verified', 'subscriptionCheck']` ([routes.php:5](app/Addons/EmbeddedSignup/routes.php#L5)) | User must be logged in, email-verified, and on an active subscription |
| **Multi-tenant data scope** | `ClientSetting::scopeWithPermission()` ([ClientSetting.php:57](app/Models/ClientSetting.php#L57)) | Non-admin users are restricted to `where('client_id', $client->id)` — a client can only sync/delete/edit **their own** connection; admin sees all. Used in `find()`, `delete()` |
| **Demo-mode guard** | `isDemoMode()` in every write action (store/sync/delete/updateBusinessProfile) | Blocks all mutations on demo servers with a friendly message |
| **Authenticated client resolution** | `Auth::user()->client` in `store()` | The connection is always bound to the logged-in user's client; aborts if no client |

### Meta permission data captured & stored

When the token is validated via `/debug_token`, the **granted permissions** are returned
and persisted on the `client_settings` row (see `extractTokenData()`):

| Column | Source (from `debug_token`) | Meaning |
|--------|-----------------------------|---------|
| `scopes` | `data.scopes` | Flat list of granted permissions (e.g. `whatsapp_business_management`, `whatsapp_business_messaging`, `business_management`) |
| `granular_scopes` | `data.granular_scopes` | Per-permission → target IDs map (which WABAs/businesses each scope applies to) |
| `token_verified` | set `true` after `is_valid` passes | Marks the token as validated |
| `data_access_expires_at` / `expires_at` | `data.*` timestamps | When the granted access/token expires |
| `fb_user_id` | `data.user_id` | The Facebook user who granted the permissions |

These let you later confirm a connection still holds the required permissions without
re-prompting, and detect upcoming expiry.

### Permissions auto-applied to Meta after connect

Beyond *requesting* scopes in the popup, the backend **exercises** the granted
permissions immediately to provision the number (all require the scopes from the table
above):

1. **Subscribe the app to the WABA** — `POST /{waba_id}/subscribed_apps`
   (`subscribeApps`) — needs `whatsapp_business_management`.
2. **Override the webhook callback URL** per client — `POST /{waba_id}/subscribed_apps`
   with `override_callback_uri` + `verify_token` (`overrideCallbackURL`).
3. **Register the phone number** — `POST /{phone_number_id}/register`
   (`registerNumber`) — needs `whatsapp_business_management`.
4. On **delete**, the app **unsubscribes** from the WABA — `DELETE /{waba_id}/subscribed_apps`
   (`unSubscribeApps`).

---

## 3. Frontend flow (the "login")

File: [`views/index.blade.php`](app/Addons/EmbeddedSignup/views/index.blade.php)

1. **Load the Facebook JS SDK** (async, `v20.0`) and init it with the app id:
   ```js
   window.fbAsyncInit = function() {
       FB.init({ appId: "{{ setting('meta_app_id') }}", autoLogAppEvents: true, xfbml: true, version: 'v20.0' });
   };
   ```
   SDK script: `https://connect.facebook.net/en_US/sdk.js`.

2. **Listen for the Embedded Signup `postMessage`** from Facebook. When the user finishes
   the popup, Facebook posts `WA_EMBEDDED_SIGNUP` events. On `FINISH` we capture:
   ```js
   signupData = {
       phone_number_id:    data.data.phone_number_id,
       business_account_id: data.data.waba_id,
       app_id:             data.data.app_id,
       access_token:       data.code   // (overwritten by the real code below)
   };
   ```
   `CANCEL` / `ERROR` events show a toast/swal and re-enable the button.

3. **`launchWhatsAppSignup()`** (the button's `onclick`) validates that
   `meta_configuration_id` and `meta_app_id` exist, then calls:
   ```js
   FB.login(fbLoginCallback, {
       config_id: metaConfigurationId,   // Embedded Signup configuration
       response_type: 'code',            // return an auth CODE (not a token)
       scope: "business_management, whatsapp_business_management, whatsapp_business_messaging",
       override_default_response_type: true,
       extras: { setup: {}, featureType: '', sessionInfoVersion: '3' }
   });
   ```

4. **`fbLoginCallback(response)`** reads `response.authResponse.code`, merges it with the
   `signupData` captured from the postMessage, and POSTs to the backend:
   ```js
   const requestData = {
       phone_number_id:    signupData.phone_number_id,
       business_account_id: signupData.business_account_id,
       app_id:             signupData.app_id,
       code:               code,        // short-lived OAuth code
   };
   axios.post("{{ route('client.whatsapp.embedded-signup.store') }}", requestData, { headers: { 'X-CSRF-TOKEN': ... } })
   ```
   On success it swaps the connect block for the business-profile card and fires a confetti
   effect. No page reload is required.

> **Key idea:** the browser never sees a long-lived token. It only forwards the WABA id,
> phone number id, app id, and a one-time `code`. The token exchange happens server-side.

---

## 4. Backend flow (token exchange + provisioning)

Entry point: `EmbeddedSignupController@store` → `EmbeddedSignupRepository::store()`
([repo](app/Addons/EmbeddedSignup/Repository/EmbeddedSignupRepository.php#L54)).

1. **Exchange the code for an access token** — `getAccessClient()`:
   `GET https://graph.facebook.com/v20.0/oauth/access_token?client_id={meta_app_id}&client_secret={meta_app_secret}&code={code}`
   → returns `access_token`.

2. **Validate / debug the token** — `validateAccessToken()`:
   `GET /debug_token?input_token={access_token}&access_token={app_id|app_secret}`
   → confirms `is_valid` and returns `scopes`, `granular_scopes`, `expires_at`,
   `data_access_expires_at`, `app_id`, `user_id`.

3. **Persist the connection** — `extractTokenData()` builds the row and saves it to
   `ClientSetting` (`firstOrNew` keyed by `client_id` + `phone_number_id`). Stored fields:
   `access_token`, `phone_number_id`, `business_account_id`, `app_id`, `is_connected`,
   `token_verified`, `scopes`, `granular_scopes`, `data_access_expires_at`, `expires_at`,
   `fb_user_id`, `name`.

4. **Fetch & store phone + business profile** — `createPhoneAndBusinessProfile()` calls
   `MetaService` for each phone number under the WABA and writes a `ClientSettingDetail`
   row (verified name, display number, quality rating, review status, number status, code
   verification status, certificates, messaging-limit tier, and a `profile_info` JSON blob
   with address/email/description/vertical/about/websites/picture). It also:
   - **registers the number** (`/{phone_number_id}/register`, pin `123456`),
   - **subscribes the app to the WABA** (`/{waba_id}/subscribed_apps`).

5. **Override the webhook callback URL** so messages route to this platform per-client:
   ```php
   $callbackUri = route('whatsapp.webhook', $client->webhook_verify_token);
   $this->metaService->overrideCallbackURL($waba_id, $callbackUri, $verifyToken, $clientSetting);
   ```
   (`POST /{waba_id}/subscribed_apps` with `override_callback_uri` + `verify_token`.)

6. **Sync message templates** — `syncTemplate()` (from `TemplateTrait`) pulls the WABA's
   approved templates into the local `templates` table.

7. Returns the rendered business-profile card HTML to the frontend.

### Sync & delete

- **`sync()`** — re-validates the stored token and refreshes phone/profile/template data
  for an already-connected number.
- **`delete($id)`** — unsubscribes the app from the WABA (`unSubscribeApps`), deletes the
  `ClientSetting` row and that setting's templates.

---

## 5. Graph API endpoints used (`MetaService`)

All go through `makeFacebookApiRequest()` with `Authorization: Bearer {access_token}`,
base `https://graph.facebook.com/v20.0`:

| Method | Endpoint | Purpose |
|--------|----------|---------|
| GET | `/{waba_id}/phone_numbers` | list phone numbers + quality/limits |
| GET | `/{phone_number_id}` (`status,code_verification_status,...`) | phone status |
| GET | `/{phone_number_id}/whatsapp_business_profile` | read business profile |
| POST | `/{phone_number_id}/whatsapp_business_profile` | update business profile |
| GET | `/{waba_id}` (`account_review_status`) | WABA review status |
| GET | `/{waba_id}` (`id,name,timezone_id`) | WABA account info |
| POST | `/{waba_id}/subscribed_apps` | subscribe app / override callback URL |
| DELETE | `/{waba_id}/subscribed_apps` | unsubscribe app (on delete) |
| POST | `/{phone_number_id}/register` | register number (pin) |
| POST | `/{phone_number_id}/deregister` | deregister number |
| GET | `/oauth/access_token` | exchange `code` → token |
| GET | `/debug_token` | validate token + read scopes |

---

## 6. Routes

From [`app/Addons/EmbeddedSignup/routes.php`](app/Addons/EmbeddedSignup/routes.php)
(group: `/{locale}/client`, middleware `web, auth, verified, subscriptionCheck`):

```
GET  whatsapp/embedded-signup                 → index           (client.whatsapp.embedded-signup)
POST whatsapp/embedded-signup/store           → store           (.store)
GET  whatsapp/embedded-signup/access-token     → getAccessClient (.access-token)
GET  whatsapp/embedded-signup/sync/{id}        → sync            (.sync)
GET  whatsapp/embedded-signup/delete/{id}      → delete          (.delete)
GET  whatsapp/profile/edit/{id}                → getBusinessProfileDetails (client.whatsapp.profile.edit)
POST whatsapp/profile/update/{id}              → updateBusinessProfile      (client.whatsapp.profile.update)
```

Webhook endpoints (in [`routes/web.php`](routes/web.php)) that the overridden callback URL points to:

```
GET/POST whatsapp/webhook/{token}     → whatsapp.verify.token / whatsapp.webhook
ANY      webhook/whatsapp-webhook     → webhook.whatsapp-webhook   (shown in admin as the callback URL)
```

---

## 7. Database touch-points

- **`client_settings`** — one row per connected number. Key columns written by this flow:
  `client_id`, `type` (whatsapp), `access_token`, `phone_number_id`, `business_account_id`,
  `app_id`, `is_connected`, `token_verified`, `scopes`, `granular_scopes`,
  `data_access_expires_at`, `expires_at`, `fb_user_id`, `name`, `business_account_name`, `status`.
- **`client_setting_details`** — per phone number metadata + `profile_info` JSON.
- **`templates`** — synced WhatsApp templates (linked by `client_setting_id`).
- **settings table** — admin Meta credentials (`meta_app_id`, `meta_app_secret`,
  `meta_configuration_id`, `meta_app_name`, `webhook_verify_token`, `is_embedded_signup_active`).

---

## 8. How to port this to another Laravel project

1. **Copy the addon folder** `app/Addons/EmbeddedSignup/` (or, if the target has no addon
   system, copy the Controller + Repository + Blade view into normal app folders and
   register the routes manually).

2. **Copy / merge `app/Services/MetaService.php`** — this is the Graph API layer the
   repository depends on. It uses a global `curlRequest($url, $data, $method, $headers)`
   helper and `logError`/`logInfo` helpers — copy those too (see `app/Helpers/Helper.php`)
   or replace with `Illuminate\Support\Facades\Http`.

3. **Provide the models** the repository type-hints: `Client`, `ClientSetting`,
   `ClientSettingDetail`, `Template`. Ensure `client_settings` / `client_setting_details`
   have the columns listed in §7 (add a migration if needed). `ClientSetting` should cast
   `granular_scopes` / `profile_info` to array/json.

4. **Provide the traits** used: `ImageTrait`, `RepoResponse` (the `formatResponse()` helper),
   `TemplateTrait` (the `syncTemplate()` method). If you don't need template sync, stub
   `syncTemplate()` out.

5. **Register the routes** (the 7 routes in §6) and make sure the `whatsapp.webhook`
   named route exists (the callback-URL override depends on it), plus a webhook controller
   that verifies the `webhook_verify_token`.

6. **Add the admin settings** (`meta_app_id`, `meta_app_secret`, `meta_configuration_id`,
   `webhook_verify_token`, and a feature toggle). Reuse the `setting()` helper or hard-code
   from `.env`. Optional env: `FACEBOOK_BASE_URL`, `META_API_VERSION` (default `v20.0`).

7. **Front-end**: include the connect button + the `<script>` block from
   [`index.blade.php`](app/Addons/EmbeddedSignup/views/index.blade.php) (FB SDK init,
   `launchWhatsAppSignup`, `fbLoginCallback`, and the `WA_EMBEDDED_SIGNUP` message
   listener). It depends on jQuery, axios, toastr, SweetAlert (`Swal`), and (optional)
   canvas-confetti. Make sure the route URL and CSRF token in the script point to your
   project's `store` route.

8. **On the Meta side** (per §2): create the Business app, add WhatsApp + Facebook Login
   for Business, create an Embedded Signup **Configuration**, copy the **App ID / Secret /
   Configuration ID** into your settings, whitelist your domain for the JS SDK, and
   request Advanced Access for `business_management`, `whatsapp_business_management`,
   `whatsapp_business_messaging`. Set the app **Live**.

---

## 9. Quick checklist (permissions & config to replicate)

- [ ] FB.login scopes: `business_management`, `whatsapp_business_management`, `whatsapp_business_messaging`
- [ ] `response_type: 'code'` + `override_default_response_type: true`
- [ ] `config_id` = Embedded Signup Configuration ID (`meta_configuration_id`)
- [ ] FB SDK `appId` = `meta_app_id`, version `v20.0`
- [ ] Server token exchange via `/oauth/access_token` (client_id + client_secret + code)
- [ ] Token validation via `/debug_token` (app access token = `app_id|app_secret`)
- [ ] Register number + subscribe app + override webhook callback URL after connect
- [ ] Webhook verify token wired into `whatsapp.webhook` route
- [ ] Admin Meta credentials + domain whitelisting + Advanced Access approved
- [ ] Addon activation gate (`addon_is_activated('embedded_signup')` → 403) on every action
- [ ] Feature toggle `is_embedded_signup_active` gating the connect button
- [ ] Route middleware: `web`, `auth`, `verified`, `subscriptionCheck`
- [ ] Multi-tenant `withPermission()` scope so a client only touches its own connection
- [ ] Demo-mode guard on all write actions
- [ ] Persist granted permissions: `scopes`, `granular_scopes`, `token_verified`, expiry columns
- [ ] After connect: subscribe app + override webhook + register number (uses granted scopes)

---

### Reference

- Meta docs: <https://developers.facebook.com/docs/whatsapp/embedded-signup>
- API version used here: **Graph API v20.0** (configurable via `META_API_VERSION`).
