Appearance
Payment Processing
Flow ID: CF-08 Module(s): checkout, Checkout domain Complexity: Very High Last Updated: 2026-11-16 — 4.130.0 resync: a REST
klarna_paymentsorder Klarna accepts at create-order is now confirmed insideplace-order(PaymentInitResult::confirmed,PlaceOrderServicecallsconfirmPayment(), responsestatusPAID, #737, decision record) and theKlarnaAdapterdocblock no longer claims confirmation reduces stock (Known Issue 6 resolved); Stripe now pins the API version throughStripeApiVersionon stripe-php^22.1(#739, decision record), acceptsno_payment_requiredas settled and logs a failed gateway check; #1043 and #1044 limits and a legacystripe()SDK-guard asymmetry added to Known Issues; the Klarna citations in the Known Issues and return-handler sections re-anchored; previous: 2026-11-04 — 4.129.0 resync: a customer's cancel of a PayByBank order now cancels at the gateway first throughPaymentConfirmationService::cancelByCustomer()and can answer 502payment_cancel_failed(#795); the ApcoPay and Piraeus return handlers no longer cancel on an unverified request (#958); the success pages act only on the order the session placed, and the paid/cancelled transitions are conditional claims (#962,claimPaid()/claimCanceled());PaymentConfirmationService.php,Checkout.phpandAdv_checkout.phpcitations re-anchored; previous: 2026-10-13 — 4.127.0 resync:payment-methodsnow publisheskind/redirectMethodand a label for every payway (#732,PaymentAdapterInterface::presentation()replacessupportsRedirect()), PayPal Advanced for headless clients (#916:confirm-paymentcaptures and settles on the sum of captures,brand_namefromsite_name), client return/cancel URLs stored on the order instead of the callback URL (#915),Checkout.phpcitations re-anchored; previous: 2026-10-02 — 4.125.0 resync: canonical REST confirm/cancel payment contract (#880PaymentTransition, race answers,confirmedvsstatus), Viva charge-type allow-list and registration gate (#865), PayByBank expiry andpbbExpiresAt(#870), citation refresh; previous: 2026-09-29
Business Overview
Payment processing handles 19 payment method registrations (18 distinct adapter classes) through a central dispatcher. After checkout confirmation (CF-07), the Adv_checkout::run() method routes to the appropriate gateway on the legacy path; the REST path goes through PaymentInitializerFactory. Each follows: create order → redirect/render form → handle callback → update status.
All 18 adapter classes now have modern REST adapters registered via PaymentInitializerFactory. The legacy Adv_checkout::run() switch statement remains the path for storefront (non-REST) checkout; both paths share the same underlying gateway libraries.
API Reference
Modern REST Endpoints
| Method | Path | Auth | Description |
|---|---|---|---|
| POST | /rest/checkout/place-order | Guest/Customer | Create order and initialize payment in one call; accepts optional returnUrl/cancelUrl (or return_url/cancel_url) for the customer's own post-payment landing pages; returns {orderId, orderSerial, status} plus an optional paymentRedirect object (omitted when the payway has no redirect) and an optional transactionId (the gateway's own reference; omitted when the adapter returns none — #724). There is no redirectUrl key (src/Domains/Checkout/PlaceOrderResult.php:37-58) |
| GET | /rest/checkout/payment-methods | Guest | Discover the payment methods the merchant selected for external frontends; returns {"paymentMethods":[{key, label, kind, redirectMethod, requiresRedirect}]} (#732) |
| GET | /rest/checkout/payment-status/{orderId} | Customer | Check payment result after redirect |
| POST | /rest/checkout/confirm-payment/{orderId} | Customer | Verify payment with the gateway and confirm via PaymentConfirmationService (contract below) |
GET /rest/checkout/payment-methods — Route rest_routes.php:1758 (+ locale-prefixed :1767); added in commit 633ae4bd7 (#228). Controller src/Rest/Checkout/Controllers/Checkout.php:1875-1909 (OA attribute :1811-1874) calls PaymentInitializerFactory::create() then PaymentInitializer::getRegisteredPaymentMethods(). The response body is {"paymentMethods":[...]} (Checkout.php:1908). It returns only the payways the merchant selected in METHODS.PAYWAY_EXTERNAL (Settings → Payments, #672) that also have a registered adapter (credentials configured, #673), in the merchant's saved order rather than registration order; the offline adapters are filtered by the same selection. An unset/empty key yields an empty list (fail-closed, no fallback to METHODS.PAYWAY), and place-order refuses anything outside the list with 422 payway_not_available (#749; OA text Checkout.php:1825).
Presentation fields (#732). Each entry carries kind, redirectMethod and the legacy requiresRedirect (Checkout.php:1900-1905). The adapter declares them: PaymentAdapterInterface::presentation() returns a PaymentPresentation (src/Domains/Checkout/Payment/PaymentPresentation.php, PaymentAdapterInterface.php:10-18), and PaymentInitializer::getRegisteredPaymentMethods() copies kind, redirectMethod and requiresRedirect into each registered entry (PaymentInitializer.php:126-152). PaymentKind (src/Domains/Checkout/Payment/PaymentKind.php) is open-ended: a value is never redefined, new ones may be added, and a client should skip a kind it does not know.
kind | Meaning for the client | Payways |
|---|---|---|
offline | nothing to pay online; the order is complete at placement (PENDING_ACCEPTED) | delivery, bank_transfer, paid_at_store |
bank_code | UNPAID at placement; the customer pays later with the bank code returned with the order | paybybank |
redirect | navigate (redirectMethod GET) or auto-submit a form (POST) to paymentRedirect.url | GET: stripe, vivawallet, paypaladvanced, paypal, xpay, jcc, iris, ethniki_nbgpay; POST: alpha, eurobank, piraeus |
embedded | keep the customer on the page: an iframe of paymentRedirect.url, or the gateway's JavaScript SDK with params | apcopay, ethniki, ethniki_ee |
widget | an in-page widget first; placement may then answer with a redirect or complete in place; when Klarna answers fraud_status: ACCEPTED the place-order response already carries status: PAID (OA text Checkout.php:1253-1256, #737) | klarna_payments |
requiresRedirect is kept for existing clients and is derived from kind (PaymentPresentation::requiresRedirect() -> PaymentKind::handsToGateway(), PaymentKind.php:29-32), so it is true exactly for redirect, embedded and widget and cannot disagree with kind. The redirectMethod of a redirect adapter must match the PaymentRedirect its initializePayment() returns (PaymentAdapterInterface.php:10-18). PAYMENT_METHOD_LABELS (Checkout.php:77-97) now holds an English fallback label for every registrable payway except the retired proxypay (#732); label falls back to the raw key only for a payway the map does not list (:1901), and a client should localise by key.
POST /rest/checkout/confirm-payment/{orderId} contract (Checkout.php:1722, OA :1668-1721): for Viva Wallet the server verifies the payment itself by the order code stored in tran_ticket (Viva merchant GET /api/transactions/?ordercode=, Basic MERCHANT_ID:API_KEY, src/VivaWallet/OrderTransactions.php:36-52); the endpoint reads no request body, a client transactionId is ignored, and empty merchant credentials answer confirmed:false (#865, verifyVivaWalletPayment() Checkout.php:2148, with the empty-credentials arm at :2156-2158; settle checks :2223-2290). Since #754 PaymentConfirmationService::confirmPayment() no longer writes shop_order.is_paid (product-owner ruling in the code comment, src/Domains/Checkout/PaymentConfirmationService.php:44-62), and isPaid was removed from the payment-status and confirm-payment responses (paymentStatus() Checkout.php:1621-1666, confirmPayment() :1722-1809). Legacy gateway handlers still set it via set_is_paid() (Adv_order_model.php:1950-1952).
Confirm / cancel payment contract (#880) — canonical
This section is the canonical home for the REST confirm/cancel payment contract; CF-07, CF-09, SY-03 and SY-16 link here.
PaymentTransitionresults.PaymentConfirmationService::confirmPayment()andcancelPayment()return the enumPaymentTransition(src/Domains/Checkout/PaymentTransition.php:14-30):Applied(this call moved the order and ran the side effects),AlreadyApplied(the order was already in the target state),Rejected(the order is missing or in a status the transition cannot start from).isSettled()(:26) is true for everything exceptRejected. The class docblock is atPaymentConfirmationService.php:15-24.- Confirm is a conditional write.
confirmPayment()callstransitionStatus($orderId, 'PENDING', 'PAID', $updateData)(PaymentConfirmationService.php:84). OnlyAppliedreloads the order and dispatchesOrderPaid(:107-120);PENDING_ACCEPTEDcounts asAlreadyApplied(:87-91). - Cancel is atomic with the stock release.
cancelPayment()wrapstransitionStatus($orderId, 'PENDING', 'CANCELED', ...)(:173) andrestoreStockForOrder(:177) intransactional(...)(:172-180). A failed release rolls the cancel back, leaves the orderPENDINGand throwsRuntimeException(:182-184). A race loser returnsAlreadyApplied(alreadyCANCELED) orRejectedand does nothing (:186-192); only the winner dispatchesOrderCanceled(:201) and returnsApplied(:210).OrderCanceledfires after the cancel transaction commits, which is why the gift-stock listener keeps its own transaction (src/Domains/Order/Event/Listeners/RestoreGiftStockOnCanceledListener.php:44-52). Stock adjustments are ordered byproduct_code_id(src/Domains/Checkout/StockService.php:96), so concurrent adjustments queue on theproduct_codesrow locks instead of deadlocking. - Confirm race answers. The loser of a confirm race answers
confirmed:falsewithreasonalready_paid(AlreadyApplied) orinvalid_status(Rejected) (Checkout.php:1768-1794); before #880 it answeredconfirmed:true. The up-front non-PENDINGarm (:1741-1753) has the same shape, but answersalready_paidonly forPAIDandinvalid_statusfor every other status includingPENDING_ACCEPTED(:1750), whereas the race arm mapsAlreadyApplied(which includesPENDING_ACCEPTED,PaymentConfirmationService.php:87-91) toalready_paid(Checkout.php:1791). ARejectedrace is logged at error level (the order was paid at the gateway but is no longerPENDING, so it was not markedPAIDand needs a refund or a manual decision,:1776-1785). confirmedis not the verdict,statusis.confirmedmeans "this call verified the payment with the gateway";statusis the payment verdict. An order can come backstatus: PAIDwithconfirmed: false(OA textCheckout.php:1675-1679). Settled isPAIDorPENDING_ACCEPTED;PENDINGis awaiting payment.- Cancel-payment answers.
POST /rest/checkout/cancel-payment/{orderId}returns 404 only for an unknown or not-owned order (Checkout.php:1977-1980). ACANCELEDorder answers 200canceled:falsewithreasonalready_canceled(:1985-1993); any other non-PENDINGorder answers 200canceled:falsewithreasoninvalid_status(:1995-2003). The loser of a cancel race answerscanceled:falsewithalready_canceledorinvalid_status(:2029-2043). - Customer order cancel.
Order::canceltreats onlyAppliedas success (src/Rest/Order/Controllers/Order.php:319-322), so a race loser gets 400 "cannot be cancelled in its current status" even though the order isCANCELED. - Customer cancel of a Pay by Bank order (#795).
POST /rest/checkout/cancel-payment/{orderId}andPOST /rest/order/order/{id}/cancelgo throughPaymentConfirmationService::cancelByCustomer()(src/Domains/Checkout/PaymentConfirmationService.php:134). For aPENDINGpaybybankorder it cancels at PayByBank first. If the gateway does not confirm and the order is stillPENDING, it throwsPaymentCancelFailedException: the order staysPENDINGwith its stock reserved, and both endpoints answer502witherror.codepayment_cancel_failed.cancelPayment()stays gateway-agnostic, because the PayByBank poll calls it for orders the gateway already cancelled. The 502 is built inCheckout.php:2010-2019andOrder.php:323-333.PayByBankGatewayCanceller::cancel()(src/Domains/Checkout/Payment/PayByBankGatewayCanceller.php:25-52) returns aPayByBankCancelOutcome(Cancelled,RefusedorUnreachable): a missing API key or URL isUnreachable(:27-31); a 200 is downgraded toRefusedwhen the gateway reports the orderPAIDorCOMPLETED(:36-43); a refusal is re-checked against the gateway status and becomesCancelledif it readsCANCELLEDorCANCELLED_BY_MERCHANT(:49-51). Thepbb_loggingrow (called_for = 'cancel') is written best-effort byPayByBankLog::recordCancel()(src/Domains/Checkout/Payment/PayByBankLog.php:16-29). The expiry sweep (AdvCancelIncompleteOrders.php:154) and the admin batch cancel (Adv_order_model::setBatchCanceled(),Adv_order_model.php:3395, canceller call at:3427) call the canceller too, but cancel locally whatever it answers. - Callers of the service.
Checkout.php:1760(confirm) and:2006(cancel, throughcancelByCustomer()),Order.php:319(the same),PollPayByBankStatus.php:107,:121,:128, and, forconfirmPayment()only,PlaceOrderService.php:857(a gateway-confirmed order, #737, next bullet) andKlarnaNotificationHandler.php:103(the Klarna notification arm, see CF-09). - Klarna synchronous confirmation (#737).
KlarnaAdapter::initializePayment()returnsPaymentInitResult(status: 'PENDING', ..., confirmed: ($response['fraud_status'] ?? null) === 'ACCEPTED')(KlarnaAdapter.php:172-177);PaymentInitResultgainedpublic readonly bool $confirmed = false(src/Domains/Checkout/Payment/PaymentInitResult.php). Whenconfirmedis true and the optionalpaymentConfirmationServiceis wired,PlaceOrderService, after reserving stock (reduceStockForOrder():823, #282), callsconfirmPayment($orderId, array_filter(['transactionId' => ...]))(PlaceOrderService.php:844-860). The responsestatusbecomesPAIDunless the transition isRejected(AlreadyAppliedalso answersPAID,:862-863); aRejectedkeepsPENDINGand logsPayment confirmed by %s but the transition was rejected ...at error level (:864-873); a thrown exception is caught, logged as... but not recorded ...and leaves the orderPENDING, never a 500 (:874-885). The service is an optional trailing constructor argument (:139) wired explicitly insrc/Domains/Checkout/container.php:49-55(its comment notes an autowire miss would pass null). The place-orderstatusmay therefore bePAID(Checkout.php:1253-1256;application/config/rest_api_versions.php:154, REST API 1.126). Confirmation never stampsis_paid(#754). An order Klarna leaves in fraud review is confirmed later by the notification arm. See the decision record. - Stripe API version and settlement (#739).
src/Stripe/StripeApiVersion.phpreturns\Stripe\Util\ApiVersion::CURRENTfromcurrent()afterassertSupported(Stripe::VERSION), which throwsRuntimeExceptionwhen the installed SDK is older thanMINIMUM_SDK_VERSION = '22.1.0'(an old SDK would otherwise silently run its own older API version;StripeApiVersion.php:21-41;composer.json:65"stripe/stripe-php": "^22.1"). The version is pinned atStripeCheckout::newClient()('stripe_version',src/Stripe/Checkout/StripeCheckout.php:297), inStripeAdapter(StripeAdapter.php:34) and in the RESTverifyStripePayment()(Checkout.php:2100); it is not configurable and has no registry key.verifyStripePayment()settles when the sessionstatusiscompleteandpayment_statusispaidorno_payment_required(Checkout.php:2091-2106), so a zero-total order now settles (rest_api_versions.php:153); the key comes from the test seamstripeSecretKey()(:2108).verifyWithGateway()now logs a failed gateway check withlog_message('error', ...)before answering unconfirmed (:2075-2086). The legacyAdv_checkout::stripeResponse()likewise treatsno_payment_requiredlikepaid(Adv_checkout.php:3380-3381) and catches the SDK-guardRuntimeException: it logscritical("the order may be paid at Stripe", with thesession_id) and answerserror_404(), leaving the orderPENDINGfor a manual check (:3353-3362). See the decision record. - Viva verification and charge types (#865). A Viva transaction settles the order only when it names the stored order code, has
StatusIdF(Checkout.php:2123, tested at:2234), has a charge type onVIVA_CHARGE_TRANSACTION_TYPES(:2135, which now includes 42 BitPay and 58 Payconiq; 68 Pay On Delivery is deliberately excluded) and its amount matches the order total (:2268-2306). A completed transaction of an unlisted type is logged and does not confirm the order (:2241-2255). - PayPal Advanced capture and settle (#916).
verifyWithGateway()hands apaypaladvancedorder toverifyPayPalPayment()(Checkout.php:2054-2089with the PayPal arm at:2072-2073,:2313-2324), which builds aPayPalOrderSettlementand callssettle(tran_ticket, total_vat, order_currency)(:2319-2323). The class (src/PaymentGateways/PayPal/PayPalOrderSettlement.php) reads the PayPal order; when it isAPPROVEDit checks that the purchase-unit amounts sum to exactly the order total in the order currency and only then callscaptureOrder()(the call carriesPayPal-Request-Id, so a repeated or concurrent confirm does not charge twice); it then re-reads the order and decides from that read, never from the capture response (PayPalOrderSettlement.php:38-75). It settles only when theCOMPLETEDcaptures, summed across every purchase unit in minor units, equal the order total in the order currency (holdsSettlingCapture(),:166-203). An approved order for another amount or currency is not captured (logged at error level) and a completed capture that does not match is logged for a refund; both answerconfirmed:falsewith the order stillPENDING, which a client cannot tell from an approval that has not happened yet. The order is then cancelled by the incomplete-orders job after 180 minutes (SY-03). Before #916 the arm only looked for a capture, which the headless path never made, so an approved order stayedPENDING. - Registration gate and refusal.
vivawalletis registered over REST only whenhasMerchantCredentials()is true (PaymentInitializerFactory.php:167-169,src/VivaWallet/Config.php:119).place-orderrefuses a payway with no registered adapter with 422payway_not_availablebefore any write (src/Domains/Checkout/PlaceOrderService.php:181-183). - PayByBank expiry (#870). The gateway
payment_code_lifecomes fromPayByBankExpiration::secondsFrom(), called inPayByBankClientFactory::create()(src/Domains/Checkout/Payment/PayByBankClientFactory.php:20), the one place the client is built:PaymentInitializerFactory.php:623,PollPayByBankStatus.php:146andAdvFactories::payByBank()(ecommercen/core/AdvFactories.php:41-45) all go through it. A missing, empty, non-numeric or non-positivePAY_BY_BANK/EXPIRATIONsetting falls back to 24 h (DEFAULT_SECONDS = 86400,src/Domains/Checkout/Payment/PayByBankExpiration.php:42;secondsFrom:74-81, the<= 0test at:76).GET /rest/order/orderpublishespbbExpiresAt(src/Rest/Order/Controllers/Order.php:90-99,src/Rest/Order/Resources/Order/Resource.php:112and:239-242), computed bypaymentCodeExpiresAt()(PayByBankExpiration.php:108-127); it isnullunless the order ispaybybankwith a code issued, and alsonullwhenentry_datetimeis unparseable (PayByBankExpiration.php:120-124). The legacy job gets its client from the same factory (ecommercen/job/libraries/AdvPayByBankGetStatus.php:154).
POST /rest/checkout/place-order 422 errors: besides payway_not_available and loyalty_redemption_exceeds_order_total, a payway the chosen transporter does not accept (cash on delivery with a transporter that does not take it) returns 422 payway_not_allowed_for_transporter with error.payway and error.transportId (#338, Checkout.php:1451-1465).
POST /rest/checkout/place-order — returnUrl/cancelUrl (#734): two optional body parameters, documented at Checkout.php:1141 (returnUrl) and :1175 (cancelUrl), name where the customer's browser should land after payment succeeds or is cancelled/fails — never a gateway-facing field. See ## Payment Confirmation below for how (and for which gateways) the redirect is actually delivered.
Browse endpoints interactively in the API Reference.
Legacy
| Type | Path | Purpose |
|---|---|---|
| Internal | checkout->run($checkoutData) | Payment dispatch |
| Callback | /checkout/get_response/{gateway} | Gateway returns |
| Webhook | /checkout/handle/{gateway}/{action} | Async notifications |
Payment Gateways
All 19 registrations now go through PaymentInitializerFactory. Registration order: PaymentInitializerFactory.php:67-89. Any missing settings helper or empty required credential causes the adapter to be silently skipped — that payway will not appear in GET /rest/checkout/payment-methods or be accepted at POST /rest/checkout/place-order.
| Adapter | Key | kind (#732) | Gate |
|---|---|---|---|
| DeliveryAdapter | delivery | offline | Always |
| BankTransferAdapter | bank_transfer | offline | Always |
| PaidAtStoreAdapter | paid_at_store | offline | Always |
| StripeAdapter | stripe | redirect (GET) | STRIPE.SECRET_KEY; initializePayment() pins StripeApiVersion::current() and disables telemetry (StripeAdapter.php:34-35) and sends allowed_payment_method_types => ['card'] (:38, card only) (#739) |
| VivaWalletAdapter | vivawallet | redirect (GET) | getVivaWalletMergedSettings() OAuth creds; REST registration also requires MERCHANT_ID + API_KEY (#865, PaymentInitializerFactory.php:167-169); without them the adapter is not registered and place-order refuses the payway with 422 payway_not_available |
| PayPalAdapter | paypaladvanced | redirect (GET) | getPaypalAdvancedSettings() client_id + secret; selectable for external frontends since #916 (getExternalPayWays(), eshop_helper.php:439-445) |
| PayPalExpressAdapter | paypal | redirect (GET) | getPaypalSettings() client_id + secret |
| JccAdapter | jcc | redirect (GET) | getJccSettings() username + password |
| IrisAdapter | iris | redirect (GET) | getIrisSettings() username, password, customerCode, checkDigit |
| KlarnaAdapter | klarna_payments | widget | getKlarnaSettings() username + password |
| EthnikiAdapter | ethniki | embedded | getEthnikiBankSettings() publicKey + privateKey |
| EthnikiNbgPayAdapter | ethniki_nbgpay | redirect (GET) | getEthnikiNBGPaySettings() appID + appKey |
| EthnikiEEAdapter | ethniki_ee | embedded | getEthnikiEEBankSettings() merchantId, directApiKey, host, apiVersion |
| XPayAdapter | xpay | redirect (GET) | getXPaySettings() API_KEY |
| PiraeusAdapter | piraeus | redirect (POST) | getPiraeusBankSettings() → PiraeusConfig::isConfigured() |
| CardLinkAdapter (Alpha) | alpha | redirect (POST) | getAlphaBankSettings() ID, SSK, Submit |
| CardLinkAdapter (Eurobank) | eurobank | redirect (POST) | getEurobankSettings() merchantId, secret, url |
| ApcoPayAdapter | apcopay | embedded | getApcoPaySettings() profileId, secret, merchantId, merchantPassword |
| PayByBankAdapter | paybybank | bank_code | getPayByBankSettings() payByBankApiKey + payByBankApiUrl |
19 registrations, 18 distinct classes. Note: KlarnaAdapter key is klarna_payments (not klarna); PayPalExpressAdapter key is paypal (distinct from paypaladvanced); PayByBankAdapter::presentation() is bank_code (PayByBankAdapter.php:44-47) — it returns a bank payment code, not a redirect URL. Every adapter declares its kind through presentation(); supportsRedirect() no longer exists, so a client fork's Custom\ adapter that does not implement presentation() is a load-time fatal (#732).
Per-Gateway initializePayment Notes
- CardLink (Alpha/Eurobank): POST redirect; CardLink v2 SHA-256 digest over concatenated fields + secret;
CardLinkAdapter.php:63-160 - JCC: calls
Jcc::registerOrder()(amount in integer cents, ISO 4217 numeric currency); returns GET redirect toformUrl;JccAdapter.php:50-76 - IRIS: calls
Iris::registerOrder(); GET redirect tobankSelectionToolUrl;IrisAdapter.php:62-89 - Klarna: requires
klarna_authorization_tokeninpaymentData;Klarna::createOrder()converts the token. Order lines are itemised from the persisted order + basket (Order\Repository+OrderBasket\Repository, injected nullable) mirroring the legacyKlarnaHelper::generateOrderLines()construction — one line per basket row (SKU as name/reference) plus order-level shipping/coupon/points/gift lines, withorder_amount = shop_order.total_vat. A reconciliation guard falls back to a single consolidated line when the itemised lines don't sum exactly to the order total (Klarna rejectsorder_amount != Σ order_lines.total_amount), so itemisation can never break checkout. WhenpaymentDatalacks the front-end token, the adapter recovers it from the webhook-stored callback row via theOrder\KlarnaPaymentrepository (recoverTokenFromCallback(), #307) — the resilient path the legacygetAuthorizationToken()also uses.KlarnaAdapter::initializePayment()/resolveOrderLines()(#304, #307). It sendsmerchant_urlsconfirmationand the serial-freenotificationURL (KlarnaAdapter.php:144-147) and returnsconfirmed: truewhen Klarna answersfraud_status: ACCEPTED, which makesPlaceOrderServiceconfirm the order in the same request (:172-177; see the contract section above, #737). Hardened in this change:klarnaCreateOrderSuccess()(Adv_checkout.php:3784-3814) now builds$co_datawith a plain(array)cast at:3794; the previousjson_decode(json_encode($orderData), true)returnednullon any non-UTF-8 byte, silently blanking the confirmation email for orders Klarna had already marked PAID. - Ethniki iBank: GET redirect to Simplify JS SDK URL with
data-*params;EthnikiAdapter.php:62-90 - NBGPay:
NBGPayHelper::createHPPLink(); phone split viaPhoneHelper; locale injected fromconfig_item('language_abbr');EthnikiNbgPayAdapter.php:52-87 - Ethniki EE:
NBGEEHelper::beginNewSession(); session-based validation; Greek fields uppercased+transliterated;EthnikiEEAdapter.php:91-205 - XPay:
XPay::createHostedPaymentOrder(); notification URL = legacycheckout/xPayHook;XPayAdapter.php:62-88— order descriptor localized viat('checkout.xpay.order_description', [serial, siteName])— matches legacy storefront. - Piraeus: SOAP
Piraeus::issueTicket(); POST redirect with form params; confirmation via the legacycheckout/get_response/piraeuscallback (Adv_checkout::piraeusResponse(),ecommercen/checkout/controllers/Adv_checkout.php:2109). Thesuccessandfaillegs act only on aPENDINGpiraeusorder (isPendingOrderOfPayway(),:2253-2258) and a valid HashKey (piraeusValidateResponse():2174, delegating toPiraeus::validateNotificationResponse()). Thecancelleg (:2111-2122) never cancels: it only renders the cancelled message for aPENDINGpiraeusorder, and the order is cancelled later by the incomplete-orders sweep (SY-03). OnlypiraeusCancelOrder()(:2222), reached from the verifiedfailleg, cancels, and only after winningclaimCanceled()(:2226); a success POST with a failed HashKey renders the failure page throughpiraeusRenderFailure()(:2244, call at:2166-2167) and cancels nothing (#958);PiraeusAdapter.php:41-94 - ApcoPay:
ApcoPay::getPaymentUrl(); languageel→grmapped; statusUrl = legacycheckout/apcopay_status;ApcoPayAdapter.php:72-117. Fixed in this change: removed redundantshop_orderre-read (Adv_checkout.php:2825-2829) that overwrote the customer-joined row, causing contact data (email,mobile,phone) to be transmitted as null to the live gateway. The join now survives to the reads at:2844-2846. - PayByBank:
PayByBank::createOrder(); NO redirect — returns bank payment code; confirmation via the legacypayByBankResponse()callback (Adv_checkout.php:1082) and polling — thePollPayByBankStatusjob (src/Domains/Checkout/Jobs/PollPayByBankStatus.php) routes throughPaymentConfirmationService::confirmPayment()/cancelPayment(); its schedule entry is opt-in (commented out) atapplication/config/jobs.php:48;PayByBankAdapter.php:49-100. Since #724PlaceOrderServicewrites the code toshop_order.pbb_payment_codeas well astran_ticket, keyed onpayway === 'paybybank'(PlaceOrderService.php:773-812), andplace-orderreturns it astransactionIdso a guest can read it without the customer-onlypayment-statusendpoint (PlaceOrderResult.php:37-58). The gatewaypayment_code_lifecomes fromPayByBankExpiration::secondsFrom()(PayByBankClientFactory.php:20; 24 h fallback when thePAY_BY_BANK/EXPIRATIONsetting is missing, empty, non-numeric or non-positive,PayByBankExpiration.php:42,:74-81), andGET /rest/order/orderpublishes the code's deadline aspbbExpiresAt(src/Rest/Order/Controllers/Order.php:90-99,Resource.php:112,:239-242) — see the contract section above - PayPal Express: PayPal Orders v2
createOrderwithuser_action: CONTINUE; GET redirect to approve/payer-action link;PayPalExpressAdapter.php:48-108. Its constructor takes the brand name with no default;PaymentInitializerFactory::payPalBrandName()passesconfig_item('site_name')(PaymentInitializerFactory.php:230-233), and an empty name omitsbrand_nameso PayPal shows the PayPal account's business name - PayPal Advanced (
paypaladvanced, #916): PayPal Orders v2createOrderwithintent: CAPTURE,user_action: PAY_NOWand the client'sreturnUrl/cancelUrlasreturn_url/cancel_url; GET redirect to thepayer-action/approvelink with no params, and the PayPal order id returned astransactionIdand stored intran_ticket;PayPalAdapter.php:42-95. The adapter takes the samesite_namebrand (formerly the literalAdvEshop). Nothing is captured at placement: the buyer approves on PayPal, PayPal sends the browser to the client'sreturnUrlwithtoken(the PayPal order id) andPayerID, and the client callsconfirm-payment, which captures (see the contract section above).PayPalRestApifetches its access token lazily, applies a 15 s request and 3 s connect timeout, and marks a 404 ongetOrderDetails()withnotFound(PayPalRestApi.php:31-32,:134-138)
Order descriptor localization (legacy parity)
XPay, CardLink Alpha, Ethniki, Ethniki EE, VivaWallet, and PayPal Express adapters now render their gateway-facing descriptor via the same t() key the legacy storefront uses, so the descriptor on the customer's statement or bank page is identical and localized across both checkout paths. All keys (checkout.xpay.order_description, checkout.alpha.order_description, checkout.ethniki.order_description, hct_eshop_name, hct_paypal_express_description) already exist in all 8 locale files — no language file changes were needed.
CardLink has acquirer-specific descriptor logic: Alpha uses t('checkout.alpha.order_description', [serial, siteName]) (wired via orderDescriptionKey: 'checkout.alpha.order_description' at PaymentInitializerFactory.php:572 inside registerAlpha()); Eurobank keeps the legacy literal "{siteName} Order {serial}" (matching Adv_checkout::_eurobank() directly — no key is set).
Two behavior changes worth noting for reconciliation:
- VivaWallet
customerTrnschanged from'Order #'.$serialtot('hct_eshop_name').' '.$serial(e.g."Eshop ORD-2026-042");VivaWalletAdapter.php:59. - PayPal Express
purchase_units[0].descriptionchanged from'Order #'.$serialto the statict('hct_paypal_express_description')(e.g."Eshop Order") — the serial is still carried inreference_id;PayPalExpressAdapter.php:58.
Adapters deliberately NOT changed (no localized legacy descriptor to match): PayPalAdapter (paypaladvanced — no localized legacy descriptor to match; the legacy flow sets a page title only, not a PayPal API descriptor field; its purchase_units[0].description stays 'Order #' . serial), StripeAdapter, KlarnaAdapter (per-product line items), EthnikiNbgPayAdapter (no gateway descriptor field).
Universal Success Path
1. order_model->set_status(orderSerial, 'PAID', ignoreStock=true)
2. order_model->set_is_paid(orderSerial)
3. afterOrderSuccessHooks() → ERP sync
4. adv_mailer->order_complete() → confirmation email
5. sendSmsSuccess() → SMS notification
6. informLowStock() → admin alert
7. if (guest): customer_exit()
8. cart->destroy() → clear session cartNot every handler runs steps 1-2 as written. The ApcoPay status listener (apcoPaySuccessFromListener(), Adv_checkout.php:2954-2971), PayPal Advanced success (:392) and XPay (processXPayPaymentResult(), :4278) replace them with one conditional Adv_order_model::claimPaid($serial, $fromStatus, $method) (Adv_order_model.php:1151: UPDATE ... SET status = 'PAID', is_paid = 1, meta_data = ? WHERE order_serial = ? AND status = ?, :1157-1160). Only the caller that wins it runs steps 3-6 plus applyOrderGifts() (Adv_checkout.php:2778); a loser does nothing (#962).
Universal Failure Path
1. set_status(orderSerial, 'CANCELED', stockMode='+') → return stock
2. cancelCoupon() → markCouponUnused()
3. returnPointsToCustomers() → loyalty rollback
4. afterOrderCancelHooks() → ERP sync (cancel)The ApcoPay status listener (apcoPayFailFromListener(), Adv_checkout.php:2934-2952) and piraeusCancelOrder() (:2222) first win Adv_order_model::claimCanceled($serial, 'PENDING', $method) (Adv_order_model.php:1859; a conditional UPDATE ... WHERE order_serial = ? AND status = ?, :1865-1868) and run steps 1-4 only if they won (#958).
Payment Confirmation
All 19 payway registrations confirm via the legacy path — see CF-09 Payment Webhooks for the full breakdown of which gateways have a dedicated asynchronous webhook (JCC, Viva Wallet, Klarna, Skroutz SmartCart, plus XPay's in-controller handlers) versus which confirm solely via the synchronous browser-redirect/POST-back callback, checkout/get_response/{gateway}. Klarna's merchant_urls.notification push is itself a confirmation arm for an order left in fraud review (klarnaPaymentsNotification(), Adv_checkout.php:3885-3889; CF-09 describes it, #737). Either way, REST-placed orders are resolved by shared order_serial, exactly like storefront-placed ones. A REST-only deployment still requires legacy checkout routes to be mounted for confirmation.
A REST-native webhook family (
/rest/webhooks/{stripe,vivawallet,paypal,piraeus,paybybank}) existed briefly (added 4.99.6) and was retired in Advisable-com/ecommercen#721:Webhook::classnever had arest_policies.phpentry, so every request 401'd from the day it shipped, and no gateway was ever configured to call it. See therest_api_versions.phpentry and #721 for the full rationale.
Client redirect on confirmation (#734)
A REST-placed order may supply returnUrl/cancelUrl on POST /rest/checkout/place-order — its own page for the customer to land on once payment succeeds or is cancelled/fails. PlaceOrderService stores them on the order as shop_order.client_return_url / client_cancel_url (#915; PlaceOrderService.php:606-607, migration database/migrations/20261010120000_add_client_return_urls_to_shop_order.php adds two nullable text columns; WriteData::$clientReturnUrl / $clientCancelUrl carry them for the admin order write schema); the storefront's own checkout never writes those columns, so a storefront order has NULL there. Until #915 the value rode on the gateway callback URL as an advReturnUrl query parameter, which made a CardLink confirmUrl longer than the 128 characters the bank accepts; the callbacks are now the bare legacy routes (PaymentCallbackUrlBuilder::confirmationUrl() / failureUrl() take no client URL, PaymentCallbackUrlBuilder.php:68, :136). The account-erasure step blanks both columns (OrderRecordsStep.php:39, #915).
Once the legacy checkout/get_response/{gateway} callback reaches a terminal status, redirectToClientReturnUrl($order, $succeeded) (ecommercen/checkout/controllers/Adv_checkout.php:885) reads the order's column for that leg; if it is set, it issues a 303 redirect (Location: header) to the client's URL instead of rendering this deployment's legacy thank-you/failure view. This is wired at the tail of alphaResponseSuccess()/alphaResponseFail(), eurobankResponseSuccess()/eurobankResponseFail(), and the shared ethnikiResponseSuccess() (serving both ethniki and ethniki_ee) — five call sites (Adv_checkout.php:817, :954, :1009, :1424, :1480). A valid CardLink callback for an order that is no longer PENDING (the bank's optional delayed copy, or a second POST) also redirects when the order has a destination, instead of showing inactive_payment() (:767, :1371). It is not wired for iris or klarna_payments — per Checkout.php:1156's own "KNOWN LIMITATION" note, those two gateways' onward redirect was never wired, so the customer lands on this deployment's confirmation page instead. ethniki's failure leg and ethniki_ee's cancel/fail legs are also deliberately absent, each for its own tracked reason (deliberately-absent arms documented in the redirectToClientReturnUrl() docblock, Adv_checkout.php:839-846).
Return-handler ownership and claims (#958, #962)
- The session remembers the order it placed.
Adv_checkout::run()stores the placed order serial in the session undercheckout_placed_order_serial(Adv_checkout.php:33,:109-111; helpersrememberPlacedOrder(),isPlacedOrder(),forgetPlacedOrder()at:2361-2383).isPlacedOrder()is true only when the stored serial equals the order's serial, compared withhash_equals()(:2370-2378). - Success pages render only for that order. The success pages for
apcopay(apcoPaySuccess():2880-2924),xpay(xPaySuccess():4126-4207),klarna_payments(klarnaPaymentsConfirmation():3839-3877) andpaypaladvanced(paypalAdvancedSuccess():366-431) render the thank-you page only whenisPlacedOrder()is true, and each also checks its own payway. They callforgetPlacedOrder()once they render, so a replay, or a stranger hitting the URL, getsinactive_payment(); Klarna first triesredirectToClientReturnUrl()(:3847-3850). On PayPal Advanced the placed-order check follows theclaimPaid()attempt (:392-403), which only the PayPal capture status can win. These pages callrenderOrderBasket()andreportPurchase()(:2727,:2563); gift stock is applied byapplyOrderGifts()(:2778) in the caller that winsclaimPaid(). - The ApcoPay status listener.
apcopay_status()(:2973-3030) callsapcoPayGateway()->validateResponse($xml)once before the resultswitch(:2997); that call asks ApcoPay for the transaction byORefand throws when it cannot confirm it (src/ApcoPay/Response.php:27-75), which the listener answers with 400 and no write (:3022-3029).OKgoes toapcoPaySuccessFromListener()(:2954-2971);NOTOK,DECLINEDandCANCELgo toapcoPayFailFromListener()(:2934-2952), which cancels only aPENDINGapcopayorder after winningclaimCanceled().
Business Rules
| Rule | Description |
|---|---|
| Order must be PENDING | All success handlers check status before updating |
| Stock not adjusted on success | ignoreStock=true — stock deducted at creation |
| Stock returned on cancel | returnOrderStock() adds qty back |
| Coupon rolled back on cancel | Usage counter decremented |
| Points rolled back on cancel | Both spent and earned reversed |
| Guest logged out on success | customer_exit() clears session |
| Installments validated | minOrderAmount threshold + allowed values per gateway |
Client Extension Points
| Type | Details |
|---|---|
| Legacy hooks | afterOrderSuccessHooks(), afterOrderCancelHooks(), successExtras() |
| Modern adapters | Implement PaymentAdapterInterface for custom gateways |
| DI override | Replace PaymentInitializerFactory for custom adapter registration |
| Gateway credentials | All configured via Registry (per-gateway group) |
| Piraeus cardholder name | Override formatPiraeusCardholderName() to sanitize characters rejected by Paycenter IssueNewTicket calls — REST: src/Piraeus/Piraeus.php:228 (called at :206), legacy: ecommercen/checkout/controllers/Adv_checkout.php:2005 (called at :2067) |
Klarna Legacy AJAX API
These endpoints are served by AdvApiKlarna (ecommercen/api/controllers/AdvApiKlarna.php) and open/update the storefront's Klarna payment session. Both read POST data and return JSON via sendOutput(). Bot requests are rejected.
Base path: /api/klarna/{method} (routed via api/api_klarna)
| Method | Path | Parameters | Auth | Response | Description |
|---|---|---|---|---|---|
| POST | /api/klarna/openPaymentSession | intent, purchase_country, purchase_currency, order_amount, transportationCost, couponDiscount, giftPackagingCost, pointsDiscount | Session | {session_id, client_token, ...} | Create a Klarna payment session with computed order lines from the current cart; stores session_id in shop_order_klarna_payment. The session locale is derived server-side from config_item('language_abbr') via KlarnaHelper::localeForLanguage() (#309) — any client-posted locale is ignored. |
| POST | /api/klarna/updatePaymentSession | session_id, order_amount, transportationCost, couponDiscount, giftPackagingCost, pointsDiscount | Session | {success: bool} | Update an existing Klarna session (e.g., after cart or address changes) with recalculated order lines |
Order lines: Generated by KlarnaHelper::generateOrderLines() from current cart contents, live pricing data, transportation cost, coupon discount, gift packaging cost, and points discount.
Amounts (integer minor units): Klarna requires all monetary values as integer minor units per ISO 4217 (int64). Both the API client and the order-line helper convert via a toMinorUnits() helper — (int) round($amount * 100) (src/PaymentGateways/Klarna/Klarna.php, src/PaymentGateways/Klarna/KlarnaHelper.php). This covers order_amount (open/update session + create order), captured_amount, refunded_amount, and every order-line unit_price / total_amount / total_discount_amount. Before #302 these were unrounded floats (e.g. 19.99 * 100 = 1998.9999999999998), which could violate the int64 schema and the order_amount == Σ order_lines.total_amount reconciliation; the modern KlarnaAdapter and the JS widget already rounded correctly.
EMD attachment (Advisable-com/ecommercen#448): Klarna::openPaymentSession(), updatePaymentSession(), and createOrder() (src/PaymentGateways/Klarna/Klarna.php) each gained a trailing optional ?array $attachment = null param, passed through untouched as Klarna's Extra Merchant Data attachment field when provided (null by default — no behavior change for existing callers). This unblocks travel/ferry segments (e.g. ferry_reservation_details) where Klarna's risk assessment requires it. EMD can carry consumer PII, so for EU orders it should not be injected at openPaymentSession (session creation) — the GDPR-appropriate point is updatePaymentSession once context/consent is known, or ideally the client-side Klarna authorize() call. Neither AdvApiKlarna (this legacy AJAX API) nor the modern KlarnaAdapter populate $attachment yet — the parameter is plumbing only, available for a caller (e.g. a client fork) to use.
Admin Klarna actions
Cancel, capture and refund are admin actions on the orders list, served by Adv_orders_admin::klarnaPayment($action) (#963): POST /orders_admin/klarnaPayment/{cancel|capture|refund} with orderId and the per-session klarnaCsrf token the list renders. They need an admin session with the Advisable, Admin or Orders role. The Klarna order id is read from the order's shop_order_klarna_payments row and the amount is the order's total_vat; the action is refused unless the order is a klarna_payments order with a serial and the row is in the state the list offers the action for.
| Response | When |
|---|---|
200 {} | Klarna accepted; the row's status becomes canceled / captured / refunded, and cancel and refund set the order to CANCELED |
403 | not a POST, or the token is missing or wrong |
404 | unknown action, or no Klarna order for orderId |
409 | the row is not in a state that allows the action |
502 | Klarna refused or could not be reached |
Data Model
Key tables involved in payment processing
| Table | Purpose |
|---|---|
shop_order | Order record — status transitions (PENDING -> PAID or CANCELED), payway identifies gateway |
shop_order_basket | Order line items — stock adjusted on creation, returned on cancellation |
shop_order_klarna_payment | Klarna-specific session data (session_id, order_id, status: authorized/captured/refunded/canceled) |
shop_order_klarna_payments | Extended Klarna Payments tracking (see schema below) |
coupons | Coupon usage counter — incremented on order creation, decremented on cancellation |
shop_customer | Customer record — loyalty points balance updated (deducted pre-payment, returned on cancellation) |
shop_order_transactions | Payment transaction log (gateway reference, amount, status, timestamp) |
pbb_logging | PayByBank transaction log (~14.5K rows in production); tracks PBB payment lifecycle events |
xpay_logging | XPay transaction audit trail — request/response payloads (TEXT JSON), flow discriminator (order vs gift_card) for cross-flow token isolation; the securityToken is embedded in response_data JSON and read back by getStoredSecurityToken() (:315-342) for webhook verification. No dedicated token column. |
For the full
shop_ordercolumn schema, see AD-03 Order Management.
shop_order_klarna_payments — Klarna Payments extended tracking
| Column | Type | Description |
|---|---|---|
id | INT AUTO_INCREMENT | Primary key |
klarna_payments_order_id | VARCHAR | Klarna-assigned order identifier |
fraud_status | VARCHAR | Klarna fraud assessment result |
authorized_payment_method | VARCHAR | Payment method authorized by the customer (e.g., pay_later, slice_it) |
session_id | VARCHAR | Klarna session identifier (links to shop_order_klarna_payment.session_id) |
authorization_token | VARCHAR | Token received after customer authorization, used to place the Klarna order |
shop_order_id | INT | FK to shop_order.id |
status | VARCHAR | Payment status (authorized, captured, refunded, canceled) |
auto_capture | TINYINT | Whether the order was auto-captured on authorization (1 = yes) |
NBG EE (Ethniki Enterprise Edition) — Undocumented Gateway
NBG EE is completely undocumented externally. It uses a session-based checkout flow with version-specific endpoints:
- V62:
CREATE_CHECKOUT_SESSION— initiates a checkout session with the bank - V63:
INITIATE_CHECKOUT— starts the checkout process within an established session
The flow relies on server-side session state rather than token-based authorization. Validation is session-based (no digest or HMAC). This gateway has no public API documentation from NBG — all integration knowledge is derived from implementation code and internal communications.
XPay (Nexi) — securityToken echo, no HMAC
XPay Greece does not use HMAC for webhook authenticity. Instead, the gateway returns a securityToken in the HPP-create response (src/PaymentGateways/NexiXPay/XPay.php:151), persists it in xpay_logging keyed by (order_serial, flow), and echoes it back in every server-to-server xPayHook notification. The token is compared via hash_equals() (XPay.php:304) and fails closed if either side is missing. getStoredSecurityToken() (:315) retrieves the stored token from the response_data JSON field for verification.
The flow column ('order' vs 'gift_card') ensures a gift-card webhook cannot accept a regular order's stored token even when GIFT_CARDS.ORDER_PREFIX is empty and serials happen to collide.
Headless Checkout Endpoints (REST, v4.99.3+)
The modern headless commerce layer provides stateless checkout via REST:
| Method | Path | Auth | Response | Notes |
|---|---|---|---|---|
| POST | /rest/checkout/shipping | Any | Available transporters | Requires countryAlpha2 in body. Threshold-aware since #568 — cost applies the free-shipping threshold, TRANS_FREE_ALL, and the overweight per-kg surcharge against the current cart; also returns overweightCost (display-only) and deliveryCost (COD surcharge, keyed off an optional payWay field) |
| POST | /rest/checkout/coupon/validate | Any | {valid: true/false} | Requires couponCode in body |
| POST | /rest/checkout/totals | Any | Cart totals with gifts and loyalty | Returns 404 "No cart found" without active cart. Since #595, emits giftDiscount, giftsNearMiss, giftPackagingCost, pointsSpend, pointsCash, payableBeforePoints, and a loyalty decision block; computes via GiftMatcher, OrderBasketBuilder, GiftPackagingResolver, and LoyaltyRedemption (src/Rest/Checkout/Controllers/Checkout.php:804, :847 (quoteGifts(), defined :1021, where giftMatcher->match and orderBasketBuilder->applyGiftOutcome run), :933 (loyaltyRedemption->resolve), :942-944 (giftPackagingResolver->resolve), :950-956 (payableBeforePoints), :969-973 (loyalty decision block)). Coupon deducted from gross subtotal BEFORE shipping threshold since #568 |
| POST | /rest/checkout/place-order | Guest email or Customer | Created order | Places the order via PlaceOrderService — the only one of these endpoints that does. Accepts optional returnUrl/cancelUrl body params (Checkout.php:1141, :1175, #734) naming the customer's own post-payment landing pages — see ## Payment Confirmation |
| POST | /rest/checkout/cancel-payment/{orderId} | Customer | {orderId, status, canceled, reason?} | Idempotent cancellation of a PENDING order (src/Rest/Checkout/Controllers/Checkout.php:1965-2044, OA :1950-1964). 404 only for an unknown or not-owned order (:1977-1980); a CANCELED order answers 200 canceled:false already_canceled (:1985-1993), any other non-PENDING order 200 canceled:false invalid_status (:1995-2003); a race loser answers canceled:false with already_canceled or invalid_status (:2029-2043, #880); 502 payment_cancel_failed for a PENDING paybybank order the gateway does not confirm (:2005-2020, #795) — see the contract section above |
| GET | /rest/checkout/payment-status/{orderId} | Customer | Payment status | Post-payment polling |
PlaceOrderService is the order-placement orchestrator used by place-order only — it in turn calls ShippingCalculator (with CartWeightCalculator's cart-weight figure, #568) and CouponValidator, then dispatches to whichever of the 19 registered payment adapters matches the order's payway. shipping, coupon/validate, and totals are lighter-weight quote/preview endpoints: each calls ShippingCalculator and/or CouponValidator directly from Checkout without going through PlaceOrderService, so a client can preview a price before committing to place-order.
Known Issues & Security Gaps
XPay EUR hardcode is legacy-path only:
ecommercen/checkout/controllers/Adv_checkout.php:4012passes'EUR'as the currency regardless of the active storefront currency on the legacy storefront path only. The modernXPayAdaptercorrectly passes$context->currencyCode(XPayAdapter.php:72) and is not affected. Gift card payments on the legacy path correctly use$this->currentCurrency->code. See Advisable-com/ecommercen#249 for follow-up scope.payment-methodslabels are English fallbacks (low severity):PAYMENT_METHOD_LABELS(Checkout.php:77-97) holds one English string per payway (#732); the endpoint does not localise them, so a client must mapkeyto its own translated name. This closes the earlier gap where 10 of 19 payways returned the raw key.No dedicated REST webhook for any gateway: the REST webhook family (
/rest/webhooks/{stripe,vivawallet,paypal,piraeus,paybybank}) was retired in Advisable-com/ecommercen#721 — it had never been reachable (401 to every caller since the routes were declared in 4.99.6, continuing unconditionally once 4.104.0 extracted them into their own route file;Webhook::classnever had arest_policies.phpentry) and no gateway was ever configured to call it. Every payway confirms via legacy: jcc, klarna, xpay, and Viva Wallet/vivawallet have a dedicated asynchronous webhook; iris, ethniki×3, alpha, eurobank, apcopay, stripe, paypaladvanced/paypal, and piraeus confirm solely via the synchronouscheckout/get_response/{gateway}callback. Either way, REST-placed orders are resolved by sharedorder_serial. A REST-only deployment still requires legacy checkout routes to be mounted for confirmation.Unguarded post-commit order re-reads in gateway adapters (read/write-split deployments only): three legacy gateway methods re-read the just-created order post-commit and dereference it without staleness checks:
jcc()(Adv_checkout.php:3457): re-read at:3459, dereferenced unguarded at:3464—(int)($orderObj->total_vat * 100)— transmitting an amount of0to JCC if the read lags behind the write.iris()(:3591): re-read at:3593; same pattern,'instructedAmount' => (int)($orderObj->total_vat * 100)at:3598, plus$orderObj->idat:3601.klarnaPayments()(:3705): the re-read at:3714flows to two distinct non-nullableobjectparameters across three call sites:klarnaCreateOrderFail(object $orderData)(signature:3768, called at:3719and:3753) andklarnaCreateOrderSuccess(object $orderData, array …)(signature:3784, called at:3764). A stale read is therefore a fatalTypeError, not a degraded render; also dereferenced unguarded at:3733.- Contrast:
xpay()(:3957) issues the same re-read at:3963but is guarded (:3965-3970: log error, setorder_error, redirect topreview_order), so it degrades gracefully rather than fataling.
Exploitability: Reachable only on a read/write-split deployment. Reported closed in production at the infrastructure layer per
docs/changelog/Changelog.4.119.md:17— MaxScalecausal_reads: "local"(+causal_reads_timeout: "3s") enforces read-after-write consistency. Rollout: wecare 2026-07-23; realm-1 and seajets 2026-07-24. The defence-in-depth form of these checks is preserved on thespike/508-carry-forward-defence-in-depthbranch.Stale comment refers to the retired REST webhook (low severity):
PollPayByBankStatus::reconcile()carries the comment// We may have missed the webhook — capture here.(src/Domains/Checkout/Jobs/PollPayByBankStatus.php:120, thePAID/COMPLETEDarm at:118-124), but the REST webhook family was retired in Advisable-com/ecommercen#721 (see item 3), so there is no REST webhook to have missed. Comment-only; behavior is unaffected.StaleRESOLVED (Advisable-com/ecommercen#737) — the docblock was rewritten (KlarnaAdapterdocblock claimsconfirmPaymentreduces stock (low severity)src/Domains/Checkout/Payment/Adapters/KlarnaAdapter.php:37-53) and now says confirmation flipsPENDINGtoPAID, dispatchesOrderPaidand "does NOT touch stock — that was reserved at placement, #282", matchingPaymentConfirmationService.php:94-99. Seedocs/decisions/737-klarna-rest-confirmation.md.The 180-minute sweep can cancel a Klarna order still in fraud review (open, #1043): Klarna's pending fraud review exists only for US/UK merchants. If the review outlasts the sweep (
AdvCancelIncompleteOrders.php:91-99), the sweep cancels the order; a laterACCEPTEDnotification finds itCANCELED,confirmPayment()returnsRejected, andKlarnaNotificationHandleronly logs at error level and answers 200 (KlarnaNotificationHandler.php:108-117).A Klarna confirmation that throws leaves the order
PENDING(open, #1043): ifconfirmPayment()throws insidePlaceOrderServiceafter Klarna charged the customer, the exception is caught and logged withlog_message('error', ...)(PlaceOrderService.php:874-885); the order staysPENDING, no webhook follows for an order Klarna accepted synchronously, and the sweep eventually cancels it.REST
verifyWithGateway()has no Klarna arm (open, #1044): onlystripe,vivawalletandpaypaladvancedare handled (Checkout.php:2054-2089), soPOST /rest/checkout/confirm-payment/{orderId}cannot settle aklarna_paymentsorder.Legacy
Adv_checkout::stripe()does not guard the SDK check (low severity): theStripeCheckoutconstructor call (Adv_checkout.php:3305-3316) sits outside thetry(:3318-3333), which catches onlyApiErrorException, whileStripeApiVersion::current()throwsRuntimeExceptionon an SDK older than22.1.0. A fork with a stale composer pin gets an uncaught exception at the legacy Stripe checkout, arguably the intended "fail loudly" of the #739 decision, but asymmetric with the guardedstripeResponse()(:3353-3362) and REST path (Checkout.php:2075-2086).
For additional XPay webhook and security gaps, see CF-09 Payment Webhooks and IN-23 Nexi XPay Greece.
Tests
| Test File | Coverage |
|---|---|
tests/Unit/Checkout/PaymentInitializerTest.php | Payment adapter registration and gating |
tests/Unit/Checkout/Payment/** | Individual adapter initialization tests, including each adapter's presentation() (#732), PayPalAdapterTest (#916 brand_name) and PaymentCallbackUrlBuilderTest (bare callbacks, #915) |
tests/Unit/PaymentGateways/PayPal/PayPalOrderSettlementTest.php, PayPalRestApiTest.php | PayPal settlement (approved-amount check before capture, sum of completed captures, re-read after capture) and the REST client (lazy token, timeouts, notFound) (#916) |
tests/Unit/Rest/Checkout/Controllers/CheckoutPayPalConfirmationTest.php, CheckoutEndpointSmokeTest.php | confirm-payment for paypaladvanced and the payment-methods kind/redirectMethod/label contract (#916, #732) |
tests/Legacy/Checkout/AdvCheckoutClientReturnRedirectTest.php, tests/Integration/Domains/Checkout/OrderClientDestinationColumnsTest.php | The stored-destination redirect arms and the two shop_order columns (#915) |
tests/Legacy/Checkout/AdvCheckoutTest.php | Legacy gateway dispatch and success/failure paths |
tests/Legacy/Eshop/AdvPaymentsRegistryTest.php | Payment method registry and adapter list |
tests/Legacy/Webhooks/AdvKlarnaPaymentsTest.php | Klarna authorization callback handling only (the notification arm is covered in CF-09) |
tests/Unit/Checkout/Payment/Adapters/KlarnaAdapterTest.php, tests/Unit/Checkout/PlaceOrderServiceTest.php, tests/Integration/Domains/Checkout/PlaceOrderServiceContainerTest.php, tests/Integration/Domains/Checkout/KlarnaRestConfirmationFlowTest.php | Klarna confirmed result, the PlaceOrderService synchronous confirmation (PAID / Rejected / thrown), the explicit container wiring, and the end-to-end flow, which needs the test DB (#737) |
tests/Unit/Jobs/AdvCancelIncompleteOrdersTest.php (#737 cases) | The sweep never reverses a non-PENDING order |
tests/Unit/Stripe/StripeAdapterRequestTest.php, StripeApiVersionTest.php, StripeCheckoutClientTest.php, StripeCheckoutConstructorTest.php, StripeResourceWrappersTest.php, tests/Support/Fakes/FakeStripeHttpClient.php | Stripe request shape, the pinned API version and SDK floor, and the v22 client wrappers (#739) |
tests/Unit/Rest/Checkout/Controllers/CheckoutStripeVerificationTest.php, tests/Legacy/Checkout/AdvCheckoutStripeResponseTest.php | REST verifyStripePayment() (no_payment_required) and the legacy stripeResponse() cases, including the SDK-guard catch (#739) |
tests/Unit/Domains/Checkout/PaymentConfirmationServiceTest.php | confirmPayment() / cancelPayment() PaymentTransition results: winner writes once and dispatches once, race loser runs no side effects, PENDING_ACCEPTED is settled, rejected and missing orders, stock-failure and failed-transaction paths (#880); and cancelByCustomer() (the PayByBank gateway step, the PaymentCancelFailedException path, the re-read after a refusal; #795) |
tests/Unit/Domains/Checkout/Payment/PayByBankGatewayCancellerTest.php | PayByBankGatewayCanceller::cancel() outcomes (Cancelled, Refused, Unreachable), the paid-status probe and the pbb_logging cancel row (#795) |
tests/Unit/Rest/Checkout/Controllers/CustomerCancelPaymentFailureTest.php | 502 payment_cancel_failed on both customer cancel endpoints, cancelling through cancelByCustomer() (#795) |
tests/Legacy/Checkout/AdvCheckoutSuccessPageOwnershipTest.php | Success pages act only on the order the session placed (#962) |
tests/Legacy/Checkout/AdvCheckoutApcoPayPiraeusCancelTest.php | ApcoPay and Piraeus return handlers cancel only after a verified request and a won claimCanceled() (#958) |
tests/Integration/Legacy/Eshop/AdvOrderModelClaimPaidTest.php, AdvOrderModelClaimCanceledTest.php | claimPaid() / claimCanceled() conditional writes (#962, #958) |
tests/Integration/Domains/Checkout/PaymentTransitionConcurrencyTest.php | Two simultaneous confirmations or cancellations on separate DB connections: exactly one wins and dispatches; a failed stock release rolls the cancel back (#880) |
tests/Unit/Rest/Checkout/Controllers/CheckoutVivaConfirmationGatesTest.php | Viva confirm-payment verification gates (StatusId F, charge-type allow-list, amount in minor units, order code, fail-closed credentials) and the already_paid / invalid_status race answers (#865, #880) |
tests/Unit/VivaWallet/OrderTransactionsTest.php | Viva order-code transaction lookup: URL, Basic auth, response decoding and failure answers (#865) |
tests/Unit/Domains/Checkout/Payment/PayByBankExpirationTest.php | PayByBankExpiration: 24 h fallback, expiresAt(), paymentCodeExpiresAt() (#870) |
tests/Unit/Rest/Order/Controllers/OrderPbbExpiresAtTest.php | pbbExpiresAt on the order read endpoints (#870) |
Related Flows
- CF-05 Cart Management — cart cleared on success
- CF-06 Order Preview — generates checkout data
- CF-07 Order Confirmation — order creation before payment
- CF-09 Payment Webhooks — async callbacks, including the Klarna notification arm
- Decision 737 Klarna REST confirmation and Decision 739 stripe-php v22 — why Klarna confirms synchronously and via notification, and why Stripe pins the SDK's API version
- CF-13 Coupons — coupon rolled back on failure
- CF-23 Gift Cards — gift card payment via Viva Wallet
- CF-32 Loyalty Points — points rolled back on failure
- SY-02 Order Status Emails — confirmation email on success
- AD-03 Order Management — admin order status
- IN-08 ERP Integrations — ERP sync after payment success
Wiki Guides: Stripe integration setup and keys — see Stripe Guide. Gateway calls are protected by circuit breakers — see Circuit Breaker Guide. Post-payment hooks run as deferred tasks — see Deferred Task Guide.
Shared Patterns
- SY-24 Email Dispatch — order confirmation and cancellation emails dispatched after payment resolution
- SY-26 Circuit Breaker — protects external payment gateway API calls from cascading failures
- SY-27 Deferred Tasks — ERP sync (
afterOrderSuccessHooks) and SMS notifications run as deferred tasks