Skip to main content

Taking payments at Villa Market

This is the one place that says how money comes in: every way to pay, every payment method, which gateway does what, how a payment becomes "paid", and what to do when a payment needs a person. Details live in the documents it links to.

Every way to pay accepts every method​

Way to payWho starts itOrder id in the URL?Card (Visa, Mastercard, JCB, UnionPay)Thai QR (PromptPay)American ExpressApple Pay
Payment linkStaff (payment-link tool or API)No: /checkout/pay/<token>✅✅✅✅
Website / app, through the checkoutThe signed-in customerNo (the app posts the order id, gets a link)✅✅✅✅
Bulk: several orders, one paymentStaff link or the customerNo✅✅✅✅
Website / app, direct integrations (existing)The storefrontYes/cardpayment/kbank/orderwallet backend → /amex/callback/stripe/applepay

The first three rows are the hosted checkout (functions/checkout): one page, one API, all four methods, one or up to 50 orders. The last row is what the storefront already uses and keeps working unchanged.

MethodGatewayNotes
CardK Bank (KPGW)Embedded K Bank card form; 3-D Secure at K Bank
Thai QRK BankK Bank QR order for the exact amount
American ExpressMPGS (Mastercard Gateway)Hosted Checkout, authorised now and captured by staff after picking
Apple PayStripeStripe takes Apple Pay and nothing else: STRIPE_APPLE_PAY.md

A method whose gateway is not configured on a stack (for example Apple Pay before the Stripe keys are added) is shown as "not available right now"; the others keep working.

The hosted checkout​

flowchart LR
staff[Staff: payment-link tool] -- "POST /checkout/links<br/>(staff key)" --> api
app[Website / app] -- "POST /checkout/sessions<br/>(Cognito)" --> api
api[Checkout API<br/>functions/checkout] -- link --> page[/"/checkout/pay/&lt;token&gt;"/]
page -- card / Thai QR --> kbank[K Bank]
page -- Amex --> mpgs[MPGS]
page -- Apple Pay --> stripe[Stripe]
kbank -- "/callback, /notify, /thaiqr/notify<br/>(checkout_bridge)" --> verify
stripe -- "/stripe/webhook" --> verify
mpgs -- "return URL" --> verify
page -- "poll (throttled)" --> verify
cron[reconcile.py<br/>every 5 min] --> verify
verify{{"verify_session:<br/>ask the gateway"}} -- "confirmed, exact amount:<br/>session paid (once)" --> fulfil[process_paid_checkout_internal<br/>one run per order]
fulfil --> pay[Pay Lambda: order paid] --> notify[e-mail, vouchers, coupons, delivery slot]

Entry points​

Payment link (no order id in the link). Staff create it in the payment-link tool (subrepos/villa-payment-link, PAYMENT_MODE=checkout) or with POST /checkout/links. The link is https://shop.villamarket.com/api/payment3api/checkout/pay/<token>: the 32-character token is the only credential (192 bits; only its SHA-256 is stored). It expires after 24 hours by default (5 minutes to 7 days). A Villa order can be in only one open link at a time; staff cancel a link with DELETE /checkout/links/<sessionId> (refused only for the few minutes a payment on it is being confirmed).

