# Migo Payments — Autonomous Integration Guide (for AI coding agents)

> **What this is.** A self-contained, step-by-step guide for an AI coding agent to integrate
> **Migo payments** via the **hosted payment webview**, with minimal human intervention. It covers **both** flows as first-class: **one-time payments** and **recurring
> subscriptions**. They share the same path — a subscription just adds a plan (Step 1) and a
> subscription callback (Step 2); a one-time payment skips those two parts. Everything you need is in
> this file — you do **not** need to open any external link to complete the task.
>
> **Human touchpoints (two):** (1) provide the Section 1 values and confirm the callback configuration
> agreed with Migo; (2) click through the sandbox checkout once for the live test in Step 4.
> Everything else is autonomous.
>
> **Status:** verified against `migo-api` (subscription creation trigger, first-charge amount, and the
> callback mechanism). The subscription callback's exact payload fields and auth header are
> **per-account configuration you agree with Migo** (see Section 2 and Step 2), not a fixed struct.

---

## Summary (for the agent)

You will, in order: **(1)** from a **backend**, `POST /transactions` → receive a webview `URL`;
**(2)** send the customer to that `URL` to pay in Migo's hosted webview; **(3)** on your public
endpoint, receive Migo's callback and update your records **idempotently**. Do everything in
**sandbox** first. The merchant token is **server-side only** — never in the browser. Follow the
steps in order and do not skip a `VERIFY`.

**One-time vs. subscription — same flow.** A **subscription** adds the plan (`customKeys.plan.uid` in
Step 1) and the `subsCallback` (`active`/`inactive`, Step 2). A **one-time payment** omits the plan and
handles only the one-time callback (`approved`/`denied`/…). Confirm which you're building in Section 2.

---

## 0. Operating instructions (read first, agent)

You are integrating Migo payments into the current project. Follow these rules exactly:

1. **Work one step at a time, and show a live progress list.** Maintain a **visible checklist** of the
   steps (done / in progress / pending) and keep it updated as you advance, so the human always
   sees where you are. Each step has a `VERIFY` block — **do not start the next step until the current
   step's `VERIFY` passes.**
2. **If `VERIFY` fails,** go to that step's `Troubleshooting` table, apply the fix, and re-run
   `VERIFY`. Do not guess or invent endpoints, fields, or headers that are not in this document.
3. **Stay in SANDBOX** for every step. Only switch to production after a human approves (Section 9).
4. **Establish your context first (Section 2)** — identify your environment and confirm you have a
   backend and a public callback URL. **Do not assume they already exist.**
5. **Ask the human only for the values in Section 1** (plus anything Section 2 flags). Everything else
   you can do yourself.
6. **Never hardcode secrets** in source. Read them from environment variables. **Never log** the
   merchant token, card data, or full callback bodies.
7. **Never invent or use real personal data** (customer email, name, phone) to create a transaction —
   even for a test. Ask the human for the values, **or** propose obvious placeholders (e.g.
   `test@example.com`) and get explicit confirmation, **or** let the human create the test link. Never
   auto-fill someone's real email / PII on your own.
8. **Be literal.** Copy endpoints, headers, and JSON field names exactly as written — including
   capitalization (e.g. the response field is `URL`, not `url`).
9. When you finish, run the **Acceptance checklist** in Section 8 and report the result.

---

## 1. Inputs (the only setup step for the human)

Ask the human for these once, store them as environment variables, and confirm you have all of them
before continuing. Do not proceed with placeholders.

| Env var | What it is | Example (sandbox) |
|---|---|---|
| `MIGO_MERCHANT_TOKEN` | Long-lived merchant token issued by Migo for your app (sandbox). | `b6a615d8…0ba65c1` |
| `MIGO_CLIENT_SLUG` | Your client slug as registered in Migo. | `migoDeveloper` |
| `MIGO_PLAN_UID` | The subscription plan to enroll into — **subscriptions only; skip for one-time** (must already exist in Migo). | `pln_01HXXX` |
| `MIGO_CURRENCY` | Transaction currency — **ask the human which to use** (default `GTQ`). Allowed: `GTQ` or `USD`. | `GTQ` |
| `MIGO_CALLBACK_URL` | A **public HTTPS** URL on your backend where Migo will POST results (how to obtain one depends on your environment — see Section 2 → Environment notes). Configured with Migo for your account. | `https://your-app.example.com/webhooks/migo` |
| `MIGO_CALLBACK_SECRET` | The secret value Migo will send on the auth header of your callback. **You choose the header name and secret** in your Migo callback config (the callback is **not** HMAC-signed). | `whsec_…` |
| `MIGO_CALLBACK_HEADER` | The header name Migo will send that secret on, as configured for your account. | `x-api-key` |

> **From scratch:** if the human agrees, you may scaffold a **git-ignored `.env`** with these keys left
> **empty** for the human to populate — never fill the values yourself. Add `.env` to `.gitignore` and
> commit only a `.env.example` with the keys and empty values.

**Fixed values (already known — do not ask the human):**

