{
  "$comment": "villaPayment3 sales-channel contract. Human pages: /docs/guides/channels. Measured 2026-11-30 against dev@28e5fa8 and the production stack at cee8ff7; the status lines of signedServerCallback and channelRegistry and the gaps are as of 2026-12-01. Keep in step with docs/docs/guides/channels/*.md.",
  "version": "2026-12-01",
  "environments": {
    "production": {
      "branch": "master",
      "mainApi": "https://shop.villamarket.com/api/payment3api",
      "callbackApi": "https://shop.villamarket.com/api/payment3",
      "deployedCommit": "cee8ff7",
      "has": [
        "direct_card",
        "direct_thai_qr",
        "direct_amex"
      ]
    },
    "staging": {
      "branch": "dev",
      "mainApi": "https://villa.kitchen/api/payment3devapi",
      "callbackApi": "https://villa.kitchen/api/payment3dev",
      "has": [
        "direct_card",
        "direct_thai_qr",
        "direct_amex",
        "direct_apple_pay"
      ],
      "note": "Measured 2026-12-01: this address reaches an older dev stack, last deployed 2026-10-04. No hosted checkout (/checkout/... answers 403). The flows it has are as they were then."
    },
    "development": {
      "branch": "dev",
      "mainApi": "https://dev.villamarket.net/api/payment3devapi",
      "callbackApi": "https://dev.villamarket.net/api/payment3dev",
      "has": [
        "direct_card",
        "direct_thai_qr",
        "direct_amex",
        "direct_apple_pay"
      ],
      "note": "Measured 2026-12-01: this address reaches an older dev stack, last deployed 2026-10-04. No hosted checkout (/checkout/... answers 403). The flows it has are as they were then."
    },
    "currentDev": {
      "branch": "dev",
      "mainApi": null,
      "callbackApi": null,
      "has": [
        "direct_card",
        "direct_thai_qr",
        "direct_amex",
        "direct_apple_pay",
        "hosted_checkout"
      ],
      "note": "The stack built from the dev branch. No public address yet: it answers only on its own API Gateway address (ask the payments owner). K Bank returns the customer's browser to the older dev stack (gaps[8]): a hosted checkout payment still finishes, because the checkout asks K Bank itself, but a direct card charge does not. The channel registry is on (two test channels paid through on 2026-12-01) and the signed server callback is on for one test origin."
    }
  },
  "gateways": {
    "kbank": [
      "card",
      "thai_qr"
    ],
    "mpgs": [
      "amex"
    ],
    "stripe": [
      "apple_pay"
    ]
  },
  "rules": {
    "always": [
      "For a Villa order the server prices it: send the route's required fields and never an amount you computed (the hosted checkout takes order ids only; a POST /cardpayment form carries the order's own grandTotal)",
      "Treat the return URL as a hint; confirm on the channel's server",
      "Handle success, failure and the customer who never returns",
      "Send callback as a base only"
    ],
    "never": [
      "Mark an order paid from a browser parameter",
      "Log a card token, gateway body, key, link token or signing secret",
      "Use bypass_order on production without a person's approval",
      "Route anything but Apple Pay through Stripe",
      "Deploy, merge to master or change a secret without a person"
    ]
  },
  "integrations": {
    "direct_card": {
      "gateway": "kbank",
      "methods": [
        "card"
      ],
      "channelAware": true,
      "auth": "none",
      "start": {
        "method": "POST",
        "path": "/cardpayment",
        "contentType": "application/x-www-form-urlencoded",
        "fields": {
          "requiredForVillaOrder": [
            "orderId",
            "userId",
            "customerId",
            "basketId",
            "grandTotal",
            "mid"
          ],
          "requiredForBypassOrder": [
            "orderId",
            "userId",
            "basketId",
            "grandTotal",
            "mid"
          ],
          "addedByKBankScript": [
            "token"
          ],
          "optional": [
            "callback",
            "bypass_order"
          ],
          "note": "validate_input checks token, userId, orderId and grandTotal up front (plus basketId and customerId for a Villa order). basketId and mid are read when the charge is built and recorded, so a request without them fails later. A refused request is HTTP 500 with JSON {error}, not a redirect. For a Villa order the posted grandTotal is compared with the server's total and the result recorded; a difference does not refuse the request, and the server's total is what is charged."
        }
      },
      "browserReturn": {
        "handler": "POST {callbackApi}/callback",
        "redirectsTo": "{callback}/thankyou?orderId={orderId}&status={status}&amount={amount}&chargeId={chargeId}&token={token}",
        "httpStatus": 200,
        "mechanism": "HTML page with meta refresh",
        "status": [
          "success",
          "failure"
        ],
        "defaultCallback": "https://shop.villamarket.com",
        "errors": {
          "500": "POST /cardpayment: JSON {error} when the request is refused; POST /callback: an HTML error page when the charge cannot be read. Neither redirects."
        },
        "statusMeaning": {
          "success": "K Bank's inquiry confirmed this charge for this order and amount",
          "failure": "not confirmed: K Bank declined the charge, or could not be asked"
        }
      },
      "serverTruth": [
        "POST /callback: K Bank's charge inquiry; a confirmed 3-D Secure return starts process-paid (a claim on the charge stops this callback starting it twice)",
        "POST /cardpayment: a successful charge without 3-D Secure starts process-paid from K Bank's charge answer",
        "POST /notify (K Bank, checksum): can start process-paid when the browser return never came; it can be refused or fail, so it is a recovery path, not a guarantee",
        "process-paid skips an order that is already paid; a bypass_order charge never marks a Villa order"
      ],
      "confirmWith": "Villa order: your server reads the order and payment.isPaid is true (a payment header alone is not proof: a PENDING one is written before the charge). Own orders (bypass_order): the signed server callback once it is switched on for your origin (on the current dev stack it is on for one test origin; not on master); until then a person."
    },
    "direct_thai_qr": {
      "gateway": "kbank",
      "methods": [
        "thai_qr"
      ],
      "channelAware": false,
      "start": {
        "method": "POST",
        "path": "/kbank/order",
        "body": {
          "orderid": "string",
          "source": "qr | wechat"
        }
      },
      "browserReturn": {
        "handler": "POST {callbackApi}/qrcallback",
        "redirectsTo": "https://shop.villamarket.com/thankyou?orderId={orderId}&status={status}&amount={amount}&chargeId={chargeId}",
        "note": "fixed to the shop on every stack; automatic only on success"
      },
      "serverTruth": [
        "K Bank QR inquiry at /qrcallback",
        "K Bank POST /thaiqr/notify"
      ]
    },
    "direct_amex": {
      "gateway": "mpgs",
      "methods": [
        "amex"
      ],
      "channelAware": false,
      "start": "villaWalletBackend2 opens MPGS",
      "serverCallback": {
        "method": "POST",
        "path": "{callbackApi}/amex/callback",
        "headers": [
          "X-Villa-Timestamp",
          "X-Villa-Signature: v1=hex HMAC-SHA256(secret, '<timestamp>.<raw body>')"
        ],
        "answers": {
          "200": "recorded (a reported decline is recorded as not paid, MPGS is not asked)",
          "400": "unreadable body",
          "401": "bad or missing signature, block mode only",
          "409": "MPGS does not know or does not confirm the payment",
          "503": "signing secret unreadable, or MPGS has not answered yet: send again"
        },
        "signatureMode": {
          "configured": "flag",
          "flag": "an unsigned or badly signed callback is accepted and logged; an order is marked paid only if MPGS confirms it. The AmexSignatureFlagged metric is emitted for a newly recorded successful callback whose signature is missing or invalid (not for a decline or a replay), before process-paid is invoked",
          "block": "an unsigned or badly signed callback is refused with 401 (the code's default when the variable is not exactly 'flag')"
        },
        "expectedSigner": "villaWalletBackend2. It does not sign yet, which is why the stack runs flag mode."
      },
      "browserReturn": "decided by villaWalletBackend2, not villaPayment3",
      "serverTruth": [
        "MPGS RETRIEVE ORDER"
      ]
    },
    "direct_apple_pay": {
      "gateway": "stripe",
      "methods": [
        "apple_pay"
      ],
      "channelAware": "the page never leaves; redirect fallback goes to Villa web origins only",
      "auth": "Cognito ID token",
      "start": {
        "method": "POST",
        "path": "/stripe/applepay",
        "quote": {
          "orderId": "string"
        },
        "confirm": {
          "orderId": "string",
          "confirmationTokenId": "ctoken_..."
        }
      },
      "answers": {
        "200": [
          "succeeded",
          "processing",
          "requires_action"
        ],
        "400": [
          "not_apple_pay",
          "token_invalid",
          "confirm_refused"
        ],
        "402": "declined",
        "503": "apple_pay_unavailable"
      },
      "stripeReturnUrl": "{Origin header if an https Villa web origin, else https://shop.villamarket.com on master or https://villa.kitchen}/thankyou?orderId={orderId}",
      "villaWebDomains": [
        "villamarket.ai",
        "villamarket.net",
        "villamarket.com",
        "villa.kitchen"
      ],
      "serverTruth": [
        "POST /stripe/webhook (Stripe signature)"
      ]
    },
    "hosted_checkout": {
      "gateway": [
        "kbank",
        "mpgs",
        "stripe"
      ],
      "methods": [
        "card",
        "thai_qr",
        "amex",
        "apple_pay"
      ],
      "channelAware": "with the channel registry: true on the current dev stack (switched on 2026-12-01, two test channels paid through); false on production, which has no hosted checkout",
      "start": [
        {
          "method": "POST",
          "path": "/checkout/sessions",
          "auth": "Cognito ID token",
          "body": {
            "orderIds": [
              "string"
            ],
            "source": "web | app | a registered channel id (only where the channel registry is on: the current dev stack)"
          }
        },
        {
          "method": "POST",
          "path": "/checkout/links",
          "auth": "x-api-key (staff)",
          "body": {
            "orderIds": [
              "string"
            ],
            "expiresInMinutes": "5..10080",
            "reference": {
              "saleId": "string",
              "customerId": "string",
              "note": "string"
            },
            "channel": "optional: a registered channel id (only where the channel registry is on: the current dev stack; not read when off)"
          }
        }
      ],
      "response": {
        "sessionId": "CHK + 12 base32",
        "url": "{mainApi}/checkout/pay/{token}",
        "amount": "integer satang",
        "methods": [
          "card",
          "thai_qr",
          "amex",
          "apple_pay"
        ],
        "channel": "only for a session with a channel: {id, label, returnTo}"
      },
      "browserReturn": {
        "redirectsTo": "{mainApi}/checkout/return/{sessionId}",
        "note": "villaPayment3's own result page, for the flows that reach it (a declined Apple Pay, a failed extra Apple Pay step and an unpaid QR stay on the payment page). Where the channel registry is off (production, the older dev stack) it does not continue to the channel; where it is on (the current dev stack since 2026-12-01) it links back to the session's channel and continues there once the state is paid"
      },
      "confirmWith": {
        "method": "GET",
        "path": "/checkout/status/{sessionId}",
        "states": [
          "open",
          "processing",
          "paid",
          "expired",
          "cancelled",
          "needs_attention"
        ],
        "pollNoFasterThanSeconds": 4
      },
      "serverTruth": [
        "verify_session runs when the result page opens; when the payment page opens or the status is polled while the session is processing; after a card charge that K Bank answers with a charge id and without a refusal, an HTTP 5xx or a 3-D Secure redirect; after an Apple Pay confirmation that Stripe reports as succeeded or processing; when K Bank's QR form posts back; when a gateway notification is handed over; before a session is cancelled or replaced; and from a reconciler every 5 minutes. Page opens, the status poll and a QR post without a charge id are throttled (once every 4 seconds per session)",
        "verify_session may ask nothing: on the page and the poll it is throttled (once every 4 seconds per session), and it asks a gateway only about attempts that can still change and have something to ask about (a card charge id, a PaymentIntent, the MPGS order)",
        "a Thai QR attempt gets its charge id only from K Bank's form post or /thaiqr/notify; without either there is nothing to ask and it needs a person"
      ]
    }
  },
  "callbackBaseRules": {
    "source": "functions/callback/src/payment_redirect.py safe_callback_base (dev branch)",
    "maxLength": 512,
    "accepted": [
      "https:// or http:// with a host",
      "<app scheme>://..."
    ],
    "refusedFallsBackTo": "https://shop.villamarket.com",
    "refused": [
      "schemes: javascript vbscript livescript data file blob about filesystem view-source jar mhtml",
      "no ://",
      "http(s):// without a host",
      "whitespace inside the value, control characters, quotes, < > backslash backtick",
      "longer than 512 characters (code points, after the trim)"
    ],
    "appended": "/thankyou unless the base already ends with it; trailing slashes dropped",
    "normalised": "surrounding whitespace and trailing slashes are removed before the checks"
  },
  "signedServerCallback": {
    "status": "merged to dev on 2026-12-01 (pull request #235); on the current dev stack it is on for one test origin (https://staging.site.villamarket.ai) and delivered a signed event on 2026-12-01 for a sandbox charge on a real staging order: the receiver accepted the signature and marked that order paid; not on master (pull request #248, open)",
    "appliesTo": "bypass_order card charges whose stored callback origin is a configured target",
    "event": "card_charge.settled",
    "version": 1,
    "headers": [
      "X-Villa-Event-Id",
      "X-Villa-Timestamp",
      "X-Villa-Signature: v1=hex HMAC-SHA256(secret, '<timestamp>.<raw body>')"
    ],
    "body": [
      "version",
      "event",
      "eventId",
      "source",
      "branch",
      "orderId",
      "chargeId",
      "status: paid|declined",
      "amountSatang",
      "currency",
      "testCharge",
      "attemptAt",
      "verifiedBy: kbank_inquiry|kbank_notify",
      "verifiedAt"
    ],
    "receiverAccepts": {
      "maxAgeSeconds": 300,
      "maxFutureSeconds": 30
    }
  },
  "channelRegistry": {
    "status": "merged to dev on 2026-12-01 (pull request #231), deployed on the current dev stack behind stack parameter CheckoutChannelRegistry (default off); switched on there on 2026-12-01 and two test channels paid through (after 3-D Secure the return page had to be opened by hand, gaps[8]); not on master",
    "appliesTo": "hosted_checkout only",
    "entry": {
      "where": "SSM parameter /payment3/{branch}/checkout/channels/{id}",
      "value": {
        "label": "string, 1..60 characters",
        "returnBase": "https://host[:port][/path] or scheme://...; an http(s) host is a DNS name of ASCII letters, digits, hyphens and dots (xn-- for an international name) or an IPv4 address, never an IPv6 literal; http only for localhost and 127.0.0.1 and never on master; at most 512 characters; no userinfo, no port outside 1..65535, no query, fragment, whitespace, quote, <, >, backslash or backtick",
        "enabled": true
      },
      "id": "[a-z][a-z0-9-]{1,31}, not \"link\", \"web\" or \"app\" (those are labels, never channels)",
      "cachedSeconds": 60
    },
    "nameIt": {
      "customerSession": "POST /checkout/sessions {\"source\": \"<id>\"}: an id that is not a registered, enabled channel is no error, the session has no channel; \"web\" and \"app\" are labels and never ask the registry; 503 channel_registry_unavailable (nothing created, send it again) when the id could be a channel and the registry cannot be read",
      "staffLink": "POST /checkout/links {\"channel\": \"<id>\"}: 400 channel_unknown when not registered, 503 channel_registry_unavailable when the registry cannot be read"
    },
    "returnUrl": "{returnBase}/thankyou?sessionId={sessionId}&status={success|pending|failure}&state={state}",
    "statusByState": {
      "paid": "success",
      "processing": "pending",
      "needs_attention": "pending",
      "open": "failure",
      "expired": "failure",
      "cancelled": "failure"
    },
    "automaticReturn": "only when the state is paid, once per browser session; otherwise a link. The page shows \"Taking you back to {label}\" once it shows the payment as received (or after 4 seconds at most, if it has not caught up) and moves 2.5 seconds later",
    "confirmWith": {
      "method": "GET",
      "path": "/checkout/status/{sessionId}",
      "adds": [
        "channel {id, label}",
        "returnUrl",
        "unconfirmed (true when the session is not paid and some attempt, the latest or an earlier one, did not end declined, refused, failed or refunded: a gateway may have taken a payment)"
      ],
      "cors": "Access-Control-Allow-Origin: * on this route (and its 404) while the registry is on"
    },
    "rules": [
      "the return address comes from the registry only, never from a request",
      "the return URL is a hint: show paid only when the status route says state is paid",
      "failure means not confirmed, never that nothing was charged",
      "for state open, expired or cancelled, say \"not completed\" only when unconfirmed is false (a status without the field is not proof) and attempt (the latest attempt) is absent, declined, refused, failed or refunded; otherwise a gateway may have taken a payment: not confirmed, do not pay again",
      "no order id in the return URL"
    ],
    "tools": {
      "kit": "channel-kit/channel.py: register, launch, disable and enable are a plan unless --apply; validate, show, list and check write nothing (check reads the registry and fetches the thank-you page and the status route)",
      "referencePage": "channel-kit/thankyou/",
      "oneClick": "CodeBuild project villapayment3-channel-{branch} (deploy/codebuild/ci.yaml, ChannelProjects=yes): RELEASE_SHA, CHANNEL_ID, CHANNEL_LABEL, optional RETURN_BASE, ACTION=plan|launch; not created in AWS"
    },
    "docs": [
      "/docs/guides/channels/channel-return",
      "/docs/guides/channels/launch-a-shop"
    ]
  },
  "gaps": [
    "The hosted checkout result page continues to a registered channel on the current dev stack only (channel registry on since 2026-12-01, two test channels paid through); production has no hosted checkout",
    "Direct Thai QR returns only to https://shop.villamarket.com",
    "Apple Pay redirect fallback accepts Villa web origins only",
    "Direct Amex is routed by villaWalletBackend2",
    "Signed server callback covers bypass_order card charges only; on dev it is on for one test origin and delivered a signed event on 1 Dec 2026 that marked one staging order paid (sandbox charge); not on master",
    "Production has no hosted checkout and no Stripe",
    "callback is free text per direct card request; the channel registry is read by the hosted checkout only",
    "A partner cannot start a hosted checkout with its own credential: a customer session needs a Villa sign-in and a staff link a Villa staff key",
    "On dev the public addresses (/api/payment3dev/* and /api/payment3devapi/* on villa.kitchen, shop.villamarket.com and dev.villamarket.net) reach an older dev stack (last deployed 2026-10-04, no hosted checkout) and K Bank's sandbox returns the customer's browser there (an error page). A hosted checkout payment started on the current dev stack is still confirmed, by the checkout's own K Bank inquiry: open /checkout/return/{sessionId}. A direct card payment (/cardpayment) started there does not finish by itself; in a test the bank's return can be posted by hand to the current dev stack's callback address (measured 2026-12-01)"
  ]
}
