# WhatsApp Integration Guide – Using Your Own Number with This Project

**Short answer:** Yes, you use **your own WhatsApp Business number** (or a dedicated number for your app). You register it with **Meta’s WhatsApp Cloud API** and connect that number to your Chat-Automation backend via credentials and a webhook. Your app then sends and receives messages through that number.

**Testing first:** You can test the full app **without** any real WhatsApp number, then add real WhatsApp credentials when ready. See [Section 0: Testing Without Real WhatsApp](#0-testing-without-real-whatsapp) below.

---

## 0. Testing Without Real WhatsApp

You can develop and test the project **without** configuring a real WhatsApp number or Meta token. When you’re ready for real messages, you add the real credentials (Section 7).

### Option A: This project’s built-in test mode (recommended for local dev)

**How it works:** If `META_ACCESS_TOKEN` or `META_PHONE_NUMBER_ID` are **not** set in `.env`, the backend does **not** call Meta. When you “send” a message from the inbox:

- The message is saved to your database (conversations, messages).
- Socket.io emits it so the UI updates in real time.
- The API responds with `testMode: true` and a fake message ID.

**What you can test:**

- Login, dashboard, contacts, conversations.
- Sending messages from the inbox (they appear in the UI and in DB).
- Real-time updates (if Socket is connected).
- No real WhatsApp number or Meta account needed.

**Setup:** Do **not** set (or remove) these from `backend/unified_server/.env`:

```env
# Leave these out or commented for test mode
# META_ACCESS_TOKEN=...
# META_PHONE_NUMBER_ID=...
```

**Incoming messages:** In test mode, Meta never calls your server, so you won’t receive real WhatsApp messages. To simulate incoming messages you can:

- Call your webhook POST with a fake payload (e.g. from Postman or a small script), or
- Insert test rows in the DB for conversations/messages.

When you’re ready for real WhatsApp, add the real token and Phone Number ID (Section 7).

---

### Option B: Meta’s test number (real API, limited use)

If you want to hit the **real** Meta API without verifying your own number first:

1. Create a Meta Developer app and add the **WhatsApp** product.
2. In the app’s WhatsApp section, Meta can provide a **test WhatsApp Business Account** and a **test phone number**.
3. You get a test **Phone Number ID** and a **temporary access token** in the dashboard.
4. You can send a pre-approved “hello world” template to **yourself** and to a small set of recipient numbers (e.g. up to 5), for testing.

**Limits:** Test numbers are for development only; recipient list and templates are restricted. When you’re ready for production, you add and verify your **own** number (Section 3) and switch to a permanent token.

---

### Option C: Local WhatsApp Cloud API emulator (advanced)

For local webhook and API simulation without Meta at all:

- **Package:** [@whatsapp-cloudapi/emulator](https://www.npmjs.com/package/@whatsapp-cloudapi/emulator) (npm).
- Runs a **mock** of the WhatsApp Cloud API and webhook events on your machine.
- Useful if you want to test webhook payload handling and status updates without Meta or a real number.

Your app would point to the emulator’s URL instead of Meta for the webhook and (if you mock send) for the send API.

---

### Local webhook test (Option A + manual POST, or before Option C)

To **test webhook/payload logic without Meta** (incoming message handling, DB save, Socket emit):

**Option A + manual POST (recommended, no extra deps)**

1. Start the backend: `cd backend/unified_server && npm run dev`.
2. In `.env`, set `DEFAULT_BUSINESS_ID` to a valid business UUID (so the webhook can attach the message to a business). Or leave unset to use the built-in fallback UUID if your DB has it.
3. Run the included script:
   ```bash
   cd backend/unified_server
   node scripts/test_webhook_incoming.js "Hello from local test"
   ```
4. Check backend logs for “Processing text message” / “Text message processed”, then the DB (`messages`, `webhook_logs`) and the Inbox UI (conversation for the sender number, e.g. 923001234567).

**Optional:** Postman/curl – POST to `http://localhost:5000/api/v1/webhooks/whatsapp` with a body like the one in `scripts/test_webhook_incoming.js` (object, entry, changes, value.messages, value.metadata).

**Option C – emulator**

- Install and run [@whatsapp-cloudapi/emulator](https://www.npmjs.com/package/@whatsapp-cloudapi/emulator) and point your app’s webhook config to the emulator’s URL so it receives simulated events.

---

### Option D: Third-party sandbox (e.g. Twilio)

Some providers offer a shared sandbox number (e.g. Twilio’s WhatsApp sandbox). You’d integrate their API instead of (or in addition to) Meta’s. Your **current** backend is built for **Meta’s** API; using Twilio would mean adding their client or switching send/webhook logic. Usually not needed if you only want to test now and add **real** WhatsApp (Meta) later.

---

### Summary: what to use when

| Goal | Use |
|------|-----|
| Test app flow (inbox, send, DB, UI) without any WhatsApp | **Option A** – leave Meta credentials unset (built-in test mode). |
| Test real Meta API with limited recipients | **Option B** – Meta test number + temporary token. |
| Test webhook/payload logic without Meta | **Option C** – local emulator, or Option A + manual POST to webhook. |
| Go live with your own number | **Section 7** – add your number, permanent token, and webhook in Meta; set `.env`. |

---

## 1. Do You Use Your Own WhatsApp?

| Question | Answer |
|----------|--------|
| **Use our own number?** | **Yes.** You need a phone number that you will use for WhatsApp Business API. It can be a new number or (in supported cases) an existing WhatsApp Business number. |
| **Who provides the API?** | **Meta (Facebook).** The official way is **WhatsApp Cloud API** (hosted by Meta). On-Premises API is being deprecated. |
| **Can each business use a different number?** | **Yes.** Your app supports multiple businesses; each can have its own number via the `integrations` + `api_keys` tables, or you can run with one number in `.env` for testing. |

**Number rules (Meta):**

- Must be able to receive **SMS or voice OTP** for verification.
- Must **not** be currently registered on the normal WhatsApp or WhatsApp Business app (or you use migration/coexistence if Meta allows it for your case).
- For production, the number is typically dedicated to your business/app.

---

## 2. High-Level Procedure

1. **Create Meta assets**  
   Meta Developer App → WhatsApp product → WhatsApp Business Account (WABA).

2. **Add and verify your phone number**  
   In the Meta App Dashboard (WhatsApp → Configuration), add the number and verify it (SMS/voice OTP). You get a **Phone Number ID**.

3. **Get a permanent access token**  
   Create a System User in Meta Business Manager, assign WhatsApp permissions, generate a token. Store it in your backend only (e.g. `.env` or per-business in DB).

4. **Expose a public webhook URL**  
   Your backend must expose **HTTPS** endpoints for:
   - **GET** (verification): Meta sends `hub.mode`, `hub.verify_token`, `hub.challenge`; you respond with the challenge.
   - **POST** (incoming messages): Meta sends message/status updates; you process and respond with 200.

5. **Register webhook in Meta**  
   In App Dashboard → WhatsApp → Configuration, set your webhook URL and verify token. Subscribe to **messages** (and optionally message status).

6. **Configure your backend**  
   Set environment variables (or per-business credentials) so your app uses the correct **Phone Number ID** and **Access Token** when calling Meta and when receiving webhooks.

7. **Send messages**  
   Use Meta’s Graph API (or SDK) to send text, templates, or media from your backend using that number.

Your **Chat-Automation** project already has the webhook and send logic; you only need to complete Meta setup and credentials.

---

## 3. Step-by-Step (Tied to This Project)

### Step 1: Meta for Developers

1. Go to [developers.facebook.com](https://developers.facebook.com).
2. Create or select a **Business**-type app.
3. Add the **WhatsApp** product to the app.
4. You will have (or create) a **WhatsApp Business Account** (WABA) linked to a **Meta Business Manager**.

### Step 2: Business verification (for production)

- In **Meta Business Manager** → **Business Settings** → **Security Center**, submit business documents if required.
- For testing, you can often use the app in “development” with a test number; for production and your own number, verification is usually required.

### Step 3: Add and verify your phone number

1. In your app: **App Dashboard** → **WhatsApp** → **Configuration** (or **API Setup**).
2. Click **Add phone number** (or use the number section).
3. Enter the number; choose **SMS** or **Voice** for OTP.
4. Complete verification. Meta will show:
   - **Phone Number ID** (e.g. `985711124626285`) – **you need this**.
   - **WhatsApp Business Account ID** (WABA ID) – useful for some APIs.

Save the **Phone Number ID**; your backend will use it for sending and (via webhook) for receiving.

### Step 4: Permanent access token

1. **Meta Business Manager** → **Business Settings** → **Users** → **System Users**.
2. Create a system user (e.g. “WhatsApp API”).
3. **Assign assets**: add your **App** and give it **WhatsApp** permissions (e.g. `whatsapp_business_management`, `whatsapp_business_messaging`).
4. **Generate token**: create a token for that system user, select the app, choose the WhatsApp permissions, then generate. Copy the token **once** and store it securely (e.g. in `.env`); it may not be shown again.

Never put this token in frontend or public repos.

### Step 5: Webhook URL (HTTPS)

Your backend already has:

- **GET** `/api/v1/webhooks/whatsapp` – verification.
- **POST** `/api/v1/webhooks/whatsapp` – incoming messages.

So you need a **public HTTPS** URL that points to your server, for example:

- Production: `https://yourdomain.com/api/v1/webhooks/whatsapp`
- Local testing: use **ngrok** (or similar):  
  `ngrok http 5000` → use the HTTPS URL ngrok gives you, e.g.  
  `https://abc123.ngrok.io/api/v1/webhooks/whatsapp`

**Do I need to add a URL when on local?**

- **If you’re only using test mode** (no Meta credentials): **No.** You don’t add any URL in the WhatsApp/Meta API. Your app never talks to Meta.
- **If you want to receive real WhatsApp messages while running on localhost**: **Yes.** Meta can’t reach `http://localhost:5000`. You must expose your local server with a tunnel (e.g. run `ngrok http 5000`) and then in the Meta App Dashboard → WhatsApp → Configuration → Webhook, set the **Callback URL** to your ngrok HTTPS URL, e.g. `https://abc123.ngrok.io/api/v1/webhooks/whatsapp`. After that, Meta can deliver incoming messages to your local app. (Each time you restart ngrok the URL may change, so you’d need to update it in Meta or use a fixed ngrok domain if you have one.)

### Step 6: Register webhook in Meta

1. In **App Dashboard** → **WhatsApp** → **Configuration**.
2. Under **Webhook**, click **Edit**.
3. **Callback URL**: your HTTPS URL (e.g. `https://yourdomain.com/api/v1/webhooks/whatsapp` or your ngrok URL).
4. **Verify token**: set a secret string (e.g. `SajjadAhmad123`). It must **exactly** match what your backend expects.
5. Click **Verify and save**. Meta will send a GET request; your backend must respond with the `hub.challenge` value (your code already does this if the token matches).
6. Subscribe to **messages** (and optionally **message status**).

Your backend uses:

```env
META_WEBHOOK_VERIFY_TOKEN=SajjadAhmad123
```

So the value in Meta must be the same.

### Step 7: Configure environment variables (this project)

In `backend/unified_server/.env` (or your deployment env) set **one** of these naming styles. Never commit `.env` to git.

**Option A – preferred names:**

```env
META_WEBHOOK_VERIFY_TOKEN=YourSecretVerifyToken
META_ACCESS_TOKEN=your_permanent_access_token_from_step_4
META_PHONE_NUMBER_ID=your_phone_number_id_from_meta_dashboard
META_API_VERSION=v21.0
```

**Option B – alternative names (also supported):**

```env
WEBHOOK_VERIFY_TOKEN=YourSecretVerifyToken
GRAPH_API_TOKEN=your_permanent_access_token_from_step_4
META_PHONE_NUMBER_ID=your_phone_number_id_from_meta_dashboard
META_API_VERSION=v21.0
```

- **Verify token** – Must match exactly what you set in Meta App Dashboard → WhatsApp → Webhook (e.g. `AfsaraliKhan`).
- **Access token** – From Step 4 (System User token) or from your Meta app; used for Graph API and webhook media download.
- **META_PHONE_NUMBER_ID** – From Meta App Dashboard → WhatsApp → API Setup / Configuration. Required for **sending** messages; without it the app runs in test mode (messages saved to DB only).
- **META_API_VERSION** – e.g. `v21.0` or `v25.0`.

Your code already uses these (see `webhook.controller.js` and `messageOutbound.controller.js`). Optionally you can later store per-business tokens in `integrations` / `api_keys` and the code will prefer those over env.

### Step 8: Test receiving and sending

1. **Receive:** From Meta Dashboard you can send a test message to your number, or have someone WhatsApp that number. Your webhook POST should get the payload; check server logs and DB (e.g. `webhook_logs`, `messages`).
2. **Send:** Use your app’s “send message” (e.g. from the inbox). Your backend calls Meta’s `POST /v21.0/{PHONE_NUMBER_ID}/messages` with the token. Check that the message is delivered on WhatsApp.

---

## 4. How This Project Uses It

| Piece | Role |
|-------|------|
| **Your WhatsApp number** | Registered in Meta; gives you **Phone Number ID**. All messages sent by the app go from this number; all messages to this number can be received via webhook. |
| **Webhook (GET)** | Meta verifies your URL; you return `hub.challenge`. |
| **Webhook (POST)** | Meta sends incoming messages; you save to DB, optionally run automation/AI, and can reply via the send API. |
| **Send API** | Your backend calls Meta Graph API with `META_ACCESS_TOKEN` and `META_PHONE_NUMBER_ID` (or per-business credentials from DB). |
| **Multi-business** | Each business can have its own number by storing `access_token` and `phone_number_id` in `integrations` / `api_keys`; the outbound controller already supports that. |

---

## 5. Templates and policies (sending to users who didn’t message first)

- **Within 24 hours** of a user’s last message: you can send free-form text (and optionally templates).
- **After 24 hours**: you must use **approved message templates** for the first message; then you can send normal messages again in that conversation.
- Create and submit templates in **WhatsApp Manager** (or via API); wait for approval before using them in production.

---

## 6. Checklist

- [ ] Meta Developer App created; WhatsApp product added.
- [ ] WhatsApp Business Account (WABA) created/linked.
- [ ] Your phone number added and verified; **Phone Number ID** saved.
- [ ] System User created; **permanent access token** generated and stored in backend env.
- [ ] Backend running with **HTTPS** webhook URL (or ngrok for local).
- [ ] Webhook URL and **verify token** set in Meta; verification successful.
- [ ] Subscribed to **messages** (and optionally **message status**).
- [ ] `.env` has `META_WEBHOOK_VERIFY_TOKEN`, `META_ACCESS_TOKEN`, `META_PHONE_NUMBER_ID`, `META_API_VERSION`.
- [ ] Test: receive a message (see it in logs/DB) and send a reply from your app.

---

## 7. References (web)

- [Meta WhatsApp Cloud API – Overview](https://developers.facebook.com/docs/whatsapp/cloud-api)
- [WhatsApp Business API registration and setup (e.g. Bol7, WhatsBizAPI)](https://www.bol7.com/blog-details/whatsapp-business-api-registration-setup/)
- [Direct integration with Meta (DevOpsSchool)](https://www.devopsschool.com/blog/whatsapp-cloud-api-direct-integration-with-meta/)
- Your project: `POSTMAN_WHATSAPP_TESTS.md`, `sprint-2-testing-guide.md` for request examples.

---

*Summary: You use your own WhatsApp Business number, register it in Meta’s WhatsApp Cloud API, get a Phone Number ID and access token, point Meta’s webhook to your backend, and set the same credentials in this project’s env. The app already has the webhook and send logic; you only complete the Meta setup and configuration.*