| Name | Sandbox value |
|---|---|
| API base URL | `https://sb-mw.migopayments.com` |
| Webview base URL | `https://sandbox.migopayments.com` |
| Test card — approves | `4111111111111111` |
| Test card — 3D Secure challenge | `4456530000001096` |
| Test card — declines | `4000000000000002` |

---

## 2. Establish your context & prerequisites (do this first)

This guide is **identical in every environment** — the only things that differ are *where your backend
runs*, *how you get a public callback URL*, and *where secrets live*. Settle these before coding.

**Step 0 — Identify where you are running** (ask the human if unsure), then apply the matching
**Environment notes** in the appendix (Section 10):

- **Cloud IDE with deployments** (e.g. Replit) — you can deploy and get a public URL easily.
- **Local editor** (e.g. VS Code / Cursor / Claude Code) — `localhost` is **not** public; you need a tunnel or a deploy.
- **Frontend-first builder** (e.g. Lovable / Bolt / v0) — you must add a backend (a serverless/edge function).
- **Generic** — any server you control.

**Choose your flow — ask the human first, offering three explicit, equal options:**
**(A) one-time payments only**, **(B) subscriptions only**, or **(C) both**. Do **not** default to
subscriptions — one-time is a first-class path. The whole guide applies to all three; the
subscription-specific parts are only two:
- **Step 1** adds `customKeys.plan.uid` (a one-time payment omits it).
- **Step 2** adds the `subsCallback` handling + renewal/reconciliation by `subscriptionId`.

For **one-time only**, follow the same steps but **skip the subscription-specific parts**: you'll only
ever receive the one-time callback (`approved`/`denied`/…) and reconcile by `externalId`/`uid` (see
**Reconciliation & data model → Direct (one-time) payment**). For **both**, implement everything.

**Non-negotiable — you need a backend.** The Migo merchant token is a **server-side secret** and must
**never** run in the browser. Even on frontend-first platforms, create a small backend / serverless
function to call `POST /transactions` and to receive callbacks. This keeps a **single, secure code
path** across every environment — you never branch the integration by platform, only the setup below.

**From scratch vs. existing app — decide this first:**
- **From scratch:** also scaffold a **minimal test UI** for manual testing — inputs for `amount`,
  customer `email`, and the plan; a **selector for the scenario(s) you're building** — one-time /
  subscription / both (subscription includes `customKeys.plan.uid`, one-time omits it); a button that
  calls Step 1; and a panel that **prints on screen the request payload sent, the Step 1 response, and
  every incoming webhook payload** (one-time + `subsCallback`). It lets a human drive the flow and watch
  the real shapes while you build, and doubles as your Step 2 verification surface. The **human fills**
  those inputs — don't auto-fill real emails / PII (see rule 7).
- **Integrating into an existing app:** do **not** build a throwaway UI. Inspect the app's stack, data
  model, and existing user/payment flows, and **wire Migo into them** — reuse its user/access model per
  **Reconciliation & data model** (appendix).

**Confirm these before writing code (tell the human if any is missing):**

- **Outbound HTTPS** from your backend (to call `POST /transactions`).
- **A public HTTPS endpoint** for callbacks — **not `localhost`**. How you obtain it depends on your
  environment (Section 10): a Replit deployment URL, a tunnel for a local editor, or a deployed
  function for a frontend builder.
- **(Subscriptions only — skip for one-time.) The plan already exists** in Migo (`MIGO_PLAN_UID`).
  Creating plans is an admin/config task and is **out of scope** — do not attempt to create a plan.
- **The merchant callback is configured with Migo.** You cannot self-serve this: Migo stores, per
  account, your callback **URL**, the **auth header + secret**, and a **payload template** that defines
  the exact JSON body Migo will POST. **Get the confirmed payload fields and header name for your
  account from Migo (or the human)** — you will code your handler (Step 2) to exactly that shape.

---

## 3. Mental model (what you are building)

```
┌─ your backend ──────────────┐
│ Step 1: POST /transactions  │ ───────────►  Migo
│   (plan in customKeys)      │
│                             │ ◄───────────  { uid, reference, URL }
└─────────────────────────────┘
             │ Step 3: hand the URL to the customer
             ▼
┌─ customer (Migo hosted webview) ───────────────────┐
│ Step 4: opens URL, pays with card, 3DS if needed.  │  ← you write NO code here
│         On approval, Migo creates the subscription │
│         automatically (the plan rides in the trx). │
└─────────────────────────────────────────────────────┘
             │ Migo POSTs results to your MIGO_CALLBACK_URL (endpoint from Step 2)
             ▼
┌─ your backend ──────────────┐
│ Merchant Generic Callback   │  one-time payment result (approved/denied/…)
│ subsCallback                │  subscription state (active / inactive)
└─────────────────────────────┘
```

Key facts (all verified against `migo-api`):
- You make **one** API call (Step 1). The payment itself happens inside Migo's webview — you never
  collect card data, never tokenize, never call a "charge" endpoint.
- **One-time payment:** omit the plan — you get one callback (the one-time result) and you're done.
- **Subscription:** the subscription is **created automatically by Migo when the payment is approved**,
  because the plan travels inside the transaction at `customKeys.plan.uid`. You do **not** call a
  separate "create subscription" endpoint.
