# Payments and subscriptions (Bachs)

HiWhatsApp AI Assistant – Evidence, Contacts & Messaging sells two recurring products through Bachs (bachs.io), using the merchant's existing Bachs account:

| Plan code | Price | Billing |
|---|---|---|
| `monthly` | 5.99 USD | every 1 month |
| `yearly` | 49.00 USD | every 1 year |

Prices and names are stored in the `plans` table and can be edited in **Admin → Plans**. A price change applies to new subscribers only after you create a new Bachs product and link its ID. Existing subscriptions keep the product they were bought with.

## Principles

1. **Secret keys exist only on the backend** (`config/config.php` or environment variables). The extension, Chrome storage and content scripts never see them. `scripts/build.mjs` refuses to package anything shaped like a Bachs key.
2. **The backend is the authority.** The extension asks `GET /v1/billing/status` and receives a status plus an ECDSA-signed entitlement token. Editing extension code or storage cannot produce a valid token.
3. **A browser redirect never grants access.** The `success_url` page (`/billing/return`) only triggers a server-to-server lookup of the checkout at Bachs. Access comes from a verified webhook or from that lookup.
4. **Payment records are separate from evidence.** The billing tables hold account e-mail, Bachs IDs, amounts, dates and statuses. No conversation content, screenshot or contact ever reaches the backend.

## Flow

```
Extension ── POST /v1/billing/checkout {plan} ──► Backend ── POST /v1/checkout-sessions ──► Bachs
         ◄── checkout_url ─────────────────────          (metadata: hiwa_user_id, plan_code, hiwa_ref)
User pays on the Bachs hosted page
Bachs ── signed webhook (checkout.completed, customer.subscription.created, invoice.paid) ──► Backend
Backend ── GET /v1/subscriptions/{id} (confirms the live state) ──► Bachs
Extension polls /v1/billing/status → ACTIVE
```

- One open checkout per user is reused for 20 minutes, which prevents double subscriptions from repeated clicks. Subscribing while already premium returns `409 ALREADY_SUBSCRIBED`.
- Subscription webhooks are not trusted on their own: the backend fetches the subscription from Bachs before storing it, and falls back to the signed payload only if Bachs is unreachable. Out-of-order events are ignored using the provider's `updated_at`.
- Users are matched to subscriptions by `metadata.hiwa_user_id`, then by Bachs customer ID, then by e-mail (used by **Restore**).

## Access states

| State | When | Premium? |
|---|---|---|
| `FREE` | no subscription | no |
| `PAYMENT_PENDING` | a checkout was opened in the last 60 minutes and not completed | no |
| `ACTIVE` | Bachs status `active` / `trialing` and within the period | yes |
| `PAST_DUE` | renewal failed; Bachs is retrying (1, 3, 5 days) | yes (configurable: `billing.past_due_keeps_access`) |
| `CANCELLED` | cancelled with `cancel_at_period_end`; period not ended | yes, until the period end |
| `EXPIRED` | period ended after cancellation, Bachs `canceled`/`unpaid`, more than 3 days past period end without renewal, or the last payment was fully refunded | no |

Free-plan limits and premium entitlements are in **Admin → Entitlements** and are enforced server-side through `POST /v1/usage/consume`.

## Events handled

| Bachs event | Action |
|---|---|
| `checkout.completed` | reconcile checkout → fetch and store the subscription |
| `checkout.expired` | mark the checkout abandoned |
| `customer.subscription.created` / `updated` / `deleted` | fetch live subscription, store status, period, cancel flag |
| `invoice.paid` | record payment (initial or renewal), refresh subscription |
| `invoice.payment_failed` | record failed payment; status becomes `PAST_DUE` |
| `refund.created` / `refund.paid` / `refund.failed` | record refund; a full refund of the latest payment revokes premium (configurable) |

Duplicate deliveries are detected by event ID (`webhook_events` unique key) and acknowledged without reprocessing. A processing error returns HTTP 500 so Bachs retries. Every event is visible in **Admin → Webhooks** and can be reprocessed.

## Cancellation, restore, portal

- **Cancel** (extension → Subscription) calls Bachs `DELETE /v1/subscriptions/{id}` with `cancel_at_period_end: true`. Access continues to the period end.
- **Manage billing** opens a Bachs customer portal session (card update, invoices).
- **Restore purchase** looks up subscriptions at Bachs by the account's customer ID and e-mail. Use it when a payment was made but the account still shows Free (for example, a webhook was missed before reconciliation ran).
- **Upgrade / downgrade** (monthly ↔ yearly): while a subscription is `ACTIVE` or `PAST_DUE`, the plan buttons point to **Manage billing / change plan** (Bachs customer portal), and the API refuses a second checkout (`409 ALREADY_SUBSCRIBED`), so nobody is double-billed by accident. After cancelling (`CANCELLED`), the user can subscribe to the other plan straight away; the new subscription starts on payment. The backend does not call a Bachs plan-change/proration API because none could be verified in the public documentation. Confirm in the sandbox whether the customer portal offers plan switching (checklist item P-12).

## Reconciliation

`bin/cron.php` reconciles once an hour: open checkouts, every non-final subscription, and expirations. `php bin/cli.php bachs:reconcile --full` also lists all subscriptions at Bachs and imports any that carry this product's metadata.

## Items to verify in the Bachs sandbox

These parts of the Bachs API were implemented from public documentation and community SDKs, and are covered only by the test double in `backend/tests/fakes/bachs.php`:

- the request body of `DELETE /v1/subscriptions/{id}` (`cancel_at_period_end`);
- the filter parameters of `GET /v1/subscriptions` used by Restore and `--full` reconcile;
- the exact payload shapes of `invoice.*` and `refund.*` events (amount fields, subscription reference);
- whether `metadata` from the checkout session is copied onto the subscription (the matching falls back to customer ID / e-mail if not).

[MANUAL_TEST_CHECKLIST.md](MANUAL_TEST_CHECKLIST.md) lists each check. `BachsClient` and `WebhookProcessor` are the only files to adjust if the real behaviour differs.
