Skip to main content

Signed server callback

Status as of 2 Dec 2026. The signed K Bank card callback is on in production for https://site.villamarket.ai and on the current dev stack for https://staging.site.villamarket.ai. Site Apple Pay uses this same callback on current dev with Stripe test keys. The Stripe site route is not enabled in production.

Who needs it​

Use this callback if your site owns its orders. Villa Payment verifies the payment and notifies your server. Your site updates its own order. A browser redirect or confirm response is not proof of payment. For Villa orders, Villa Payment updates the order directly.

When an event is sent​

  • K Bank card. Use POST /cardpayment with bypass_order=true. The stored callback must match a configured origin. Before delivery, Villa Payment asks K Bank to verify the charge, order, currency, amount and outcome. This path covers card_charge only.

  • K Bank Thai QR (dev only). Use POST /kbank/qr/site with a signed pay ticket, the persisted order ID and total in integer satang, currency: "thb" and the exact configured callbackOrigin. See Starting a Thai QR attempt.

  • Stripe Apple Pay. Use POST /stripe/applepay/site and a signed pay ticket for quote and confirm. Villa Payment checks the signed Stripe webhook and reads back the PaymentIntent and charge. A paid result requires a successful Apple Pay charge for the exact claimed amount. A decline requires a failed charge with nothing received. Pending or mismatched results are not sent.

  • American Express (dev only). Use POST /amex/site to open MPGS Hosted Checkout. After checkout, ask Villa Payment to check the payment using the same signed pay ticket attempt. See Starting an Amex attempt.

WeChat and Alipay do not send signed site callbacks. The legacy Villa Amex flow is not a site callback.

Refunds and disputes are not sent after a Stripe paid callback. Staff use the approved Stripe process and reconcile the original charge against the site's order. A refund does not reopen the paid claim.

The request​

POST <your receiver URL>
Content-Type: application/json
User-Agent: villaPayment3-site-notify/1
X-Villa-Event-Id: <eventId>
X-Villa-Timestamp: <Unix seconds>
X-Villa-Signature: v1=<lowercase hex HMAC-SHA256(secret, "<timestamp>.<raw body bytes>")>

K Bank card keeps the same 14-field v1 body, with no provider field.

{
"version": 1,
"event": "card_charge.settled",
"eventId": "<stable event ID>",
"source": "villaPayment3",
"branch": "master",
"orderId": "ORDER-1234",
"chargeId": "chrg_...",
"status": "paid",
"amountSatang": 7400,
"currency": "THB",
"testCharge": false,
"attemptAt": "<ISO time>",
"verifiedBy": "kbank_inquiry",
"verifiedAt": "<ISO time>"
}

Stripe uses the same v1 event name and adds provider as the 15th field. This is a dev example.

{
"version": 1,
"event": "card_charge.settled",
"eventId": "<stable event ID>",
"source": "villaPayment3",
"branch": "dev",
"orderId": "ORDER-1234",
"chargeId": "ch_...",
"status": "paid",
"amountSatang": 7400,
"currency": "THB",
"testCharge": true,
"attemptAt": "<ISO time>",
"verifiedBy": "stripe_webhook",
"verifiedAt": "<ISO time>",
"provider": "stripe"
}

Thai QR uses qr_charge.settled and adds provider: "kbank_qr".

{"version":1,"event":"qr_charge.settled","eventId":"5aa9731c89346921c68263ab20e8916d","source":"villaPayment3","branch":"dev","orderId":"ORDER-1234","chargeId":"chrg_test_QR1","status":"paid","provider":"kbank_qr","amountSatang":7412,"currency":"THB","testCharge":true,"attemptAt":"2026-12-02T03:00:00+00:00","verifiedBy":"kbank_notify","verifiedAt":"2026-12-02T03:02:00+00:00"}

Amex uses amex_charge.settled and adds provider: "mpgs".