Website / app with the order id. The signed-in customer's app calls POST /checkout/sessions with {"orderIds": ["..."]} and its Cognito token, then opens the returned url (in a browser tab or a web view). Only the customer's own orders are accepted (ownerId = the token's sub; an order without an owner is refused). The session lives 2 hours. Asking again for the same order (the customer closed the page, so its link is gone) replaces the customer's earlier session, unless a payment on it is being confirmed.

Bulk. Give several order ids to either endpoint. Every order is priced, the customer pays the total once, and each order is then marked paid with its own share (its own grandTotal). If one order of the list cannot be paid (paid already, not found, cannot be priced, in another open link), nothing is created and the answer names that order.

Full request and answer reference: CHECKOUT_API.md.

What the customer sees​

The page lists the order (lines, delivery, discounts, total; for bulk, each order and the total) and the four methods. Card and Thai QR open K Bank's own form, Amex goes to MPGS's payment page, Apple Pay is a button on the page. After paying, the customer lands on a result page that waits for the gateway's confirmation ("Confirming your payment…" → "Payment received"). A declined payment says that no money was taken and links back to the payment page.

How a payment becomes "paid"​

  1. The amount is always the server's. Every order is priced with calculate-cost-3-master when the link is made, when the page loads and again when the customer starts paying (in parallel for bulk). Nothing the browser sends sets an amount.

  2. A browser never decides. verify_session asks the gateway itself:

    • card: K Bank charge inquiry (/card/v2/charge/<id>): successful, Authorized or Settled, THB, this checkout's reference, exact amount;
    • Thai QR: /qr/v2/qr/<chargeId>, description Checkout <sessionId> <attemptId>;
    • Amex: MPGS RETRIEVE ORDER for the attempt: AUTHORIZED/CAPTURED, THB, totalAuthorizedAmount exactly the amount;
    • Apple Pay: Stripe PaymentIntent succeeded, amount_received exact, this checkout in its metadata, and charged to an Apple Pay card.

    It runs when the customer returns from the gateway, when K Bank or Stripe notifies us, on the result page's poll (at most once every 4 seconds per session), and every 5 minutes from reconcile.py (a lost 3-D Secure return, a lost webhook, an Amex payment made on the MPGS page).

    A reference that arrives later is matched by the gateway, never by a guess. A charge id from K Bank's QR form, /notify, /thaiqr/notify or a Stripe webhook is attached to an attempt only after the gateway says which session and attempt it belongs to (K Bank's description and reference_order, the PaymentIntent's metadata). So one QR payment is one payment however many times its page was opened, a card charge whose answer was lost is still found when its notify arrives, and a charge id posted by anyone else changes nothing. Only the link's holder can post the QR form (it posts to the link's own URL).

    A reference that arrives while its gateway cannot be asked is not lost: it is kept on the session and the reconciler asks again every 5 minutes, for three days (then unchecked_reference). A hand-over asks only about the attempt it names, so whoever sends one cannot make the checkout ask the gateways about every attempt of a session.

    What the reconciler cannot find by itself: a Thai QR payment whose charge id never reached us. K Bank tells us about a QR payment only through the QR page's form post and /thaiqr/notify; if handing that notify to the checkout fails, /thaiqr/notify answers 503 so K Bank sends it again, and reports the error to Sentry.

  3. Paid once. A confirmed payment marks the session paid with a conditional write: two notifications, two tabs or two methods can never both win. A second payment is flagged (below), never fulfilled twice.

  4. Each order is marked paid at most once. functions/processPaidOrder/process_paid_checkout_internal.py reads the paid session again, prices the order again, writes the payment header through the Pay Lambda (the same single write gate as every other method), then sends the confirmation e-mail and the usual notifications. It is wrapped by paid_once like every process-paid entry point. The payment header keeps the order schema's fields (paymentMethod card-kbank, qr, amex or stripe, as for the storefront flows); the checkout reference is in remark and paymentLog.

K Bank sends every charge's notifications to the same merchant URLs (/callback, /notify, /thaiqr/notify). Those handlers recognise a checkout payment (functions/callback/src/checkout_bridge.py: a charge recorded by the checkout, or a description holding a CHK… reference), ask the checkout to verify it, and never mark anything paid themselves. If the checkout table cannot be read they carry on exactly as before. The Stripe webhook does the same for metadata.checkoutSessionId.

Safety rules​

  • Amounts and ownership are decided on the server, from the stored order and calculate-cost; the calculator's arithmetic is checked before a total is accepted.
  • Links are bearer tokens of 192 bits, stored only as SHA-256. The order id is never in a link. Staff routes need a staff key, stored only as SHA-256 (scripts/create-checkout-staff-key.sh); without the key secret every staff request is refused.
  • Live gateway secrets are readable by master's functions only (K Bank, Stripe: !If [IsMaster, …], pinned by tests).
  • Stripe is Apple Pay only: checked on the ConfirmationToken before any charge, card-only intents, and the webhook refunds anything else.
  • Pages are server-rendered with every value escaped, no inline script, and a Content-Security-Policy that allows scripts only from this origin and the three gateways; frame-ancestors 'none'. A 3-D Secure redirect is followed only to K Bank's own hosts.
  • Logs carry ids, states and amounts in satang only: never a card token, a gateway body, a key or a person's details.
  • One open link per order; a link cannot be cancelled while a payment on it is being confirmed (15 minutes at most). A QR still on a screen or an MPGS page still open does not block a cancel: the answer lists them in stillPayable, and money that arrives through them is flagged (paid_closed_session), never kept quietly.
  • Attempts: opening the QR or American Express page again reuses its attempt while it is fresh; a link takes at most 50 attempts.
  • Records: a session is kept 30 days after its link expires, and 400 days once it is paid, cancelled or needs attention (DynamoDB TTL on purgeAt).
  • Error reports never carry a link token (Sentry events are scrubbed and carry no stack-frame variables).

When a payment needs a person​

The alarm payment3-checkout-needs-attention-<branch> (metric Payment3/Checkout NeedsAttention, the "Villa paid orders" topic) fires with a Sentry error naming the session and the reason. Look the session up with GET /checkout/links/<sessionId> (staff key): it shows every attempt, its gateway reference and what happened to each order.

ReasonWhat happenedWhat to do
amount_mismatchThe gateway confirmed a payment whose amount is not the checkout'sNothing was marked paid. Compare in the gateway's dashboard; refund or adjust the order by hand
second_paymentTwo attempts on one link were both paid (for example a QR paid after a card)The first paid the orders. Refund the second at its gateway
paid_closed_sessionA payment arrived for a cancelled linkRefund it, or fulfil the orders by hand if the customer still wants them
not_apple_payA Stripe payment that was not Apple PayRefunded automatically; check the refund in Stripe
refund_failedThat automatic refund failedRefund it in the Stripe Dashboard
card_charge_unanswered, apple_pay_unansweredThe gateway did not answer the charge call (or answered HTTP 5xx)A charge may exist. Its notify or webhook is still matched automatically; if none comes, search the gateway for the session id before the customer retries
fulfil_invoke_failedA paid order could not be handed onRetried every 5 minutes by reconcile.py; alarm clears when done
payment_unresolvedA gateway payment never became final in 24 hours, or a card or Apple Pay request stopped half way (the gateway may have charged)Look the session id up in the gateway's dashboard and settle it by hand
unmatched_payment, second_charge_for_attemptA paid gateway payment names this session but no attempt the checkout made (for example a shop /cardpayment charge carrying the session id), or a second one for an attemptLook it up in the gateway; refund it, or fulfil by hand
unchecked_referenceA payment reference arrived and its gateway could not be asked about it for three daysLook the reference up in the gateway; settle it by hand

A second payment for an order that the shop's own flow (or another link) had already marked paid is escalated too, by the order processor: "second payment for an order that is already paid". Refund the checkout payment.

A paid order whose processor run failed raises the process-paid alarms instead (payment3-process-paid-needs-person-<branch> and payment3-process-paid-needs-person-event-<branch>; see functions/processPaidOrder/docs/RUNBOOK_PROCESS_PAID_NEEDS_PERSON.md). An order whose processor run (the checkout's or another payment's) is still going, or failed or stopped and waits for a person, is noted waiting on the session and handed on again every 5 minutes. A failed or stopped run is reported once per session, naming it (checkout payment waits behind a held claim); once that run is settled, the link payment is applied, or escalated as a second payment.

The shop's own Apple Pay payments (Stripe, outside the checkout) follow the same rule: an order that another payment already paid is never written again, and the second payment is escalated ("[Stripe Second Payment]" e-mail and payment3-process-paid-needs-person-event-<branch>). Refund one of the two. An Apple Pay payment that meets another run of the order while the order is unpaid fails, so Stripe sends it again (for up to three days) until that run is settled; it is reported once, with its PaymentIntent, and a payment refunded or disputed meanwhile is never fulfilled.

Amex payments made through the checkout are MPGS orders whose id is the attempt id (CHK…A01), not the Villa order id. Staff capturing after picking find it in MPGS under the paymentId of the order's payment header.

Go-live steps​

Merging to master deploys to production, and every new piece is safe to deploy before it is used: nothing changes for the storefront, no link exists until staff create one, and Apple Pay stays unavailable until its keys exist.

  1. Deploy to dev and make a staff key there: ./scripts/create-checkout-staff-key.sh dev saletool.
  2. Card and Thai QR on dev: create a link for a test order and pay it with the K Bank sandbox card (5444 8801 1727 6129, any future expiry and CVV, OTP 123456) and with the sandbox QR. Use an order whose total is not a whole number of baht at least once (the checkout sends satang to K Bank; the storefront's QR flow sends whole baht).
  3. Amex on dev needs the MPGS TEST merchant's API password in dev-walletApiConfig (see subrepos/villa-payment-link/docs/proposals/vpl-8o2-amex-mpgs-test-merchant.md). The dev wallet secret holds the real merchant today: do not test Amex on dev until it holds the TEST one.
  4. Apple Pay: when the Stripe keys arrive, follow STRIPE_APPLE_PAY.md ("Keys"): set-stripe-secret.sh dev, register the domains, create the webhook endpoints, test on a real iPhone, then the same for prod.
  5. Production: ./scripts/create-checkout-staff-key.sh prod saletool, set CHECKOUT_STAFF_KEY in the staff tool, make one small real link and pay it.
  6. FillOrderIdNotify runs on dev from the first deploy; switch it on for master in template.yaml after a clean week on dev.
  7. Archive the old repositories (villa-payment-link, payment3-test-ui, villa-payment3-automation): their README already points here.

Testing​

WhatCommand
Checkout (every entry point, every method, money edge cases)cd functions/checkout && python -m pytest tests
Checkout in a browser (Chromium, gateway scripts stubbed)node functions/checkout/tests/e2e/checkout.e2e.mjs
Stripe (Apple Pay only)cd functions/stripe && python -m pytest tests
K Bank / Amex / wallet callbacks and the checkout bridgecd functions/callback && python -m pytest tests --noconftest --ignore=tests/test_query_index.py
Everything CI runs.github/workflows/monorepo-tests.yml (dependencies: requirements-ci.txt)

None of these reach AWS or a gateway: DynamoDB is moto and the gateways are doubles. Live tests that need production credentials run only with VILLA_ALLOW_LIVE_KBANK_TESTS=1.