# WhatsApp Integration

## Overview

MailTrixy integrates with the WhatsApp Business API (via Meta's Cloud API) to let you send and receive WhatsApp messages directly from your MailTrixy dashboard. Conversations from WhatsApp appear in the same unified inbox alongside emails, SMS, and other channels.

AI-powered replies work on WhatsApp conversations too — the AI reads incoming WhatsApp messages, pulls context from your Knowledge Base, and generates replies just like it does for email.

## Meta Business API Setup

WhatsApp Business API is provided by Meta (Facebook). You need a Meta Business account to get started.

1. Go to business.facebook.com and log in (or create a Meta Business account).
2. Navigate to developers.facebook.com and create a new app. Select Business type.
3. On the app dashboard, find WhatsApp in the product list and click Set Up.
4. You will be assigned a temporary Phone Number ID and WhatsApp Business Account ID for testing.
5. Generate a Permanent Access Token (System User token from Business Settings → System Users → Generate Token with `whatsapp_business_messaging` permission).

## Business Verification

To send messages to customers (not just test numbers), Meta requires you to verify your business. This process takes 2–7 business days.

1. Go to Business Settings → Security Center → Start Verification.
2. Provide your business legal name, address, phone number, and website.
3. Upload a supporting document (business registration, utility bill, or bank statement).
4. Meta will review and approve (or request additional information).

> Note: You can use the test phone number (provided by Meta) to develop and test your integration while waiting for verification. Test numbers can only message up to 5 pre-registered phone numbers.

## Phone Number Setup

You can use your existing business phone number or a new dedicated number for WhatsApp.

- The number must be able to receive SMS or voice calls for verification.
- The number cannot already be registered with WhatsApp (personal or business app). If it is, you must delete the existing WhatsApp account first.
- Toll-free numbers and landlines work (Meta will verify via voice call).

In the Meta Developer dashboard, add your phone number under WhatsApp → Phone Numbers → Add Phone Number. Complete the verification process via SMS or voice call.

Once verified, copy the Phone Number ID and paste it into MailTrixy at Settings → Channels → WhatsApp → Phone Number ID.

## Message Templates

WhatsApp requires that businesses use pre-approved message templates to initiate conversations with customers. Templates must be submitted to Meta for approval before use.

- When templates are needed: Only when you are sending the first message (initiating a conversation). If the customer messages you first, you can reply freely for 24 hours without a template.
- Template categories: Marketing, Utility (order updates, shipping), Authentication (OTP codes).
- Creating templates: Go to Meta Business Manager → WhatsApp Manager → Message Templates → Create Template.
- Variables: Use `{{1}}`, `{{2}}`, etc. as placeholders that MailTrixy will fill dynamically (customer name, order number, etc.).

MailTrixy syncs your approved templates automatically. You can select which template to use when starting a new WhatsApp conversation from the dashboard.

## Credentials in MailTrixy

Settings → Channels → WhatsApp expects four values:

- Phone Number ID — from Meta Dev Portal → WhatsApp → API Setup.
- Access Token — permanent System User token recommended. Temporary tokens expire in 24 h.
- Verify Token — any random string you choose; Meta echoes it back during webhook registration.
- App Secret — required. From Meta Dev Portal → App Settings → Basic → "App secret" (click Show). Used to verify webhook HMAC-SHA256 signatures. Without it, every inbound webhook is rejected with 403.

> App Secret is not the Access Token and not the Verify Token. It is a separate value on the App Settings page. A common misconfiguration is pasting the wrong value — the webhook will log "Signature did not match any active integration secret" and ignore the payload.

## Webhook Configuration

Webhooks allow Meta to notify MailTrixy when new WhatsApp messages arrive.

1. In the Meta Developer Dashboard, go to WhatsApp → Configuration.
2. Set the Callback URL to: `https://yourdomain.com/api/webhooks/whatsapp`
3. Set the Verify Token to the same value you saved in MailTrixy.
4. Subscribe to the following webhook fields:
   - `messages` — incoming messages
   - `message_status` — delivery receipts (sent, delivered, read)
5. Click Verify and Save.

> Important: Your server must be accessible over HTTPS with a valid SSL certificate. Meta will not send webhooks to HTTP URLs or self-signed certificates.

### Signature verification

Every webhook delivery from Meta includes an `X-Hub-Signature-256` header. MailTrixy recomputes the signature with your saved App Secret and rejects any request that doesn't match. If you see repeated "Signature did not match any active integration secret" warnings in `storage/logs/laravel.log`:

1. Confirm the App Secret in Settings is exactly what Meta shows in App Settings → Basic (click Show; it starts with a letter/digit, 32+ chars).
2. The App Secret belongs to the App whose Phone Number ID you're using — using Secret A with App B's phone number will fail.
3. Re-save the integration after pasting to trigger a fresh credential encryption.

### Status updates

Meta sends `sent`, `delivered`, `read`, and `failed` status webhooks. MailTrixy maps them as follows:

- sent → `delivery_status = sent`, `sent_at` set.
- delivered → `delivery_status = delivered`, `delivered_at` set.
- read → `delivery_status` stays `delivered` (its stored enum doesn't include "read"), but `opened_at` is set — that timestamp is the source of truth for read receipts in the UI.
- failed → `delivery_status = failed`, Meta's error message is stored in `delivery_error` (truncated to fit the column).

## Common issues

- "Signature did not match any active integration secret" — App Secret is missing, empty, or belongs to a different App. See "Signature verification" above.
- "Unsupported post request. Object with ID '…' does not exist" when Mailtrixy tries to mark a message as read — the Access Token stored in your integration is for a different App or has been revoked. Re-paste a fresh permanent System User token.
- Inbound message saves but no auto-reply fires — the rule's Exact phrase match requires the trimmed, lower-cased message to equal the keyword exactly. Either switch the match type to "Contains", or have the customer send the exact keyword.

## Testing

Before going live, test the integration thoroughly:

1. Send a test message: From your personal WhatsApp, send a message to the WhatsApp Business number you configured.
2. Check MailTrixy: The message should appear in your MailTrixy inbox within a few seconds.
3. Reply from MailTrixy: Type a reply in MailTrixy and send it. The message should arrive on your personal WhatsApp.
4. Test AI reply: If AI is enabled for the WhatsApp channel, verify that AI-generated drafts appear (or auto-send, depending on your settings).
5. Test templates: From MailTrixy, start a new conversation using a message template. Verify the template is sent correctly with variables filled in.

If messages are not arriving, check the Webhook Logs section in MailTrixy (Settings → Channels → WhatsApp → Logs) for error details.