{"version":1,"event":"amex_charge.settled","eventId":"63bbe631b5f40c398bb9006ea87cda94","source":"villaPayment3","branch":"dev","orderId":"ORDER-1234","chargeId":"SAMEX945c6729ebf74bf7445d19426f563d7a","status":"paid","provider":"mpgs","amountSatang":7412,"currency":"THB","testCharge":true,"attemptAt":"2026-12-02T03:00:00+00:00","verifiedBy":"mpgs_inquiry","verifiedAt":"2026-12-02T03:02:00+00:00"}
  • status is paid or declined for card. QR additionally supports expired for explicit bank expiry, never a local timeout. QR paid means K Bank confirmed successful authorization or settlement. All QR statuses require the inquiry to match the K Bank QR charge, its original QR order, THB and the full requested amount. Unknown and pending states do not send events.
  • Amex also supports paid, declined and expired. Treat Amex paid as AUTHORISED, not captured. This build has no capture, void or refund path for site orders. Do not ship as if funds were captured until a capture path exists. The result must match the saved MPGS order ID, THB and the exact amount. Partial capture or an unconfirmed result sends no event. Only an explicit MPGS expiry sends expired.
  • amountSatang is an integer. It is the confirmed amount for paid and the requested amount otherwise. All providers use uppercase THB.
  • For K Bank, verifiedBy is kbank_inquiry or kbank_notify. Non-production K Bank callbacks have testCharge: true. For QR, the field identifies the trigger. Both triggers require a fresh bank inquiry. Production card can also send true for a test charge.
  • Stripe's chargeId is the ch_... charge ID, not the pi_... PaymentIntent ID. For Stripe, testCharge is the inverse of the verified livemode flag. Current dev always sends true.
  • Amex uses verifiedBy: "mpgs_inquiry" and sends testCharge: true because it only queries TEST merchants. Its chargeId is the MPGS order ID, not the browser's session ID.
  • attemptAt is the creation time of the K Bank card record, Stripe PaymentIntent or QR or Amex claim. eventId is stable across retries. It is the first 32 characters of the lowercase hex SHA-256 of <branch>|<chargeId>|<status>.

Verify it​

Verify the timestamp and HMAC before parsing the JSON. Sign the exact bytes received. Compare signatures in constant time. This Node.js example expects rawBody as a Buffer and lowercase header names.

import crypto from "node:crypto";

export function isFromVillaPayment3(rawBody, headers, secret) {
const ts = headers["x-villa-timestamp"];
const got = headers["x-villa-signature"];
if (typeof ts !== "string" || !/^\d+$/.test(ts)) return false;
if (typeof got !== "string" || !/^v1=[0-9a-f]{64}$/.test(got)) return false;

const now = Math.floor(Date.now() / 1000);
const seconds = Number(ts);
if (!Number.isSafeInteger(seconds) || now - seconds > 300 || seconds - now > 30) return false;

const want = "v1=" + crypto.createHmac("sha256", secret)
.update(ts + ".")
.update(rawBody)
.digest("hex");
return crypto.timingSafeEqual(Buffer.from(got), Buffer.from(want));
}

What your receiver does​

  1. Verify the signature, then validate the v1 body. Route K Bank card without provider, Stripe card with provider: "stripe", and QR with event: "qr_charge.settled" and provider: "kbank_qr". Route Amex with event: "amex_charge.settled" and provider: "mpgs". Preserve provider when present.
  2. Refuse test events on your production receiver. Require testCharge: false there. Test events belong only in a test environment.
  3. For paid, match amountSatang exactly to the total on the site's persisted order and require THB. Do not use the signed quote or the browser response as your total. Claim the charge ID in the same write that marks the order paid. It must not belong to another order. Send mismatches to staff.
  4. Apply declined or expired only if you can prove it matches the order's current attempt, including its provider. For Stripe, QR and Amex, also require an exact amount match. For Amex, match the saved MPGS order ID as well. Leave the order unchanged if the attempt is unknown, stale or from another provider. Never downgrade a paid order.
  5. Dedupe on chargeId plus status. Return 2xx for a delivery you already handled.
