# WhatsApp Master Account Setup Guide

**Quick Setup Guide for Platform Admin**

This guide walks you through setting up the Master WhatsApp Business Account for the bakery-ia pilot program.

---

## Prerequisites

- [ ] Meta/Facebook Business account
- [ ] Business verification documents (tax ID, business registration)
- [ ] 10 phone numbers for pilot bakeries
- [ ] Credit card for WhatsApp Business API billing

**Time Required:** 2-3 hours (including verification wait time)

---

## Step 1: Create Meta Business Account

### 1.1 Create Business Manager

1. Go to [Meta Business Suite](https://business.facebook.com)
2. Click **Create Account**
3. Enter business details:
   - Business Name: "Bakery Platform" (or your company name)
   - Your Name
   - Business Email
4. Click **Submit**

### 1.2 Verify Your Business

Meta requires business verification for WhatsApp API access:

1. In Business Settings → **Security Center**
2. Click **Start Verification**
3. Choose verification method:
   - **Business Documents** (Recommended)
     - Upload tax registration document
     - Upload business license or registration
   - **Domain Verification**
     - Add DNS TXT record to your domain
   - **Phone Verification**
     - Receive call/SMS to business phone

4. Wait for verification (typically 1-3 business days)

**Status Check:**
```
Business Settings → Security Center → Verification Status
```

---

## Step 2: Add WhatsApp Product

### 2.1 Enable WhatsApp

1. In Business Manager, go to **Settings**
2. Click **Accounts** → **WhatsApp Accounts**
3. Click **Add** → **Create a new WhatsApp Business Account**
4. Fill in details:
   - Display Name: "Bakery Platform"
   - Category: Food & Beverage
   - Description: "Bakery management notifications"
5. Click **Create**

### 2.2 Configure WhatsApp Business Account

1. After creation, note your **WhatsApp Business Account ID (WABA ID)**
   - Found in: WhatsApp Manager → Settings → Business Info
   - Format: `987654321098765` (15 digits)
   - **Save this:** You'll need it for environment variables

---

## Step 3: Add Phone Numbers

### 3.1 Add Your First Phone Number

**Option A: Use Your Own Phone Number** (Recommended for testing)

1. In WhatsApp Manager → **Phone Numbers**
2. Click **Add Phone Number**
3. Enter phone number in E.164 format: `+34612345678`
4. Choose verification method:
   - **SMS** (easiest)
   - **Voice call**
5. Enter verification code
6. Note the **Phone Number ID**:
   - Format: `123456789012345` (15 digits)
   - **Save this:** Default phone number for environment variables

**Option B: Use Meta-Provided Free Number**

1. In WhatsApp Manager → **Phone Numbers**
2. Click **Get a free phone number**
3. Choose country: Spain (+34)
4. Meta assigns a number in format: `+1555XXXXXXX`
5. Note: Free numbers have limitations:
   - Can't be ported to other accounts
   - Limited to 1,000 conversations/day
   - Good for pilot, not production

### 3.2 Add Additional Phone Numbers (For Pilot Bakeries)

Repeat the process to add 10 phone numbers total (one per bakery).

**Tips:**
- Use virtual phone number services (Twilio, Plivo, etc.)
- Cost: ~€5-10/month per number
- Alternative: Request Meta phone numbers (via support ticket)

**Request Phone Number Limit Increase:**

If you need more than 2 phone numbers:

1. Open support ticket at [WhatsApp Business Support](https://business.whatsapp.com/support)
2. Request: "Increase phone number limit to 10 for pilot program"
3. Provide business justification
4. Wait 1-2 days for approval

---

## Step 4: Create System User & Access Token

### 4.1 Create System User

**Why:** System Users provide permanent access tokens (don't expire every 60 days).

1. In Business Settings → **Users** → **System Users**
2. Click **Add**
3. Enter details:
   - Name: "WhatsApp API Service"
   - Role: **Admin**
4. Click **Create System User**

### 4.2 Generate Access Token

1. Select the system user you just created
2. Click **Add Assets**
3. Choose **WhatsApp Accounts**
4. Select your WhatsApp Business Account
5. Grant permissions:
   - ✅ Manage WhatsApp Business Account
   - ✅ Manage WhatsApp Business Messaging
   - ✅ Read WhatsApp Business Insights
6. Click **Generate New Token**
7. Select token permissions:
   - ✅ `whatsapp_business_management`
   - ✅ `whatsapp_business_messaging`
8. Click **Generate Token**
9. **IMPORTANT:** Copy the token immediately
   - Format: `EAAxxxxxxxxxxxxxxxxxxxxxxxx` (long string)
   - **Save this securely:** You can't view it again!

**Token Security:**
```bash
# Good: Use environment variable
WHATSAPP_ACCESS_TOKEN=EAAxxxxxxxxxxxxx

# Bad: Hardcode in source code
# token = "EAAxxxxxxxxxxxxx"  # DON'T DO THIS!
```

---

## Step 5: Create Message Templates

WhatsApp requires pre-approved templates for business-initiated messages.

### 5.1 Create PO Notification Template

1. In WhatsApp Manager → **Message Templates**
2. Click **Create Template**
3. Fill in template details:

```
Template Name:       po_notification
Category:            UTILITY
Languages:           Spanish (es)

Message Body:
Hola {{1}}, has recibido una nueva orden de compra {{2}} por un total de {{3}}.

Parameters:
1. Supplier Name (text)
2. PO Number (text)
3. Total Amount (text)

Example:
Hola Juan García, has recibido una nueva orden de compra PO-12345 por un total de €250.50.
```

4. Click **Submit for Approval**

**Approval Time:**
- Typical: 15 minutes to 2 hours
- Complex templates: Up to 24 hours
- If rejected: Review feedback and resubmit

### 5.2 Check Template Status

**Via UI:**
```
WhatsApp Manager → Message Templates → Filter by Status
```

**Via API:**
```bash
curl "https://graph.facebook.com/v18.0/{WABA_ID}/message_templates?fields=name,status,language" \
  -H "Authorization: Bearer {ACCESS_TOKEN}" | jq
```

**Template Statuses:**
- `PENDING` - Under review
- `APPROVED` - Ready to use
- `REJECTED` - Review feedback and fix
- `DISABLED` - Paused due to quality issues

### 5.3 Create Additional Templates (Optional)

For inventory alerts, production alerts, etc.:

```
Template Name:       low_stock_alert
Category:            UTILITY
Language:            Spanish (es)
Message:
⚠️ Alerta: El ingrediente {{1}} tiene stock bajo.
Cantidad actual: {{2}} {{3}}.
Punto de reorden: {{4}} {{5}}.
```

---

## Step 6: Configure Webhooks (For Status Updates)

### 6.1 Create Webhook Endpoint

Webhooks notify you of message delivery status, read receipts, etc.

**Your webhook endpoint:**
```
https://your-domain.com/api/v1/whatsapp/webhook
```

**Implemented in:** `services/notification/app/api/whatsapp_webhooks.py`

### 6.2 Register Webhook with Meta

1. In WhatsApp Manager → **Configuration**
2. Click **Edit** next to Webhook
3. Enter details:
   ```
   Callback URL:     https://your-domain.com/api/v1/whatsapp/webhook
   Verify Token:     random-secret-token-here
   ```
4. Click **Verify and Save**

**Meta will send GET request to verify:**
```
GET /api/v1/whatsapp/webhook?hub.verify_token=YOUR_TOKEN&hub.challenge=XXXXX
```

**Your endpoint must respond with:** `hub.challenge` value

### 6.3 Subscribe to Webhook Events

Select events to receive:

- ✅ `messages` - Incoming messages (for replies)
- ✅ `message_status` - Delivery, read receipts
- ✅ `message_echoes` - Sent message confirmations

**Environment Variable:**
```bash
WHATSAPP_WEBHOOK_VERIFY_TOKEN=random-secret-token-here
```

---

## Step 7: Configure Environment Variables

### 7.1 Collect All Credentials

You should now have:

1. ✅ **WhatsApp Business Account ID (WABA ID)**
   - Example: `987654321098765`
   - Where: WhatsApp Manager → Settings → Business Info

2. ✅ **Access Token**
   - Example: `EAAxxxxxxxxxxxxxxxxxxxxxxxx`
   - Where: System User token you generated

3. ✅ **Phone Number ID** (default/fallback)
   - Example: `123456789012345`
   - Where: WhatsApp Manager → Phone Numbers

4. ✅ **Webhook Verify Token** (you chose this)
   - Example: `my-secret-webhook-token-12345`

### 7.2 Update Notification Service Environment

**File:** `services/notification/.env`

```bash
# ================================================================
# WhatsApp Business Cloud API Configuration
# ================================================================

# Master WhatsApp Business Account ID (15 digits)
WHATSAPP_BUSINESS_ACCOUNT_ID=987654321098765

# System User Access Token (starts with EAA)
WHATSAPP_ACCESS_TOKEN=EAAxxxxxxxxxxxxxxxxxxxxxxxx

# Default Phone Number ID (15 digits) - fallback if tenant has none assigned
WHATSAPP_PHONE_NUMBER_ID=123456789012345

# WhatsApp Cloud API Version
WHATSAPP_API_VERSION=v18.0

# Enable/disable WhatsApp notifications globally
ENABLE_WHATSAPP_NOTIFICATIONS=true

# Webhook verification token (random secret you chose)
WHATSAPP_WEBHOOK_VERIFY_TOKEN=my-secret-webhook-token-12345
```

### 7.3 Restart Services

```bash
# Docker Compose
docker-compose restart notification-service

# Kubernetes
kubectl rollout restart deployment/notification-service

# Or rebuild
docker-compose up -d --build notification-service
```

---

## Step 8: Verify Setup

### 8.1 Test API Connectivity

**Check if credentials work:**

```bash
curl -X GET "https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}" \
  -H "Authorization: Bearer {ACCESS_TOKEN}" \
  | jq
```

**Expected Response:**
```json
{
  "verified_name": "Bakery Platform",
  "display_phone_number": "+34 612 345 678",
  "quality_rating": "GREEN",
  "id": "123456789012345"
}
```

**If error:**
```json
{
  "error": {
    "message": "Invalid OAuth access token",
    "type": "OAuthException",
    "code": 190
  }
}
```
→ Check your access token

### 8.2 Test Sending a Message

**Via API:**

```bash
curl -X POST "https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages" \
  -H "Authorization: Bearer {ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "messaging_product": "whatsapp",
    "to": "+34612345678",
    "type": "template",
    "template": {
      "name": "po_notification",
      "language": {
        "code": "es"
      },
      "components": [
        {
          "type": "body",
          "parameters": [
            {"type": "text", "text": "Juan García"},
            {"type": "text", "text": "PO-12345"},
            {"type": "text", "text": "€250.50"}
          ]
        }
      ]
    }
  }'
```

**Expected Response:**
```json
{
  "messaging_product": "whatsapp",
  "contacts": [
    {
      "input": "+34612345678",
      "wa_id": "34612345678"
    }
  ],
  "messages": [
    {
      "id": "wamid.XXXxxxXXXxxxXXX"
    }
  ]
}
```

**Check WhatsApp on recipient's phone!**

### 8.3 Test via Notification Service

**Trigger PO notification:**

```bash
curl -X POST http://localhost:8002/api/v1/whatsapp/send \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "uuid-here",
    "recipient_phone": "+34612345678",
    "recipient_name": "Juan García",
    "message_type": "template",
    "template": {
      "template_name": "po_notification",
      "language": "es",
      "components": [
        {
          "type": "body",
          "parameters": [
            {"type": "text", "text": "Juan García"},
            {"type": "text", "text": "PO-TEST-001"},
            {"type": "text", "text": "€150.00"}
          ]
        }
      ]
    }
  }'
```

**Check logs:**
```bash
docker logs -f notification-service | grep whatsapp
```

**Expected log output:**
```
[INFO] Using shared WhatsApp account tenant_id=xxx phone_number_id=123456789012345
[INFO] WhatsApp template message sent successfully message_id=xxx whatsapp_message_id=wamid.XXX
```

---

## Step 9: Assign Phone Numbers to Tenants

Now that the master account is configured, assign phone numbers to each bakery.

### 9.1 Access Admin Interface

1. Open: `http://localhost:5173/app/admin/whatsapp`
2. You should see:
   - **Available Phone Numbers:** List of your 10 numbers
   - **Bakery Tenants:** List of all bakeries

### 9.2 Assign Each Bakery

For each of the 10 pilot bakeries:

1. Find tenant in the list
2. Click dropdown: **Assign phone number...**
3. Select a phone number
4. Verify green checkmark appears

**Example:**
```
Panadería San Juan  →  +34 612 345 678
Panadería Goiko     →  +34 612 345 679
Bakery Artesano     →  +34 612 345 680
... (7 more)
```

### 9.3 Verify Assignments

```bash
# Check all assignments
curl http://localhost:8001/api/v1/admin/whatsapp/tenants | jq

# Should show each tenant with assigned phone
```

---

## Step 10: Monitor & Maintain

### 10.1 Monitor Quality Rating

WhatsApp penalizes low-quality messaging. Check your quality rating weekly:

```bash
curl -X GET "https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}" \
  -H "Authorization: Bearer {ACCESS_TOKEN}" \
  | jq '.quality_rating'
```

**Quality Ratings:**
- **GREEN** ✅ - All good, no restrictions
- **YELLOW** ⚠️ - Warning, review messaging patterns
- **RED** ❌ - Restricted, fix issues immediately

**Common Issues Leading to Low Quality:**
- High block rate (users blocking your number)
- Sending to invalid phone numbers
- Template violations (sending promotional content in UTILITY templates)
- User reports (spam complaints)

### 10.2 Check Message Costs

```bash
# View billing in Meta Business Manager
Business Settings → Payments → WhatsApp Business API
```

**Cost per Conversation (Spain):**
- Business-initiated: €0.0319 - €0.0699
- User-initiated: Free (24hr window)

**Monthly Estimate (10 Bakeries):**
- 5 POs per day per bakery = 50 messages/day
- 50 × 30 days = 1,500 messages/month
- 1,500 × €0.05 = **~€75/month**

### 10.3 Rotate Access Token (Every 60 Days)

Even though system user tokens are "permanent," rotate for security:

1. Generate new token (Step 4.2)
2. Update environment variable
3. Restart notification service
4. Revoke old token

**Set reminder:** Calendar alert every 60 days

---

## Troubleshooting

### Issue: Business verification stuck

**Solution:**
- Check Business Manager → Security Center
- Common reasons:
  - Documents unclear/incomplete
  - Business name mismatch with documents
  - Banned domain/business
- Contact Meta Business Support if > 5 days

### Issue: Phone number verification fails

**Error:** "This phone number is already registered with WhatsApp"

**Solution:**
- Number is used for personal WhatsApp
- You must use a different number OR
- Delete personal WhatsApp account (this is permanent!)

### Issue: Template rejected

**Common Rejection Reasons:**
1. **Contains promotional content in UTILITY template**
   - Fix: Remove words like "offer," "sale," "discount"
   - Use MARKETING category instead

2. **Missing variable indicators**
   - Fix: Ensure {{1}}, {{2}}, {{3}} are clearly marked
   - Provide good example values

3. **Unclear purpose**
   - Fix: Add context in template description
   - Explain use case clearly

**Resubmit:** Edit template and click "Submit for Review" again

### Issue: "Invalid OAuth access token"

**Solutions:**
1. Token expired → Generate new one (Step 4.2)
2. Wrong token → Copy correct token from System User
3. Token doesn't have permissions → Regenerate with correct scopes

### Issue: Webhook verification fails

**Error:** "The URL couldn't be validated. Callback verification failed"

**Checklist:**
- [ ] Endpoint is publicly accessible (not localhost)
- [ ] Returns `200 OK` status
- [ ] Returns the `hub.challenge` value exactly
- [ ] HTTPS enabled (not HTTP)
- [ ] Verify token matches environment variable

**Test webhook manually:**
```bash
curl "https://your-domain.com/api/v1/whatsapp/webhook?hub.verify_token=YOUR_TOKEN&hub.challenge=12345"
# Should return: 12345
```

---

## Checklist: You're Done When...

- [ ] Meta Business Account created and verified
- [ ] WhatsApp Business Account created (WABA ID saved)
- [ ] 10 phone numbers added and verified
- [ ] System User created
- [ ] Access Token generated and saved securely
- [ ] Message template `po_notification` approved
- [ ] Webhook configured and verified
- [ ] Environment variables set in `.env`
- [ ] Notification service restarted
- [ ] Test message sent successfully
- [ ] All 10 bakeries assigned phone numbers
- [ ] Quality rating is GREEN
- [ ] Billing configured in Meta Business Manager

**Estimated Total Time:** 2-3 hours (plus 1-3 days for business verification)

---

## Next Steps

1. **Inform Bakeries:**
   - Send email: "WhatsApp notifications are now available"
   - Instruct them to toggle WhatsApp ON in settings
   - No configuration needed on their end!

2. **Monitor First Week:**
   - Check quality rating daily
   - Review message logs for errors
   - Gather bakery feedback

3. **Scale Beyond Pilot:**
   - Request phone number limit increase (up to 120)
   - Consider WhatsApp Embedded Signup for self-service
   - Evaluate tiered pricing (Standard vs. Enterprise)

---

## Support Resources

**Meta Documentation:**
- WhatsApp Cloud API: https://developers.facebook.com/docs/whatsapp/cloud-api
- Getting Started Guide: https://developers.facebook.com/docs/whatsapp/cloud-api/get-started
- Template Guidelines: https://developers.facebook.com/docs/whatsapp/message-templates/guidelines

**Meta Support:**
- Business Support: https://business.whatsapp.com/support
- Developer Community: https://developers.facebook.com/community/

**Internal:**
- Full Implementation Guide: `WHATSAPP_SHARED_ACCOUNT_GUIDE.md`
- Admin Interface: `http://localhost:5173/app/admin/whatsapp`
- API Documentation: `http://localhost:8001/docs#/whatsapp-admin`

---

**Document Version:** 1.0
**Last Updated:** 2025-01-17
**Author:** Platform Engineering Team
**Estimated Setup Time:** 2-3 hours
**Difficulty:** Intermediate
