Skip to content

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_payments order Klarna accepts at create-order is now confirmed inside place-order (PaymentInitResult::confirmed, PlaceOrderService calls confirmPayment(), response status PAID, #737, decision record) and the KlarnaAdapter docblock no longer claims confirmation reduces stock (Known Issue 6 resolved); Stripe now pins the API version through StripeApiVersion on stripe-php ^22.1 (#739, decision record), accepts no_payment_required as settled and logs a failed gateway check; #1043 and #1044 limits and a legacy stripe() 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 through PaymentConfirmationService::cancelByCustomer() and can answer 502 payment_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.php and Adv_checkout.php citations re-anchored; previous: 2026-10-13 — 4.127.0 resync: payment-methods now publishes kind/redirectMethod and a label for every payway (#732, PaymentAdapterInterface::presentation() replaces supportsRedirect()), PayPal Advanced for headless clients (#916: confirm-payment captures and settles on the sum of captures, brand_name from site_name), client return/cancel URLs stored on the order instead of the callback URL (#915), Checkout.php citations re-anchored; previous: 2026-10-02 — 4.125.0 resync: canonical REST confirm/cancel payment contract (#880 PaymentTransition, race answers, confirmed vs status), Viva charge-type allow-list and registration gate (#865), PayByBank expiry and pbbExpiresAt (#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 ​

MethodPathAuthDescription
POST/rest/checkout/place-orderGuest/CustomerCreate 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-methodsGuestDiscover the payment methods the merchant selected for external frontends; returns {"paymentMethods":[{key, label, kind, redirectMethod, requiresRedirect}]} (#732)
GET/rest/checkout/payment-status/{orderId}CustomerCheck payment result after redirect
POST/rest/checkout/confirm-payment/{orderId}CustomerVerify 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.

kindMeaning for the clientPayways
offlinenothing to pay online; the order is complete at placement (PENDING_ACCEPTED)delivery, bank_transfer, paid_at_store
bank_codeUNPAID at placement; the customer pays later with the bank code returned with the orderpaybybank
redirectnavigate (redirectMethod GET) or auto-submit a form (POST) to paymentRedirect.urlGET: stripe, vivawallet, paypaladvanced, paypal, xpay, jcc, iris, ethniki_nbgpay; POST: alpha, eurobank, piraeus
embeddedkeep the customer on the page: an iframe of paymentRedirect.url, or the gateway's JavaScript SDK with paramsapcopay, ethniki, ethniki_ee
widgetan 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.

  • PaymentTransition results. PaymentConfirmationService::confirmPayment() and cancelPayment() return the enum PaymentTransition (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 except Rejected. The class docblock is at PaymentConfirmationService.php:15-24.
  • Confirm is a conditional write. confirmPayment() calls transitionStatus($orderId, 'PENDING', 'PAID', $updateData) (PaymentConfirmationService.php:84). Only Applied reloads the order and dispatches OrderPaid (:107-120); PENDING_ACCEPTED counts as AlreadyApplied (:87-91).
  • Cancel is atomic with the stock release. cancelPayment() wraps transitionStatus($orderId, 'PENDING', 'CANCELED', ...) (:173) and restoreStockForOrder (:177) in transactional(...) (:172-180). A failed release rolls the cancel back, leaves the order PENDING and throws RuntimeException (:182-184). A race loser returns AlreadyApplied (already CANCELED) or Rejected and does nothing (:186-192); only the winner dispatches OrderCanceled (:201) and returns Applied (:210). OrderCanceled fires 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 by product_code_id (src/Domains/Checkout/StockService.php:96), so concurrent adjustments queue on the product_codes row locks instead of deadlocking.
  • Confirm race answers. The loser of a confirm race answers confirmed:false with reason already_paid (AlreadyApplied) or invalid_status (Rejected) (Checkout.php:1768-1794); before #880 it answered confirmed:true. The up-front non-PENDING arm (:1741-1753) has the same shape, but answers already_paid only for PAID and invalid_status for every other status including PENDING_ACCEPTED (:1750), whereas the race arm maps AlreadyApplied (which includes PENDING_ACCEPTED, PaymentConfirmationService.php:87-91) to already_paid (Checkout.php:1791). A Rejected race is logged at error level (the order was paid at the gateway but is no longer PENDING, so it was not marked PAID and needs a refund or a manual decision, :1776-1785).
  • confirmed is not the verdict, status is. confirmed means "this call verified the payment with the gateway"; status is the payment verdict. An order can come back status: PAID with confirmed: false (OA text Checkout.php:1675-1679). Settled is PAID or PENDING_ACCEPTED; PENDING is 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). A CANCELED order answers 200 canceled:false with reason already_canceled (:1985-1993); any other non-PENDING order answers 200 canceled:false with reason invalid_status (:1995-2003). The loser of a cancel race answers canceled:false with already_canceled or invalid_status (:2029-2043).
  • Customer order cancel. Order::cancel treats only Applied as 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 is CANCELED.
  • Customer cancel of a Pay by Bank order (#795). POST /rest/checkout/cancel-payment/{orderId} and POST /rest/order/order/{id}/cancel go through PaymentConfirmationService::cancelByCustomer() (src/Domains/Checkout/PaymentConfirmationService.php:134). For a PENDING paybybank order it cancels at PayByBank first. If the gateway does not confirm and the order is still PENDING, it throws PaymentCancelFailedException: the order stays PENDING with its stock reserved, and both endpoints answer 502 with error.code payment_cancel_failed. cancelPayment() stays gateway-agnostic, because the PayByBank poll calls it for orders the gateway already cancelled. The 502 is built in Checkout.php:2010-2019 and Order.php:323-333. PayByBankGatewayCanceller::cancel() (src/Domains/Checkout/Payment/PayByBankGatewayCanceller.php:25-52) returns a PayByBankCancelOutcome (Cancelled, Refused or Unreachable): a missing API key or URL is Unreachable (:27-31); a 200 is downgraded to Refused when the gateway reports the order PAID or COMPLETED (:36-43); a refusal is re-checked against the gateway status and becomes Cancelled if it reads CANCELLED or CANCELLED_BY_MERCHANT (:49-51). The pbb_logging row (called_for = 'cancel') is written best-effort by PayByBankLog::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, through cancelByCustomer()), Order.php:319 (the same), PollPayByBankStatus.php:107, :121, :128, and, for confirmPayment() only, PlaceOrderService.php:857 (a gateway-confirmed order, #737, next bullet) and KlarnaNotificationHandler.php:103 (the Klarna notification arm, see CF-09).
  • Klarna synchronous confirmation (#737). KlarnaAdapter::initializePayment() returns PaymentInitResult(status: 'PENDING', ..., confirmed: ($response['fraud_status'] ?? null) === 'ACCEPTED') (KlarnaAdapter.php:172-177); PaymentInitResult gained public readonly bool $confirmed = false (src/Domains/Checkout/Payment/PaymentInitResult.php). When confirmed is true and the optional paymentConfirmationService is wired, PlaceOrderService, after reserving stock (reduceStockForOrder() :823, #282), calls confirmPayment($orderId, array_filter(['transactionId' => ...])) (PlaceOrderService.php:844-860). The response status becomes PAID unless the transition is Rejected (AlreadyApplied also answers PAID, :862-863); a Rejected keeps PENDING and logs Payment 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 order PENDING, never a 500 (:874-885). The service is an optional trailing constructor argument (:139) wired explicitly in src/Domains/Checkout/container.php:49-55 (its comment notes an autowire miss would pass null). The place-order status may therefore be PAID (Checkout.php:1253-1256; application/config/rest_api_versions.php:154, REST API 1.126). Confirmation never stamps is_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.php returns \Stripe\Util\ApiVersion::CURRENT from current() after assertSupported(Stripe::VERSION), which throws RuntimeException when the installed SDK is older than MINIMUM_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 at StripeCheckout::newClient() ('stripe_version', src/Stripe/Checkout/StripeCheckout.php:297), in StripeAdapter (StripeAdapter.php:34) and in the REST verifyStripePayment() (Checkout.php:2100); it is not configurable and has no registry key. verifyStripePayment() settles when the session status is complete and payment_status is paid or no_payment_required (Checkout.php:2091-2106), so a zero-total order now settles (rest_api_versions.php:153); the key comes from the test seam stripeSecretKey() (:2108). verifyWithGateway() now logs a failed gateway check with log_message('error', ...) before answering unconfirmed (:2075-2086). The legacy Adv_checkout::stripeResponse() likewise treats no_payment_required like paid (Adv_checkout.php:3380-3381) and catches the SDK-guard RuntimeException: it logs critical ("the order may be paid at Stripe", with the session_id) and answers error_404(), leaving the order PENDING for 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 StatusId F (Checkout.php:2123, tested at :2234), has a charge type on VIVA_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 a paypaladvanced order to verifyPayPalPayment() (Checkout.php:2054-2089 with the PayPal arm at :2072-2073, :2313-2324), which builds a PayPalOrderSettlement and calls settle(tran_ticket, total_vat, order_currency) (:2319-2323). The class (src/PaymentGateways/PayPal/PayPalOrderSettlement.php) reads the PayPal order; when it is APPROVED it checks that the purchase-unit amounts sum to exactly the order total in the order currency and only then calls captureOrder() (the call carries PayPal-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 the COMPLETED captures, 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 answer confirmed:false with the order still PENDING, 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 stayed PENDING.
  • Registration gate and refusal. vivawallet is registered over REST only when hasMerchantCredentials() is true (PaymentInitializerFactory.php:167-169, src/VivaWallet/Config.php:119). place-order refuses a payway with no registered adapter with 422 payway_not_available before any write (src/Domains/Checkout/PlaceOrderService.php:181-183).
  • PayByBank expiry (#870). The gateway payment_code_life comes from PayByBankExpiration::secondsFrom(), called in PayByBankClientFactory::create() (src/Domains/Checkout/Payment/PayByBankClientFactory.php:20), the one place the client is built: PaymentInitializerFactory.php:623, PollPayByBankStatus.php:146 and AdvFactories::payByBank() (ecommercen/core/AdvFactories.php:41-45) all go through it. A missing, empty, non-numeric or non-positive PAY_BY_BANK/EXPIRATION setting falls back to 24 h (DEFAULT_SECONDS = 86400, src/Domains/Checkout/Payment/PayByBankExpiration.php:42; secondsFrom :74-81, the <= 0 test at :76). GET /rest/order/order publishes pbbExpiresAt (src/Rest/Order/Controllers/Order.php:90-99, src/Rest/Order/Resources/Order/Resource.php:112 and :239-242), computed by paymentCodeExpiresAt() (PayByBankExpiration.php:108-127); it is null unless the order is paybybank with a code issued, and also null when entry_datetime is 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 ​

TypePathPurpose
Internalcheckout->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.

AdapterKeykind (#732)Gate
DeliveryAdapterdeliveryofflineAlways
BankTransferAdapterbank_transferofflineAlways
PaidAtStoreAdapterpaid_at_storeofflineAlways
StripeAdapterstriperedirect (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)
VivaWalletAdaptervivawalletredirect (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
PayPalAdapterpaypaladvancedredirect (GET)getPaypalAdvancedSettings() client_id + secret; selectable for external frontends since #916 (getExternalPayWays(), eshop_helper.php:439-445)
PayPalExpressAdapterpaypalredirect (GET)getPaypalSettings() client_id + secret
JccAdapterjccredirect (GET)getJccSettings() username + password
IrisAdapteririsredirect (GET)getIrisSettings() username, password, customerCode, checkDigit
KlarnaAdapterklarna_paymentswidgetgetKlarnaSettings() username + password
EthnikiAdapterethnikiembeddedgetEthnikiBankSettings() publicKey + privateKey
EthnikiNbgPayAdapterethniki_nbgpayredirect (GET)getEthnikiNBGPaySettings() appID + appKey
EthnikiEEAdapterethniki_eeembeddedgetEthnikiEEBankSettings() merchantId, directApiKey, host, apiVersion
XPayAdapterxpayredirect (GET)getXPaySettings() API_KEY
PiraeusAdapterpiraeusredirect (POST)getPiraeusBankSettings() → PiraeusConfig::isConfigured()
CardLinkAdapter (Alpha)alpharedirect (POST)getAlphaBankSettings() ID, SSK, Submit
CardLinkAdapter (Eurobank)eurobankredirect (POST)getEurobankSettings() merchantId, secret, url
ApcoPayAdapterapcopayembeddedgetApcoPaySettings() profileId, secret, merchantId, merchantPassword
PayByBankAdapterpaybybankbank_codegetPayByBankSettings() 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 to formUrl; JccAdapter.php:50-76
  • IRIS: calls Iris::registerOrder(); GET redirect to bankSelectionToolUrl; IrisAdapter.php:62-89
  • Klarna: requires klarna_authorization_token in paymentData; Klarna::createOrder() converts the token. Order lines are itemised from the persisted order + basket (Order\Repository + OrderBasket\Repository, injected nullable) mirroring the legacy KlarnaHelper::generateOrderLines() construction — one line per basket row (SKU as name/reference) plus order-level shipping/coupon/points/gift lines, with order_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 rejects order_amount != Σ order_lines.total_amount), so itemisation can never break checkout. When paymentData lacks the front-end token, the adapter recovers it from the webhook-stored callback row via the Order\KlarnaPayment repository (recoverTokenFromCallback(), #307) — the resilient path the legacy getAuthorizationToken() also uses. KlarnaAdapter::initializePayment() / resolveOrderLines() (#304, #307). It sends merchant_urls confirmation and the serial-free notification URL (KlarnaAdapter.php:144-147) and returns confirmed: true when Klarna answers fraud_status: ACCEPTED, which makes PlaceOrderService confirm 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_data with a plain (array) cast at :3794; the previous json_decode(json_encode($orderData), true) returned null on 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 via PhoneHelper; locale injected from config_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 = legacy checkout/xPayHook; XPayAdapter.php:62-88 — order descriptor localized via t('checkout.xpay.order_description', [serial, siteName]) — matches legacy storefront.
  • Piraeus: SOAP Piraeus::issueTicket(); POST redirect with form params; confirmation via the legacy checkout/get_response/piraeus callback (Adv_checkout::piraeusResponse(), ecommercen/checkout/controllers/Adv_checkout.php:2109). The success and fail legs act only on a PENDING piraeus order (isPendingOrderOfPayway(), :2253-2258) and a valid HashKey (piraeusValidateResponse() :2174, delegating to Piraeus::validateNotificationResponse()). The cancel leg (:2111-2122) never cancels: it only renders the cancelled message for a PENDING piraeus order, and the order is cancelled later by the incomplete-orders sweep (SY-03). Only piraeusCancelOrder() (:2222), reached from the verified fail leg, cancels, and only after winning claimCanceled() (:2226); a success POST with a failed HashKey renders the failure page through piraeusRenderFailure() (:2244, call at :2166-2167) and cancels nothing (#958); PiraeusAdapter.php:41-94
  • ApcoPay: ApcoPay::getPaymentUrl(); language el→gr mapped; statusUrl = legacy checkout/apcopay_status; ApcoPayAdapter.php:72-117. Fixed in this change: removed redundant shop_order re-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 legacy payByBankResponse() callback (Adv_checkout.php:1082) and polling — the PollPayByBankStatus job (src/Domains/Checkout/Jobs/PollPayByBankStatus.php) routes through PaymentConfirmationService::confirmPayment() / cancelPayment(); its schedule entry is opt-in (commented out) at application/config/jobs.php:48; PayByBankAdapter.php:49-100. Since #724 PlaceOrderService writes the code to shop_order.pbb_payment_code as well as tran_ticket, keyed on payway === 'paybybank' (PlaceOrderService.php:773-812), and place-order returns it as transactionId so a guest can read it without the customer-only payment-status endpoint (PlaceOrderResult.php:37-58). The gateway payment_code_life comes from PayByBankExpiration::secondsFrom() (PayByBankClientFactory.php:20; 24 h fallback when the PAY_BY_BANK/EXPIRATION setting is missing, empty, non-numeric or non-positive, PayByBankExpiration.php:42, :74-81), and GET /rest/order/order publishes the code's deadline as pbbExpiresAt (src/Rest/Order/Controllers/Order.php:90-99, Resource.php:112, :239-242) — see the contract section above
  • PayPal Express: PayPal Orders v2 createOrder with user_action: CONTINUE; GET redirect to approve/payer-action link; PayPalExpressAdapter.php:48-108. Its constructor takes the brand name with no default; PaymentInitializerFactory::payPalBrandName() passes config_item('site_name') (PaymentInitializerFactory.php:230-233), and an empty name omits brand_name so PayPal shows the PayPal account's business name
  • PayPal Advanced (paypaladvanced, #916): PayPal Orders v2 createOrder with intent: CAPTURE, user_action: PAY_NOW and the client's returnUrl/cancelUrl as return_url/cancel_url; GET redirect to the payer-action/approve link with no params, and the PayPal order id returned as transactionId and stored in tran_ticket; PayPalAdapter.php:42-95. The adapter takes the same site_name brand (formerly the literal AdvEshop). Nothing is captured at placement: the buyer approves on PayPal, PayPal sends the browser to the client's returnUrl with token (the PayPal order id) and PayerID, and the client calls confirm-payment, which captures (see the contract section above). PayPalRestApi fetches its access token lazily, applies a 15 s request and 3 s connect timeout, and marks a 404 on getOrderDetails() with notFound (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 customerTrns changed from 'Order #'.$serial to t('hct_eshop_name').' '.$serial (e.g. "Eshop ORD-2026-042"); VivaWalletAdapter.php:59.
  • PayPal Express purchase_units[0].description changed from 'Order #'.$serial to the static t('hct_paypal_express_description') (e.g. "Eshop Order") — the serial is still carried in reference_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 cart

Not 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::class never had a rest_policies.php entry, so every request 401'd from the day it shipped, and no gateway was ever configured to call it. See the rest_api_versions.php entry 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 under checkout_placed_order_serial (Adv_checkout.php:33, :109-111; helpers rememberPlacedOrder(), isPlacedOrder(), forgetPlacedOrder() at :2361-2383). isPlacedOrder() is true only when the stored serial equals the order's serial, compared with hash_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) and paypaladvanced (paypalAdvancedSuccess() :366-431) render the thank-you page only when isPlacedOrder() is true, and each also checks its own payway. They call forgetPlacedOrder() once they render, so a replay, or a stranger hitting the URL, gets inactive_payment(); Klarna first tries redirectToClientReturnUrl() (:3847-3850). On PayPal Advanced the placed-order check follows the claimPaid() attempt (:392-403), which only the PayPal capture status can win. These pages call renderOrderBasket() and reportPurchase() (:2727, :2563); gift stock is applied by applyOrderGifts() (:2778) in the caller that wins claimPaid().
  • The ApcoPay status listener. apcopay_status() (:2973-3030) calls apcoPayGateway()->validateResponse($xml) once before the result switch (:2997); that call asks ApcoPay for the transaction by ORef and throws when it cannot confirm it (src/ApcoPay/Response.php:27-75), which the listener answers with 400 and no write (:3022-3029). OK goes to apcoPaySuccessFromListener() (:2954-2971); NOTOK, DECLINED and CANCEL go to apcoPayFailFromListener() (:2934-2952), which cancels only a PENDING apcopay order after winning claimCanceled().

Business Rules ​

RuleDescription
Order must be PENDINGAll success handlers check status before updating
Stock not adjusted on successignoreStock=true — stock deducted at creation
Stock returned on cancelreturnOrderStock() adds qty back
Coupon rolled back on cancelUsage counter decremented
Points rolled back on cancelBoth spent and earned reversed
Guest logged out on successcustomer_exit() clears session
Installments validatedminOrderAmount threshold + allowed values per gateway

Client Extension Points ​

TypeDetails
Legacy hooksafterOrderSuccessHooks(), afterOrderCancelHooks(), successExtras()
Modern adaptersImplement PaymentAdapterInterface for custom gateways
DI overrideReplace PaymentInitializerFactory for custom adapter registration
Gateway credentialsAll configured via Registry (per-gateway group)
Piraeus cardholder nameOverride 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)

MethodPathParametersAuthResponseDescription
POST/api/klarna/openPaymentSessionintent, purchase_country, purchase_currency, order_amount, transportationCost, couponDiscount, giftPackagingCost, pointsDiscountSession{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/updatePaymentSessionsession_id, order_amount, transportationCost, couponDiscount, giftPackagingCost, pointsDiscountSession{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.

ResponseWhen
200 {}Klarna accepted; the row's status becomes canceled / captured / refunded, and cancel and refund set the order to CANCELED
403not a POST, or the token is missing or wrong
404unknown action, or no Klarna order for orderId
409the row is not in a state that allows the action
502Klarna refused or could not be reached

Data Model ​

Key tables involved in payment processing ​

TablePurpose
shop_orderOrder record — status transitions (PENDING -> PAID or CANCELED), payway identifies gateway
shop_order_basketOrder line items — stock adjusted on creation, returned on cancellation
shop_order_klarna_paymentKlarna-specific session data (session_id, order_id, status: authorized/captured/refunded/canceled)
shop_order_klarna_paymentsExtended Klarna Payments tracking (see schema below)
couponsCoupon usage counter — incremented on order creation, decremented on cancellation
shop_customerCustomer record — loyalty points balance updated (deducted pre-payment, returned on cancellation)
shop_order_transactionsPayment transaction log (gateway reference, amount, status, timestamp)
pbb_loggingPayByBank transaction log (~14.5K rows in production); tracks PBB payment lifecycle events
xpay_loggingXPay 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_order column schema, see AD-03 Order Management.

shop_order_klarna_payments — Klarna Payments extended tracking ​

ColumnTypeDescription
idINT AUTO_INCREMENTPrimary key
klarna_payments_order_idVARCHARKlarna-assigned order identifier
fraud_statusVARCHARKlarna fraud assessment result
authorized_payment_methodVARCHARPayment method authorized by the customer (e.g., pay_later, slice_it)
session_idVARCHARKlarna session identifier (links to shop_order_klarna_payment.session_id)
authorization_tokenVARCHARToken received after customer authorization, used to place the Klarna order
shop_order_idINTFK to shop_order.id
statusVARCHARPayment status (authorized, captured, refunded, canceled)
auto_captureTINYINTWhether 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:

MethodPathAuthResponseNotes
POST/rest/checkout/shippingAnyAvailable transportersRequires 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/validateAny{valid: true/false}Requires couponCode in body
POST/rest/checkout/totalsAnyCart totals with gifts and loyaltyReturns 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-orderGuest email or CustomerCreated orderPlaces 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}CustomerPayment statusPost-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 ​

  1. XPay EUR hardcode is legacy-path only: ecommercen/checkout/controllers/Adv_checkout.php:4012 passes 'EUR' as the currency regardless of the active storefront currency on the legacy storefront path only. The modern XPayAdapter correctly 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.

  2. payment-methods labels 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 map key to its own translated name. This closes the earlier gap where 10 of 19 payways returned the raw key.

  3. 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::class never had a rest_policies.php entry) 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 synchronous checkout/get_response/{gateway} callback. Either way, REST-placed orders are resolved by shared order_serial. A REST-only deployment still requires legacy checkout routes to be mounted for confirmation.

  4. 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 of 0 to 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->id at :3601.
    • klarnaPayments() (:3705): the re-read at :3714 flows to two distinct non-nullable object parameters across three call sites: klarnaCreateOrderFail(object $orderData) (signature :3768, called at :3719 and :3753) and klarnaCreateOrderSuccess(object $orderData, array …) (signature :3784, called at :3764). A stale read is therefore a fatal TypeError, not a degraded render; also dereferenced unguarded at :3733.
    • Contrast: xpay() (:3957) issues the same re-read at :3963 but is guarded (:3965-3970: log error, set order_error, redirect to preview_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 — MaxScale causal_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 the spike/508-carry-forward-defence-in-depth branch.

  5. 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, the PAID/COMPLETED arm 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.

  6. Stale KlarnaAdapter docblock claims confirmPayment reduces stock (low severity) RESOLVED (Advisable-com/ecommercen#737) — the docblock was rewritten (src/Domains/Checkout/Payment/Adapters/KlarnaAdapter.php:37-53) and now says confirmation flips PENDING to PAID, dispatches OrderPaid and "does NOT touch stock — that was reserved at placement, #282", matching PaymentConfirmationService.php:94-99. See docs/decisions/737-klarna-rest-confirmation.md.

  7. 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 later ACCEPTED notification finds it CANCELED, confirmPayment() returns Rejected, and KlarnaNotificationHandler only logs at error level and answers 200 (KlarnaNotificationHandler.php:108-117).

  8. A Klarna confirmation that throws leaves the order PENDING (open, #1043): if confirmPayment() throws inside PlaceOrderService after Klarna charged the customer, the exception is caught and logged with log_message('error', ...) (PlaceOrderService.php:874-885); the order stays PENDING, no webhook follows for an order Klarna accepted synchronously, and the sweep eventually cancels it.

  9. REST verifyWithGateway() has no Klarna arm (open, #1044): only stripe, vivawallet and paypaladvanced are handled (Checkout.php:2054-2089), so POST /rest/checkout/confirm-payment/{orderId} cannot settle a klarna_payments order.

  10. Legacy Adv_checkout::stripe() does not guard the SDK check (low severity): the StripeCheckout constructor call (Adv_checkout.php:3305-3316) sits outside the try (:3318-3333), which catches only ApiErrorException, while StripeApiVersion::current() throws RuntimeException on an SDK older than 22.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 guarded stripeResponse() (: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 FileCoverage
tests/Unit/Checkout/PaymentInitializerTest.phpPayment 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.phpPayPal 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.phpconfirm-payment for paypaladvanced and the payment-methods kind/redirectMethod/label contract (#916, #732)
tests/Legacy/Checkout/AdvCheckoutClientReturnRedirectTest.php, tests/Integration/Domains/Checkout/OrderClientDestinationColumnsTest.phpThe stored-destination redirect arms and the two shop_order columns (#915)
tests/Legacy/Checkout/AdvCheckoutTest.phpLegacy gateway dispatch and success/failure paths
tests/Legacy/Eshop/AdvPaymentsRegistryTest.phpPayment method registry and adapter list
tests/Legacy/Webhooks/AdvKlarnaPaymentsTest.phpKlarna 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.phpKlarna 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.phpStripe 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.phpREST verifyStripePayment() (no_payment_required) and the legacy stripeResponse() cases, including the SDK-guard catch (#739)
tests/Unit/Domains/Checkout/PaymentConfirmationServiceTest.phpconfirmPayment() / 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.phpPayByBankGatewayCanceller::cancel() outcomes (Cancelled, Refused, Unreachable), the paid-status probe and the pbb_logging cancel row (#795)
tests/Unit/Rest/Checkout/Controllers/CustomerCancelPaymentFailureTest.php502 payment_cancel_failed on both customer cancel endpoints, cancelling through cancelByCustomer() (#795)
tests/Legacy/Checkout/AdvCheckoutSuccessPageOwnershipTest.phpSuccess pages act only on the order the session placed (#962)
tests/Legacy/Checkout/AdvCheckoutApcoPayPiraeusCancelTest.phpApcoPay and Piraeus return handlers cancel only after a verified request and a won claimCanceled() (#958)
tests/Integration/Legacy/Eshop/AdvOrderModelClaimPaidTest.php, AdvOrderModelClaimCanceledTest.phpclaimPaid() / claimCanceled() conditional writes (#962, #958)
tests/Integration/Domains/Checkout/PaymentTransitionConcurrencyTest.phpTwo 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.phpViva 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.phpViva order-code transaction lookup: URL, Basic auth, response decoding and failure answers (#865)
tests/Unit/Domains/Checkout/Payment/PayByBankExpirationTest.phpPayByBankExpiration: 24 h fallback, expiresAt(), paymentCodeExpiresAt() (#870)
tests/Unit/Rest/Order/Controllers/OrderPbbExpiresAtTest.phppbbExpiresAt on the order read endpoints (#870)

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 ​