# WhatsApp via WuzAPI

Spot sends WhatsApp texts through an existing [WuzAPI](https://github.com/asternic/wuzapi) server, using one
dedicated, already paired **agency session**. Optionally it accepts `ACCETTA <code>` / `RIFIUTA <code>` replies.
Device pairing and session setup happen in WuzAPI, not in Spot.

## Pinned release

| | |
|---|---|
| Release | **v1.1.1** (published 2026-11-13) |
| Commit | `db621dd057259ae68e2fa2e8cdab5aba755a1c49` |
| Constant | `App\Services\Whatsapp\Wuzapi::PINNED_RELEASE` / `PINNED_COMMIT` |

These were checked on 2026-11-23 against `API.md`, `README.md` and the Go source (`handlers.go`, `helpers.go`,
`wmiau.go`) at that commit, plus the whatsmeow types it pins (`go.mau.fi/whatsmeow v0.0.0-20261013142727-4cf8bc8e0aeb`:
`types/message.go`, `types/events/events.go`, `types/jid.go`, `proto/waE2E`). Re-check the points below before
upgrading WuzAPI.

### Verified against the pinned docs / source

| What Spot relies on | Where it is documented |
|---|---|
| `POST {base}/chat/send/text`, JSON `{"Phone": "<digits>", "Body": "<text>", "Id": "<message id>"}`; `Id` is optional and caller-supplied ("If ID is omitted, a random message ID will be generated") | API.md "Send Text Message"; `handlers.go` `SendMessage` |
| Success `{"code":200,"data":{"Details":"Sent","Id":"…","Timestamp":…},"success":true}`; errors `{"code":…,"error":"…","success":false}` | API.md; `handlers.go` `Respond` |
| A successful send is **not** a delivery receipt | API.md "Message destinations" — hence the status name *Accepted by provider* |
| `Phone` accepts international digits (a leading `+` is tolerated) | API.md "Message destinations" |
| User token header: **`Token: <user token>`** (all examples use `-H 'Token: …'`; the server reads `r.Header.Get("token")`, or `?token=`) | `handlers.go` `authalice`. Note: the API.md intro says "use the `Authorization` header" — that applies to admin endpoints (`authadmin`); user endpoints read `token`. |
| Reusing an `Id` "does not provide idempotency"; after an ambiguous timeout "reconcile the outcome before another attempt" | API.md (carousel section, "Delivery and retry limitations") |
| Webhook JSON mode requires the WuzAPI server env `WEBHOOK_FORMAT=json` (default is form-encoded) | API.md "Webhook format configuration"; `helpers.go` `callHookWithHmac` |
| JSON body = the event map (`type`, `event`, …) plus `userID` and `instanceName` | `helpers.go` `callHookWithHmac` (the `token` field mentioned in API.md is not added by this release) |
| Signature header **`x-hmac-signature`** = **hex(HMAC-SHA256(key, raw JSON body))**; key ≥ 32 characters; per-instance key overrides `WUZAPI_GLOBAL_HMAC_KEY` | API.md "HMAC Configuration"; README "Webhook Security with HMAC"; `helpers.go` `generateHmacSignature` |
| Message events: `type: "Message"`, `event.Info.{Chat, Sender, SenderAlt, IsFromMe, IsGroup, ID, …}` (whatsmeow `MessageInfo` embeds `MessageSource`, JIDs serialise as `user@server`), `event.Message.conversation` or `event.Message.extendedTextMessage.text` | `wmiau.go` `case *events.Message`; whatsmeow types |

### Assumptions (not explicitly documented)

- The bytes WuzAPI posts are exactly the bytes it signed: it signs `json.Marshal(body)` and then lets resty marshal the
  same map again (Go map marshalling is deterministic). Spot verifies against the raw request body as received.
- A sender whose `Sender` is a LID (`…@lid`) carries the phone JID in `SenderAlt`; Spot only maps phone-number JIDs to
  verified numbers and ignores the message otherwise.
- `Info.ID` is stable across WuzAPI webhook retries of the same message (it is the WhatsApp message id), so it is
  used as the dedupe key.

## How Spot uses it

- **Outbound**: every notification that has a WhatsApp copy (new / revised / reconfirm offer, withdrawn, cancelled,
  reassigned, show cancelled, deadline and show reminders, verification codes, replies to commands) creates a
  `whatsapp_deliveries` row (status *Queued*, unique `client_message_id`, body with reply codes masked) and queues
  `App\Jobs\SendWhatsappMessage` after the transaction commits. The job payload is encrypted (`ShouldBeEncrypted`);
  only it carries the plain reply code. Offer texts contain the show date, venue / city, the reply deadline and
  `{APP_URL}/offers/{revision}`; with direct replies on, also `ACCETTA <code>` / `RIFIUTA <code>`.
- **Retries**: 5xx, 429 and "could not connect" are retried up to `WUZAPI_MAX_ATTEMPTS` (default 3) with 30 s / 2 min /
  10 min backoff, then *Failed*. 4xx fail immediately. **Timeouts are ambiguous** (the message may have been sent) and,
  because the pinned docs state that reusing an `Id` is not idempotent, Spot does **not** resend: the delivery is marked
  *Failed* with `unconfirmed: timeout …`. A manager can resend deliberately from `/manager/deliveries` (new message id;
  a fresh reply code is issued if the offer still awaits a reply).
- **Webhook**: `POST {APP_URL}/webhooks/wuzapi` — no session/CSRF/auth, throttled. The signature is checked with
  `hash_equals` against the raw body before parsing; missing/invalid signature (or no secret configured) → 401.
  Only `type: "Message"`, private chats (`@s.whatsapp.net` / `@lid`, not `IsGroup`), not `IsFromMe`, text messages
  matching `ACCETTA|ACCEPT|RIFIUTA|DECLINE <6-char code>` are processed. The sender must map to a user with that
  **verified** `whatsapp_number`. Each processed command is recorded in `whatsapp_inbound_events` (unique provider id,
  masked sender, outcome) in the same transaction as `BookingWorkflow::acceptWithCode` / `declineWithCode`, so
  duplicates are no-ops and the code is consumed together with the decision. Everything else gets `200` and is not
  stored.
- If WuzAPI is disabled, misconfigured or down, booking actions and in-app notifications keep working; failures are
  visible to managers at `/manager/deliveries`.
- Logs: WhatsApp traffic goes to the `whatsapp` log channel (`storage/logs/whatsapp-*.log`, created automatically
  unless `config/logging.php` defines one). Tokens, the HMAC secret, `APP_KEY`, reply codes, verification codes and
  phone numbers are redacted from logs and stored errors.

## Configuration

`.env` (read only via `config('services.wuzapi.*')`, so `php artisan config:cache` works):

```dotenv
WUZAPI_ENABLED=false                 # master switch for WhatsApp delivery
WUZAPI_BASE_URL=                     # e.g. https://wuzapi.example.com (no trailing slash)
WUZAPI_API_TOKEN=                    # the agency session's *user* token (not the admin token)
WUZAPI_DIRECT_REPLIES_ENABLED=false  # accept ACCETTA/RIFIUTA replies
WUZAPI_WEBHOOK_HMAC_SECRET=          # same key as the session's HMAC key in WuzAPI (>= 32 chars)
```

Optional (defaults in `config/services.php`):

```dotenv
WUZAPI_SESSION_USER_ID=     # if set, webhooks must carry this WuzAPI userID (pins the agency session)
WUZAPI_INSTANCE_NAME=       # if set, webhooks must carry this instanceName
WUZAPI_TRANSPORT=auto       # auto | wuzapi | fake  (auto = real transport only when URL + token are set)
WUZAPI_TIMEOUT_SECONDS=15
WUZAPI_MAX_ATTEMPTS=3
```

### What the operator configures in WuzAPI

1. Server env: `WEBHOOK_FORMAT=json` (required — Spot only parses the JSON webhook).
2. A dedicated user/session for the agency, paired with the agency's WhatsApp number. Put its **user token** in
   `WUZAPI_API_TOKEN`.
3. Webhook URL for that session: `{APP_URL}/webhooks/wuzapi`, e.g. `https://spot.samigo.com/webhooks/wuzapi`
   (`POST /webhook` with `{"webhookURL": "…"}` or the dashboard).
4. Subscribed events: at least **`Message`** (`POST /session/connect` with `{"Subscribe":["Message"]}`, or the dashboard).
5. HMAC key for the session (`POST /session/hmac/config` with `{"hmac_key": "…"}`, ≥ 32 chars) and the same value in
   `WUZAPI_WEBHOOK_HMAC_SECRET`. Spot rejects every webhook when no secret is configured.
6. Optionally note the session's `userID` / instance name and set `WUZAPI_SESSION_USER_ID` / `WUZAPI_INSTANCE_NAME`.

Run a queue worker (`php artisan queue:work`) and the scheduler (`php artisan schedule:work` or cron
`* * * * * php artisan schedule:run`): deliveries are queued and `spot:send-reminders` runs every 5 minutes.

## Local development and tests

- With `WUZAPI_ENABLED=true` and an empty `WUZAPI_BASE_URL` / `WUZAPI_API_TOKEN` (or `WUZAPI_TRANSPORT=fake`), Spot
  uses `App\Services\Whatsapp\FakeTransport`: nothing leaves the machine, each message is recorded in memory and a
  redacted line is written to `storage/logs/whatsapp-*.log`; deliveries show as *Accepted by provider* with id
  `FAKE-…`. In the `local` environment the WhatsApp verification page also flashes the code on screen so you can
  verify a number without a real WhatsApp session.
- Simulate an inbound reply (with `WUZAPI_WEBHOOK_HMAC_SECRET` set and `WUZAPI_DIRECT_REPLIES_ENABLED=true`):

  ```bash
  BODY='{"type":"Message","userID":"1","instanceName":"agency","event":{"Info":{"Chat":"393331234567@s.whatsapp.net","Sender":"393331234567@s.whatsapp.net","IsFromMe":false,"IsGroup":false,"ID":"3EB0LOCALTEST0001"},"Message":{"conversation":"ACCETTA 8K4Q7M"}}}'
  SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$WUZAPI_WEBHOOK_HMAC_SECRET" | sed 's/^.* //')
  curl -X POST http://localhost:8000/webhooks/wuzapi -H 'Content-Type: application/json' \
       -H "x-hmac-signature: $SIG" --data-binary "$BODY"
  ```

  The reply code is only in the (encrypted) queued job, never in the database or logs; in tests it is captured from
  the `OfferSent` event.
- Tests: `php artisan test tests/Feature/Comms` (Http::fake for WuzAPI, signed fixtures in `tests/Fixtures/wuzapi/`
  modelled on the pinned payloads; placeholders `{{SENDER}}`, `{{ID}}`, `{{TEXT}}`, `{{SESSION}}`, `{{INSTANCE}}`).