- Migo tells your backend what happened through **callbacks**. The browser redirect is for UX only —
  **the callback is your source of truth.** The callback body/headers follow **your account's
  configured template** (Section 2), not a fixed schema.
- **Build order matters:** you implement and self-test the callback endpoint (Step 2) **before** the
  live payment (Step 4), so the first `subsCallback active` has somewhere to land.

---

## 4. Step 1 — Create the payment transaction

**Goal:** create a transaction and get back the webview `URL`. (A **subscription** carries the plan; a **one-time payment** omits it.)

**Action:** from your backend, call `POST /transactions` with the merchant token in the
`Authorization` header (raw token, **no** `Bearer` prefix). Put the plan in `customKeys`, and use a
**unique `externalId` per order** so you can reconcile the callbacks. (An `Idempotency-Key` header is
shown below as a retry safeguard — confirm with Migo whether this legacy endpoint honors it.)

```bash
curl -X POST https://sb-mw.migopayments.com/transactions \
  -H 'Content-Type: application/json' \
  -H "Authorization: $MIGO_MERCHANT_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "amount": 54.88,
    "currency": "'"$MIGO_CURRENCY"'",
    "userId": "customer@example.com",
    "channel": "web",
    "client": "'"$MIGO_CLIENT_SLUG"'",
    "externalId": "your-order-id-001",
    "customKeys": {
      "emailTo": "customer@example.com",
      "plan": { "uid": "'"$MIGO_PLAN_UID"'" },
      "automaticRedirect": {
        "approved":  { "url": "https://your-app.example.com/checkout/result?status=approved" },
        "denied":    { "url": "https://your-app.example.com/checkout/result?status=denied" },
        "expired":   { "url": "https://your-app.example.com/checkout/result?status=expired" },
        "cancelled": { "url": "https://your-app.example.com/checkout/result?status=cancelled" }
      }
    },
    "ads": []
  }'
```

> **One-time payment** (no subscription): send the exact same body **without** `customKeys.plan`.
> The presence of `customKeys.plan.uid` is the only difference.

Field notes:
- `amount` — the **real amount in major units**, sent as a plain JSON number — **integer or decimal**
  both work (e.g. `84` or `54.88`; use standard money precision, up to 2 decimals). **Do NOT multiply by
  100 / do NOT use minor units.** Must be within your client's configured min/max. This is the
  **first-charge** amount; **renewals** are charged at the plan's own amount, not this value.
- `currency` — `GTQ` (default) or `USD`, from `MIGO_CURRENCY`. Send it explicitly; if omitted, Migo
  falls back to the first currency configured for your client.
- `userId` — your end customer's identifier (typically their **email**; a phone or your internal id
  also work). **Keep it stable** — the subscription is tied to it.
- `channel` — one of `wa | sms | email | web | app`.
- `externalId` — your own order/record id, echoed back on the callbacks so you can **reconcile**
  (recommended; e.g. `myapp_{userId}_{plan}_{period}_{timestamp}`).
