Stripe Apple Pay
Stripe is used for Apple Pay and nothing else. Cards (Visa, Mastercard, JCB, UnionPay) and Thai QR go through K Bank; American Express goes through MPGS. No card form, Google Pay, Link, PayPal or PromptPay ever runs through Stripe.
The Stripe path shares nothing with the K Bank path: separate Lambdas, endpoints, webhook, paid-order processor and secrets.
For how Apple Pay fits next to the other methods, and for payment links and bulk payments, see PAYMENTS.md.
How "Apple Pay only" is enforced
The page is not trusted. Three server-side checks keep the rule
(functions/stripe/src/applepay.py):
| # | Where | Check | If it fails |
|---|---|---|---|
| 1 | POST /stripe/applepay (confirm.py) and the checkout API | The Stripe ConfirmationToken must be a card from an Apple Pay wallet before the server confirms anything | 400 not_apple_pay; nothing is charged |
| 2 | Same | The PaymentIntent allows only the card payment method type (Apple Pay is a card wallet) | Stripe itself refuses any other method |
| 3 | POST /stripe/webhook (webhook.py) | A paid event of ours must have been charged to an Apple Pay card | The payment is refunded (idempotently) and never fulfilled; Sentry error for staff |
| 4 | Same | Its money must still be with us: not refunded (in full or in part) or disputed. Stripe resends an event the processor could not take yet (another run held the order) for up to three days, and staff may refund meanwhile | Acknowledged and never fulfilled; Sentry error for staff |
The webhook check covers payments confirmed some other way, for example with
the client secret of the older /stripepaymentintent flow. It only touches
events that carry our orderId metadata and this stack's branch: the Stripe
account is shared with partner-api (partnerOrderId intents) and with
Dashboard payment links, and those are acknowledged and left alone.
In the Stripe Dashboard, also switch off every other payment method (Settings → Payment methods: leave Cards on for Apple Pay; switch off Link, PayPal, Amazon Pay, Klarna, Google Pay, PromptPay).
Keys (to do once the Stripe account owner hands them over)
Nothing works until the keys are in Secrets Manager. Until then every Apple
Pay endpoint answers 503 apple_pay_unavailable and the checkout page hides
Apple Pay; card, Thai QR and Amex are unaffected.
| Stack | Secret | Keys | Mode check |
|---|---|---|---|
master | stripe-prod | secret_key (rk_live_… or sk_live_…), publishable_key (pk_live_…), webhook_secrets (whsec_…, a list) | A test key on master, or a live key elsewhere, is refused at start |
| every other branch | stripe-dev | the same, test mode (rk_test_, pk_test_) |
./scripts/set-stripe-secret.sh dev # sandbox keys first: test everything on dev
./scripts/set-stripe-secret.sh prod # live keys, when dev is proven
The script prompts with hidden input and never writes a key to disk or to
git. Run it a second time to add the webhook signing secret once the endpoint
exists in Stripe (below). A restricted key (rk_) is preferred. The code
creates and reads PaymentIntents, reads ConfirmationTokens and Charges, and
creates Refunds; grant exactly those. If Stripe refuses a call with a
permission error, its message names the missing permission (check the Lambda
log right after the first test payment on dev).
Only master's functions may read stripe-prod (!If [IsMaster, …] in
template.yaml, pinned by functions/stripe/tests/test_template_secrets.py).
Endpoints
Every path below is under MainApi, so it is reachable on all three CloudFront distributions with no CloudFront change:
| Environment | Domain | API prefix |
|---|---|---|
Production (master) | shop.villamarket.com | /api/payment3api |
| Staging | villa.kitchen | /api/payment3devapi |
| Development | dev.villamarket.net | /api/payment3devapi |
| Path | Auth | Purpose |
|---|---|---|
POST /stripe/applepay | Cognito (order owner) | Storefront Apple Pay: quote, then server-side confirm (below) |
POST /checkout/sessions/{id}/applepay | Checkout link | Apple Pay on the hosted checkout page (payment links, bulk) — see CHECKOUT_API.md |
POST /stripepaymentintent | Cognito | Older client-confirmed flow, kept for pages built on it. Do not build new pages on it |
POST /stripe/webhook | Stripe signature | Stripe → us. Marks orders paid; refunds non-Apple-Pay payments |
POST /stripe/canary | Stripe signature | Delivery heartbeat (proof of concept) |
The webhook is on MainApi with the Cognito authorizer off for that path; its
authentication is the Stripe signature. /api/payment3api/* and
/api/payment3devapi/* forward every header except Host, so
Stripe-Signature reaches the Lambda. Webhook URLs to register in Stripe:
| Environment | URL |
|---|---|
| Production | https://shop.villamarket.com/api/payment3api/stripe/webhook |
| Staging / dev | https://villa.kitchen/api/payment3devapi/stripe/webhook |
Subscribe to payment_intent.succeeded and payment_intent.payment_failed,
then store the endpoint's whsec_ with set-stripe-secret.sh.
Storefront integration (POST /stripe/applepay)
<script src="https://js.stripe.com/basil/stripe.js"></script>
<div id="apple-pay-button"></div>
const API = `${window.location.origin}/api/payment3api`; // master
// const API = `${window.location.origin}/api/payment3devapi`; // dev/staging
async function post(body) {
const r = await fetch(`${API}/stripe/applepay`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: cognitoIdToken },
body: JSON.stringify(body),
});
return { status: r.status, body: await r.json() };
}
// 1. Quote. Only orderId is sent; the amount is the server's.
const quote = await post({ orderId });
if (quote.status !== 200) { showOtherMethods(); return; } // 503: Apple Pay not available yet
const stripe = Stripe(quote.body.publishableKey);
const elements = stripe.elements({ mode: 'payment', amount: quote.body.amount, currency: 'thb' });
const button = elements.create('expressCheckout', {
paymentMethods: { applePay: 'always', googlePay: 'never', link: 'never',
paypal: 'never', amazonPay: 'never', klarna: 'never' },
buttonType: { applePay: 'buy' },
});
button.on('availablepaymentmethodschange', ({ paymentMethods }) => {
if (!paymentMethods?.applePay) showOtherMethods(); // no Apple Pay on this device
});
// 2. Confirm on the server.
button.on('confirm', async () => {
const { error: submitError } = await elements.submit();
if (submitError) return showError(submitError.message);
const { error, confirmationToken } = await stripe.createConfirmationToken({ elements });
if (error) return showError(error.message);
const result = await post({ orderId, confirmationTokenId: confirmationToken.id });
if (result.body.status === 'requires_action') {
const { error: actionError } = await stripe.handleNextAction({ clientSecret: result.body.clientSecret });
if (actionError) return showError(actionError.message);
} else if (result.status !== 200) {
return showError(result.body.error); // 402 declined, 400 not Apple Pay, ...
}
location.href = `/thankyou?orderId=${encodeURIComponent(orderId)}`;
});
button.mount('#apple-pay-button');
Rules for the page:
- Never send an amount. The server prices the order with
calculate-cost-3-masterat quote time and again at confirm time, and refuses to charge when the calculator's total does not reconcile. - Never treat a 200 as "paid". The order is marked paid by the webhook after signature verification. The thank-you page reads the order status from the order API, as for cards.
elements.submit()must run beforecreateConfirmationToken.
| Answer | Meaning |
|---|---|
200 {status: "succeeded" | "processing"} | Charged; the webhook marks the order paid |
200 {status: "requires_action", clientSecret} | Call stripe.handleNextAction({clientSecret}) |
402 {status: "declined", error} | Show error; the customer may try again |
400 {code: "not_apple_pay"} | The token was not an Apple Pay card; nothing charged |
400 {code: "token_invalid" | "confirm_refused"} | Token used or expired; start again from the button |
401 | No Cognito session |
404 | Unknown order, or not the caller's |
503 {code: "apple_pay_unavailable"} | No Stripe keys yet: offer the other methods |
One-time Stripe Dashboard setup
- Register every domain the button renders on (Settings →
Payment method domains):
shop.villamarket.com,villa.kitchen,dev.villamarket.net, andwww.variants if served. Stripe performs Apple's merchant validation: there is no merchant ID, CSR or.well-knownfile. Registering in live mode also registers the domain for sandboxes. Apple Pay silently does not render on an unregistered domain. - Switch off every other payment method (see the policy above).
- Create the webhook endpoints (above) and store their secrets.
Browser reality
| Environment | Apple Pay button |
|---|---|
| Safari on iOS / macOS with a card in Wallet | Yes |
| Chrome / Edge / Firefox on macOS | Yes (applePay: 'always' shows a QR hand-off) |
| Chrome on Android, Windows without an iPhone | No — show the other methods |
HTTPS is required. Apple Pay does not render on http://localhost.
Testing
-
Offline (CI):
cd functions/stripe && python -m pytest tests/— 227 tests, including the Apple-Pay-only checks (tests/test_apple_pay_only.py) and the confirm endpoint (tests/test_confirm.py). No Stripe account is needed. -
Hosted checkout page:
tests/e2e/checkoutdrives the page in Chromium with Stripe.js stubbed (see CHECKOUT_API.md). -
Against Stripe test mode (after
set-stripe-secret.sh dev): Apple Pay needs a real card in a real Wallet even in test mode; Stripe's test card numbers cannot be typed into the Apple Pay sheet. Use a device signed in to an Apple sandbox account, or drive the webhook with the Stripe CLI:stripe listen --forward-to https://villa.kitchen/api/payment3devapi/stripe/webhook
stripe trigger payment_intent.succeededA triggered test event is a typed test card, so the webhook refuses and refunds it — which is the check working.
stripe listenissues its own signing secret: add it towebhook_secretsinstripe-devwhile testing.