Your responseWhat Villa Payment does
2xxStops.
408, 425, 429, 5xx, timeout or network errorRetries, with normally three total attempts.
Other 4xxStops without retrying.

Delivery uses HTTPS on port 443, with a five-second timeout per attempt. It does not follow redirects. If delivery fails, staff reconcile the payment. Do not ask the shopper to pay again while the outcome is unknown.

Starting a Thai QR attempt​

Issue the v1 pay ticket from the site's server after authorizing the shopper against the order. For QR, the ticket's attempt is the site's stable nonempty identifier for this QR attempt. Reuse it on request retry, even with a refreshed ticket. Send the same order ID, amount, and origin in the JSON body.

The create response includes qrOrderId, attemptAt (the stored UTC ISO creation time, omitted if no valid time was stored), and widget: {scriptUrl, attributes}. The claim has no lifetime and replays the same bank order for the same attempt. When attemptAt is older than your site's limit, start a new attempt ID and keep the old one so it can still be verified.

Put the returned script and data attributes in your KPayment form. The widget posts the bank QR chargeId to your form action. This is not the qrOrderId from create. To trigger an inquiry, relay the charge ID in another POST /kbank/qr/site with the same signed attempt, adding chargeId to the JSON. A 202 means the result is queued. Continue to show the order as unconfirmed until you verify its signed server callback. Keep the widget's charge ID with the current attempt as a hint so you can match a signed decline or expiry. If you cannot match it to an attempt, reconcile it. The bank can notify Villa Payment even if the widget never returns.

If create returns 409 payment_attempt_exists or 502 qr_outcome_unknown, reconcile the existing attempt. Do not make a new one or switch providers to work around it. For a 409 qr_not_verified on inquiry, wait for the callback or retry the same charge inquiry. Production is not enabled.

Starting an Amex attempt​

Dev requires the MPGS TEST merchant login in the payment3-mpgs-dev secret. Until the payments operator configures a valid login with a merchant ID starting with TEST, valid POST requests to /amex/site return 503 amex_unavailable without reserving an attempt.

On dev, send POST /amex/site with orderId, amountSatang as an integer, currency: "thb", callbackOrigin, siteTicket and returnUrl. Create the v1 pay ticket on your server after you authorize the shopper and read the order's saved total. Use a stable attempt in the ticket. The return URL must be HTTPS on the same origin with no fragment. A browser request must use the same origin. Server requests can omit the browser Origin header.

A 200 response gives you orderId, amountSatang, currency: "THB", chargeId, sessionId and checkoutJsUrl. Save chargeId with the attempt. Load checkoutJsUrl, call Checkout.configure({session: {id: sessionId}}) and then Checkout.showPaymentPage(). After MPGS sends the shopper back, repeat the same POST with "verify":true. Use a valid ticket for the same attempt, amount and origin, and reuse the original return URL. Ignore any resultIndicator on the browser return. A 202 only means the check was queued.

Keep the order unconfirmed until your server verifies the signed result. Your page can poll your own server. You can ask for another check if the result is still unknown. A background job also checks open sessions if the shopper closes the page, for up to 24 hours. This does not turn a timeout into a decline or expiry.

A repeat create returns the same session while it is open and less than 15 minutes old. For 409 payment_attempt_exists or 502 amex_outcome_unknown, reconcile the existing attempt. Do not change the amount, start a new attempt or ask the shopper to switch methods while the outcome is unknown. For 503 amex_unavailable, retry with the same attempt. These are test results only. The Amex site route does not update a Villa order.

Getting your channel switched on​

A payments operator configures the exact HTTPS origin and a receiver URL under that origin. Use a lowercase origin without a path or trailing slash. The operator shares a random, per-target hmacSecret of at least 32 characters with your server. Store it securely on both sides. Keep it out of browsers, logs and repositories.

Use the same origin for the K Bank callback and the Stripe callbackOrigin if both flows use this target. Use separate settings for test and production. A test hostname does not make a live Stripe key safe.