- `customKeys.emailTo` — the customer's email for Migo's **payment voucher/receipt** (for the voucher
  Migo uses `userId` first when it's a valid email, then `emailTo`). Note: the **subscription-confirmation**
  email instead goes to the email the customer types in the **webview** at checkout (falling back to
  `emailTo` only if left blank). Keep `userId` and `emailTo` set to the same customer email so everything
  lines up.
- `customKeys.plan.uid` — the plan to enroll into. **This exact key path is what triggers subscription
  creation on approval** (verified against `migo-api`). Use `customKeys.plan.uid` — not `subscriptionData`.
  Omit it entirely for a one-time payment.
- `customKeys.automaticRedirect` — per-status browser return URLs (`approved`/`denied`/`expired`/`cancelled`).
  **If present, it overrides Migo's configured redirect; if omitted, Migo uses the redirect stored in its
  own config for your account.** This is the *browser* redirect only — not your server callback (Step 2).
- `Idempotency-Key` — optional retry safeguard; **confirm with Migo whether this legacy endpoint honors
  it.** Regardless, always send a **unique `externalId` per order** — the reference integration relies on
  `externalId` (not this header) for reconciliation.
- `ads` — always send `[]`.

**Expected result** (HTTP `201 Created` — treat any `2xx` as success):

```json
{
  "uid": "Ypo5z2zTpLqWoe3eVvZMH",
  "reference": "CAMPGT020007SB",
  "URL": "https://sandbox.migopayments.com/?orderId=Ypo5z2zTpLqWoe3eVvZMH"
}
```

**VERIFY:**
- Response status is `2xx` (sandbox returns `201`).
- The body has a non-empty `uid` and a `URL` field. **Read it as `URL` (uppercase).** In JS,
  `const paymentLink = response.URL` or `response["URL"]` — `const { url } = response` is a bug and
  returns `undefined`.
- Persist `uid` (you will correlate callbacks to it) and `reference`.

**Troubleshooting:**

| Symptom | `ownCode` | Cause | Fix |
|---|---|---|---|
| `401 { "message": "Unauthorized" }` (no `ownCode`) | — | Bad/missing merchant token | Check `MIGO_MERCHANT_TOKEN`; ensure it's the **sandbox** token; send it raw (no `Bearer`). |
| `409` | `5000` | Missing/invalid required field | Ensure `amount`, `userId`, `channel`, `client` are present with correct types. |
| `409` | `5004` | `client` slug not found | Confirm `MIGO_CLIENT_SLUG`; ask Migo to activate it in sandbox. |
| `409` | `2003` | `amount` out of your configured min/max | Adjust `amount`. |
| `400` | `2004/2005/2006` | Customer blocked/suspended/excluded | Use a different `userId`. |

**Checkpoint:** only continue when you have a valid `uid` and `URL`.

---

## 5. Step 2 — Implement & self-test the callback endpoint

Do this **before** the live payment (Step 4), so the first-charge callback has somewhere to land.
This step is **fully autonomous** — you build the handler and verify it with replay payloads, without
touching the webview.

**Goal:** implement the endpoint at `MIGO_CALLBACK_URL` that receives Migo's server-to-server results,
and update your records idempotently. (One-time only? You only need the first bullet below — skip the
`subsCallback` rules.)

Migo POSTs up to two callbacks:
- **Merchant Generic Callback** — one-time payment result. Statuses: `approved`, `denied`, `refunded`, `reversed`.
- **`subsCallback`** — subscription state. Statuses: **`active`** (created, manual payment, successful
  renewal) and **`inactive`** (Migo exhausted its dunning retries). `cancelled`/`expired` do **not**
  travel over the webhook.

> **One-time only?** If you're not doing subscriptions, you'll only ever receive the **Merchant Generic
> Callback** — implement just that branch (grant access on `approved`, ignore non-approved) and **skip
> the `subsCallback` rules below** (routing, cross-type idempotency, renewals, lease).

> **Timing you must handle:** on the **first charge**, Migo sends **both** callbacks (the one-time
> result **and** `subsCallback active`). On **renewals**, Migo sends **only** `subsCallback`.

> **The callback body is a per-account Handlebars template you configure with Migo (confirmed against a
> real production config).** You define the fields; there is no fixed struct. Request a `subsCallback`
> template that includes at least these fields — the Migo template variable is shown so you can hand the
> exact mapping to Migo:
>
> | Field your handler reads | Migo template value | Notes |
> |---|---|---|
> | `status` | `{{subscription.status}}` | subscription state → `active` \| `inactive` |
> | `subscriptionId` | `{{subscription.uid}}` | store this |
> | `transactionId` | `{{transaction.uid}}` | idempotency key |
> | `transactionStatus` | `{{transaction.status}}` | charge result (e.g. `approved`) — **distinct** from `status` |
> | `plan` | `{{plan.name}}` | plan **name** string (e.g. `"Órbita Mensual"`), not the id |
> | `amount` | `{{plan.amount}}` | the **plan** amount (renewals), as a **string** (e.g. `"125"`) — not your first-charge amount |
> | `nextRenewalDate` | `{{subscription.nextRenewalDate}}` | **Careful:** arrives as a **JS `Date.toString()` string, NOT ISO 8601** (e.g. `"Tue Jul 28 2026 06:00:00 GMT+0000 (Coordinated Universal Time)"`) — parse defensively |
> | `email` | `{{subscription.email}}` | **Careful:** it **may differ** from the `userId`/`emailTo` you sent — **do not key access on it** |
> | `transactionReference` | `{{transaction.reference}}` | your Migo reference |
> | `paymentDate` | `{{transaction.approvedAt}}` | JS `Date.toString()` string (not ISO) |
> | `customKeys` | `{{transaction.customKeys}}` | may arrive empty (`""`) |
>
> Confirmed in production, the `subsCallback` also flattens a `transaction*` block at the root:
> `transactionCurrency`, `transactionChannel`, `transactionCountry`, `transactionStatus`,
> `transactionCreatedAt`, `transactionAmount` (the last may be empty). None are required by the handler.
>
> **One URL, fields at the root (confirmed in production).** The reference integration points **both** the
> one-time callback and the `subsCallback` at the **same URL**, and the fields arrive at the **root** of
> the JSON body (not nested). Tell the two apart by the **presence of `subscriptionId`**: the one-time
> callback carries `uid` (its transaction id), `status`, and fields like `reference`, `amount`,
> `currency`, `externalId`, `createdAt` — but **no `subscriptionId`** (that absence is the discriminator).
> The `subsCallback` carries `subscriptionId` + `transactionId` + `status`.

**Handler rules:**
- Authenticate with the configured secret on the configured header (`MIGO_CALLBACK_HEADER`), using a
  **constant-time** comparison (the callback is **not** HMAC-signed).
- **Route by callback type first.** The one-time payment callback and the `subsCallback` may hit the
  **same URL**; the `subsCallback` is the one carrying `subscriptionId`. Route on that.
- **The one-time callback fires for every terminal result** (`approved` / `denied` / `refunded` /
  `reversed`) — it arrives **even on a declined payment**. Act on `status`: grant access only on
  `approved`, never on `denied`.
- **Return `2xx` fast.** A non-`2xx` (or a timeout) makes Migo **retry** the delivery — so your handler
  must be **idempotent**.
- `active` → grant/keep access; store `subscriptionId` and `nextRenewalDate`.
- `inactive` → revoke access (terminal dunning event).
- **Idempotency — read this carefully.** On the **first charge**, Migo sends **both** callbacks and they
  carry the **same `transactionId`**. Do **not** dedupe with a single shared "seen `transactionId`" set
  across both types, or the `subsCallback` gets dropped as a "duplicate" and the subscription never links
  (a real bug the reference integration hit). Instead **dedupe per callback type**: for the `subsCallback`,
  upsert on `subscriptionId` (+ `nextRenewalDate`) and run the subscription-linking **independently** of
  the one-time payment handling. Renewals send **only** the `subsCallback`.
- **Reconcile by `transactionId`, not `email`.** The `subsCallback` does **not** include `externalId`,
  and its `email` may not match what you sent. Correlate the subscription to your order via
  `transactionId` — it equals the `uid` you got from Step 1 (which you stored alongside your order /
  `externalId`). Do not tie access to the callback `email`. See **Reconciliation & data model**
  (appendix) for the full DB model.

**Action — reference handler (Node/Express).** Field names below assume your configured payload; rename
to match what Migo confirmed for your account.

```js
import crypto from "node:crypto";

function secretMatches(received) {
  const a = Buffer.from(received ?? "", "utf8");
  const b = Buffer.from(process.env.MIGO_CALLBACK_SECRET ?? "", "utf8");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

app.post("/webhooks/migo", express.json(), async (req, res) => {
  const header = (process.env.MIGO_CALLBACK_HEADER || "x-api-key").toLowerCase();
  if (!secretMatches(req.get(header))) return res.status(401).end();

  const body = req.body;
  try {
    // The subsCallback is the one carrying a subscription id (it may be nested under extraData).
    const subscriptionId = body.subscriptionId ?? body.extraData?.subscriptionId;
    if (subscriptionId) {
      await handleSubsCallback(body);   // subscription state (idempotent, keyed on transaction id)
    } else {
      await handleGenericCallback(body); // one-time payment result
    }
    return res.status(200).end();        // ack fast; do heavy work async if needed
  } catch (err) {
    return res.status(500).end();        // non-2xx → Migo retries; handler stays idempotent
  }
});
```

**Action — self-test with replay payloads.** POST these to your own endpoint to validate your handler
without the real async flow. These match the **real production shape** (root-level fields).

```bash
# subsCallback — active (creation / renewal): grant access, store subscriptionId + nextRenewalDate
curl -X POST "$MIGO_CALLBACK_URL" \
  -H 'Content-Type: application/json' \
  -H "$MIGO_CALLBACK_HEADER: $MIGO_CALLBACK_SECRET" \
  -d '{
    "subscriptionId": "sub_TEST_001",
    "transactionId": "trx_TEST_A1",
    "status": "active",
    "transactionStatus": "approved",
    "plan": "Órbita Mensual",
    "amount": 54.88,
    "email": "customer@example.com",
    "nextRenewalDate": "Sat Aug 08 2026 06:00:00 GMT+0000 (Coordinated Universal Time)"
  }'

# one-time payment callback — the FIRST charge also sends THIS, with the SAME transactionId.
# Its transaction id is `uid` and it has NO subscriptionId → route it as a payment, not a subscription.
# It also fires for non-approved results (e.g. "denied") — act only on "approved". Note: amount is a STRING.
curl -X POST "$MIGO_CALLBACK_URL" \
  -H 'Content-Type: application/json' \
  -H "$MIGO_CALLBACK_HEADER: $MIGO_CALLBACK_SECRET" \
  -d '{
    "uid": "trx_TEST_A1",
    "status": "approved",
    "reference": "Subscription01TEST",
    "amount": "10",
    "currency": "GTQ",
    "externalId": "myapp_customer@example.com_ORDER123",
    "createdAt": "Mon Jul 13 2026 21:58:02 GMT+0000 (Coordinated Universal Time)"
  }'

# duplicate delivery of the SAME subsCallback — must be a no-op (idempotency)
# (re-send the first command; your app state must not change)

# subsCallback — inactive (dunning exhausted): revoke access
curl -X POST "$MIGO_CALLBACK_URL" \
  -H 'Content-Type: application/json' \
  -H "$MIGO_CALLBACK_HEADER: $MIGO_CALLBACK_SECRET" \
  -d '{
    "subscriptionId": "sub_TEST_001",
    "transactionId": "trx_TEST_A2",
    "status": "inactive",
    "plan": "Órbita Mensual"
  }'

# wrong secret — must be rejected
curl -i -X POST "$MIGO_CALLBACK_URL" -H 'Content-Type: application/json' \
  -H "$MIGO_CALLBACK_HEADER: WRONG" -d '{"subscriptionId":"x","status":"active"}'
```

**VERIFY:**
- `active` subsCallback replay → customer has access; `subscriptionId` + `nextRenewalDate` stored
  (and `nextRenewalDate` parsed correctly despite the non-ISO format).
- The **one-time** replay (same `transactionId`, no `subscriptionId`) is handled as a payment and does
  **not** drop or overwrite the subscription (first-charge collision test).
- **Duplicate** `active` subsCallback → **no state change** (idempotent).
- `inactive` replay → access revoked.
- Wrong-secret request → `401`.

**Checkpoint:** all five assertions pass. (One-time only? Only the one-time replay and the wrong-secret
check apply — the `subsCallback` assertions don't.)

---

## 6. Step 3 — Deliver the webview to the customer

**Goal:** get the customer into the hosted webview.

**Action:** send them to the `URL` from Step 1. In a web app, redirect the browser or open it; if you
deliver out-of-band (WhatsApp/SMS/email), send the `URL` string as-is. Do **not** rebuild the URL by
hand — use exactly what Step 1 returned.

**Note on embedding:** the supported pattern is **redirect / new tab**. An `<iframe>` may break due to
`X-Frame-Options`/CSP and third-party cookies — do not rely on iframing the checkout.

**VERIFY:** opening `URL` renders the Migo checkout (card form). If it shows an error page, the `uid`
is wrong or expired — re-run Step 1.

**Checkpoint:** the checkout renders.

---

## 7. Step 4 — Live sandbox payment (end-to-end confirmation)

**Goal:** drive one real successful payment and confirm Migo's callback reaches the endpoint you built
in Step 2. For a **subscription**, confirm the real `subsCallback active` arrives (the subscription was
created); for a **one-time payment**, confirm the `approved` one-time callback arrives and access is granted.

> **Not fully autonomous.** Completing the checkout means entering a card in the webview UI. A **human**
> must do this (or an agent with a browser-automation tool). Your backend logic was already fully
> verified by the replays in Step 2 — this step only confirms the live end-to-end path.

**Action:** in the webview, pay with the **approving** test card `4111111111111111` (any future expiry,
any CVV). Use `4456530000001096` to exercise 3D Secure, or `4000000000000002` to test a decline.

**Expected result:** after approval, Migo redirects back to your return URL with `uid`, `status`,
`reference` in the query, and POSTs to your `MIGO_CALLBACK_URL`: on the first charge you receive
**both** the one-time result **and** `subsCallback active`.

**VERIFY:**
- **Subscription:** your endpoint logged an authenticated `subsCallback` with status `active`; your app
  granted access and stored the `subscriptionId` + next renewal date.
- **One-time:** your endpoint logged the authenticated one-time callback with `status: approved`; your
  app granted access for that order (correlated by `externalId`/`uid`).
- Do **not** rely on the browser redirect as proof — the callback is authoritative.

**Troubleshooting:**

| Symptom | Cause | Fix |
|---|---|---|
| No callback arrives | `MIGO_CALLBACK_URL` not configured, not public, or not HTTPS | Confirm the callback config with Migo; ensure it's the public deployment URL (not `localhost`). |
| `401` on real callbacks | Wrong header name/value | Confirm `MIGO_CALLBACK_HEADER` + `MIGO_CALLBACK_SECRET` match your Migo callback config exactly. |
| Fields missing / named differently than expected | Your account's payload template differs from the representative shape | Align your handler to the exact fields Migo confirmed for your account. |
| Payment approved but no subscription | Plan not attached / wrong key path | Confirm you sent `customKeys.plan.uid`. |

**Checkpoint:** a live sandbox payment produced the expected result in your app — an `active`
subscription, or an `approved` one-time payment.

---

## 8. Acceptance checklist (final gate)

Report the result of each:

- [ ] Step 1 returns `201` (any `2xx`) with `uid` + `URL`; `URL` is read with correct capitalization; a unique `externalId` was sent.
- [ ] Callback endpoint returns `200` (authenticated) / `401` (unauthenticated), and returns `2xx` fast.
- [ ] The webview renders from the returned `URL`.
- [ ] **One-time:** an `approved` one-time callback grants access for that order (`externalId`/`uid`); a non-`approved` result does not.
- [ ] **Subscription:** an `active` callback grants access and stores `subscriptionId` + next renewal date.
- [ ] **Subscription:** a duplicate `active` delivery is a no-op (idempotent, keyed on transaction id).
- [ ] **Subscription:** an `inactive` callback revokes access.
- [ ] A live sandbox payment with `4111111111111111` produced the expected result (subscription `active`, or one-time `approved`).
- [ ] No secrets or card data are hardcoded or logged.

When all boxes pass in sandbox, stop and ask the human before going to production (Section 9).

---

## 9. Go-live (only after human approval)

Switch these, then re-run the acceptance checklist against production:
- API base URL → `https://mw.migopayments.com`; webview base URL → `https://web.migopayments.com`.
- `MIGO_MERCHANT_TOKEN` → production token; `MIGO_CLIENT_SLUG` / `MIGO_PLAN_UID` → production values.
- `MIGO_CALLBACK_URL` + callback config → your production endpoint, configured with Migo for production.
- Use a **real card** for the first live payment (there are no test cards in production).

---

## 10. Reference appendix (self-contained)

### Endpoints

| Purpose | Method & path | Auth |
|---|---|---|
| Create transaction (carries the plan) | `POST {API_BASE}/transactions` | `Authorization: <MIGO_MERCHANT_TOKEN>` (raw) |
| Result to your backend | Migo → `POST {MIGO_CALLBACK_URL}` | your configured auth header + secret (no HMAC; HTTP Basic also supported) |

### Base URLs

| Env | API base | Webview base |
|---|---|---|
| Sandbox | `https://sb-mw.migopayments.com` | `https://sandbox.migopayments.com` |
| Production | `https://mw.migopayments.com` | `https://web.migopayments.com` |

### Subscription statuses (over the webhook)

| Status | Meaning | Your action |
|---|---|---|
| `active` | Created / manual payment / successful renewal | Grant/keep access |
| `inactive` | Dunning retries exhausted (terminal over webhook) | Revoke access |

> `cancelled` (merchant-initiated) and `expired` are **not** delivered over the webhook. A stopped
> subscription can be recovered by a **manual payment** (adding a card and paying reactivates it).

### Callback payload (per-account configuration)

Migo renders the callback body from a Handlebars template configured for your account, so you define
the shape with Migo (there is no fixed schema). Both the one-time callback and the `subsCallback` can
share **one URL**; tell them apart by the presence of `subscriptionId` (the one-time callback does not
carry it — it carries `uid` + `status` + `reference`/`amount`/`currency`/`externalId`/`createdAt`).
Request a `subsCallback` body with `subscriptionId`, `transactionId`, `status`,
`transactionStatus`, `plan`, `amount`, `nextRenewalDate`, `email` — the default template omits the ids,
so request them explicitly (the handler keys idempotency on `transactionId`, **per callback type**).
Fields arrive at the **root** of the body; `nextRenewalDate` is a JS `Date.toString()` string (not ISO).
See Step 2 for the exact field → Migo variable mapping.

### Reconciliation & data model

Three identifiers, each with a different job:
- `externalId` — **your** order id (you generate + send it); echoed back on the **one-time** callback.
- `uid` / `transactionId` — the **charge** id (`uid` in the Step 1 response + one-time callback; the
  **same value** appears as `transactionId` in the `subsCallback`). **Changes every charge.**
- `subscriptionId` — the **subscription** id. **Stable for the subscription's whole life.**

**Direct (one-time) payment** — tie by `externalId`/`uid`: store `externalId ↔ uid` at Step 1; the
one-time callback carries both + `status`; update that one order. Done.

**Subscription** — key your records on the **stable `subscriptionId`**, not on `transactionId`:

```
Step 1 (with plan)  → uid=ABC (externalId=your-order)        [store order ↔ uid]
First charge (two callbacks):
  · one-time         → uid=ABC, externalId, approved
  · subsCallback     → transactionId=ABC, subscriptionId=SUB123, active, nextRenewalDate
       → find your user via transactionId (=uid=ABC), then store subscriptionId=SUB123 ↔ user
Renewal (each cycle) → ONLY subsCallback: same SUB123, NEW transactionId, advanced nextRenewalDate, active
       → look up by subscriptionId, mark renewed, update nextRenewalDate
Dunning exhausted    → subsCallback: same SUB123, inactive
       → look up by subscriptionId, revoke access
```

Suggested tables:

```
users:               id, email, …
subscriptions:       subscription_id (PK = Migo subscriptionId), user_id, status ('active'|'inactive'),
                     plan, next_renewal_date, last_transaction_id
processed_callbacks: (type, transaction_id) UNIQUE   -- idempotency, per callback type
```

**"Who's active / who renewed / who lapsed"** comes from the `subsCallback` `status` + `nextRenewalDate`.
**Careful:** only `active`/`inactive` travel over the webhook — **merchant cancellations and expirations are NOT
webhooked** (Migo emails only). For a robust system, add a scheduled **lease check** as a backstop: if
`next_renewal_date` passed by a grace margin and no new `active` arrived, downgrade the user. The webhook
covers the normal path; the lease covers what Migo doesn't notify.

### Conventions

- Amounts are in **major units** (integer or decimal, e.g. `84` or `54.88`) — **not** minor units. Always send `currency` (`GTQ` default | `USD`).
- The response field is **`URL`** (uppercase).
- Migo **timestamps** (`createdAt`, `nextRenewalDate`, `paymentDate`) arrive as **JS `Date.toString()`
  strings, not ISO 8601** — parse defensively. Some fields (e.g. `amount` in callbacks) arrive as
  **strings** — coerce before use.
- Reconcile with a **unique `externalId` per order** (echoed back on the **one-time** callback). The
  `subsCallback` does **not** carry `externalId` — correlate the subscription via `transactionId`
  (= the `uid` from Step 1). Do **not** reconcile by the callback `email`. An `Idempotency-Key` header
  may or may not be honored by this legacy endpoint — confirm with Migo.
- The callback is **not** HMAC-signed; authenticate via the header + secret configured for your account,
  and return `2xx` fast (non-`2xx` → Migo retries).
- The **callback is the source of truth**, not the browser redirect.

### Optional — subscription self-management panel

To let the customer manage/recover their subscription (add/remove cards, reactivate), deep-link to:
`{WEBVIEW_BASE}/subscriptions/{subscriptionId}` — open in a new tab (not an iframe).

### Environment notes (apply the one that matches your context)

The integration is the same everywhere; only the three items below differ. Everything else in this
guide is identical across environments.

**Replit (cloud IDE with deployments)**
- **Backend:** use a Replit backend (Node/Express, Python, …). Do **not** put the token in the frontend.
- **Public callback URL:** use your Replit **deployment** URL (Deployments), not the dev preview. Register it with Migo.
- **Secrets:** store every `MIGO_*` value in Replit **Secrets** (env vars), never in code.

**Local editor — VS Code / Cursor / Claude Code**
- **Backend:** run your backend locally.
- **Public callback URL:** `localhost` is unreachable by Migo. Expose it with a **public tunnel** or by
  **deploying** the backend — evaluate which fits your setup and choose one. Register that public URL
  with Migo. Note: tunnels often need a one-time setup/token (a human step) and many hand out an
  **ephemeral** URL (valid only while running) — re-register with Migo if it changes.
- **Secrets:** use a git-ignored `.env`. Never commit secrets.

**Frontend-first builder — Lovable / Bolt / v0**
- **Backend:** these are frontend-oriented — **add a backend or serverless/edge function** to hold the
  token, call `POST /transactions`, and receive callbacks. Never call Migo with the token from the browser.
- **Public callback URL:** the deployed function's public URL.
- **Secrets:** the platform's server-side env/secret store.

**Generic — any server you control**
- **Backend:** your app server.
- **Public callback URL:** your public HTTPS route.
- **Secrets:** your platform's secret manager or env vars.

---

### Real sandbox payloads (captured 2026-07-13)

A real, successful subscription end-to-end. Emails are placeholders; secrets/ids abbreviated.
**Correlation key:** the request/one-time `uid` **equals** the `subsCallback` `transactionId`.

Request — `POST /transactions` → `201`:

```json
{
  "amount": 10,
  "currency": "GTQ",
  "userId": "customer@example.com",
  "channel": "web",
  "client": "your-client-slug",
  "externalId": "myapp_customer@example.com_<order-uuid>",
  "customKeys": {
    "emailTo": "customer@example.com",
    "plan": { "uid": "<MIGO_PLAN_UID>" },
    "automaticRedirect": { "approved": { "url": "https://your-app.example.com/checkout/result?status=approved" } }
  },
  "ads": []
}
```

Response: `{ "uid": "LXY…J0", "reference": "Subscription01…TEST", "URL": "https://sandbox.migopayments.com/?orderId=LXY…J0" }`

One-time callback (`approved`) — has `externalId`, **no** `subscriptionId`:

```json
{
  "reference": "Subscription01…TEST",
  "uid": "LXY…J0",
  "country": "GT", "currency": "GTQ", "channel": "web",
  "status": "approved",
  "createdAt": "Mon Jul 13 2026 22:01:33 GMT+0000 (Coordinated Universal Time)",
  "amount": "10",
  "externalId": "myapp_customer@example.com_<order-uuid>",
  "name": "", "type": "001", "device": "macOS"
}
```

`subsCallback` (`active`) — has `subscriptionId` + `transactionId`, **no** `externalId`; `email` may differ:

```json
{
  "plan": "QAReintentos",
  "amount": "125",
  "nextRenewalDate": "Tue Jul 28 2026 06:00:00 GMT+0000 (Coordinated Universal Time)",
  "email": "notifications@example.com",
  "status": "active",
  "paymentDate": "Mon Jul 13 2026 22:57:41 GMT+0000 (Coordinated Universal Time)",
  "customKeys": "",
  "subscriptionId": "374ff976-…",
  "transactionReference": "Subscription01…TEST",
  "transactionId": "LXY…J0",
  "transactionCountry": "GT", "transactionCurrency": "GTQ", "transactionChannel": "web",
  "transactionStatus": "approved",
  "transactionCreatedAt": "Mon Jul 13 2026 22:01:33 GMT+0000 (Coordinated Universal Time)",
  "transactionAmount": ""
}
```

---

### Verified against the `migo-api` source

1. **Plan trigger** — `customKeys.plan.uid` is written at create (`stacks/middleware/.../transactionHandler.ts`)
   and read to trigger subscription creation on approval (`libs/subscriptions-lib/.../subscriptions-lib.ts`).
2. **First-charge amount** — taken from the request `amount` (not a plan `amountPolicy`); adjusted only
   for fixed-day proration or `tokenizeForSub`. Renewals use the plan amount.
3. **Callback payload** — merchant-configured Handlebars template (Mongo `clientCfg.subsCallback.data`);
   default keys `status/amount/plan/nextRenewalDate/email/paymentDate/customKeys`; statuses `active`/`inactive`.
4. **Callback auth header** — merchant-configured (`value.headers`), no hardcoded name; HTTP Basic also
   supported. The generic callback and `subsCallback` build headers identically.

> The only per-account values a human/Migo must confirm are the callback's exact payload fields and the
> auth header name — everything else in this guide is fixed and verified.
