Appearance
Payment Webhooks & Callbacks
Flow ID: CF-09 | Module(s): webhooks, checkout, eshop, gift_cards | Complexity: High Last Updated: 2026-11-16 — 4.130.0 resync: new section for the Klarna
merchant_urls.notificationconfirmation arm (KlarnaNotificationHandler, re-reads the order from Klarna and confirms throughconfirmPayment(); 503 so Klarna retries, #737, decision record); the Klarna authorization-callback "no status change" rule is now scoped to that callback;PaymentConfirmationServiceconsumers list corrected (PlaceOrderServicesync confirm and the Klarna notification are consumers,KlarnaAdapterstill is not);shop_order.tran_ticketwidened tovarchar(64)and indexed; #1043/#1044 limits added to Known Issues; previous: 2026-11-04 — 4.129.0 resync: the XPay orders webhook now settles through the conditionalclaimPaid()claim, so its mail, SMS, stock alert and gift stock run once andmeta_datais stamped (#962); new section for the ApcoPayapcopay_statuslistener, which validates the notification once and cancels only after winningclaimCanceled()(#958); the XPay gift-card reversal now goes throughrevokeGiftCard()while browser returns can only cancel a Pending order (#957);xPayCancel()added to Known Issues as the open #849 item;PaymentConfirmationService::cancelByCustomer()(#795);Adv_checkout.php,AdvGiftCardPage.phpandXPay.phpcitations re-anchored; previous: 2026-10-13 — 4.127.0 resync:Adv_checkout.php,Checkout.phpandPlaceOrderService.phpcitations re-anchored; previous: 2026-10-02 — 4.125.0 resync:PaymentConfirmationServicetransitions are atomic and returnPaymentTransition(#880), consumer list corrected, #754 citations refreshed; previous: 2026-09-29
Business Context
Payment webhooks are asynchronous, server-to-server notifications sent by external payment providers to confirm (or reject) transactions. They serve as the authoritative payment confirmation for gateways that operate asynchronously, and as a fallback/supplement for gateways that also have a synchronous browser-redirect flow (get_response).
Legacy is the platform's sole payment-webhook layer — four ecommercen/webhooks/ handlers plus XPay in-controller handlers for provider-specific flows:
| Type | Provider | Purpose |
|---|---|---|
| Card payment | JCC | Asynchronous notification after card authorization/deposit |
| BNPL / Deferred | Klarna Payments | Authorization token delivery (payment not yet captured); confirmation notification for an order Klarna created in fraud review (#737) |
| Marketplace | Skroutz SmartCart | Marketplace order creation and state updates |
| Multi-method | Viva Wallet | Transaction payment confirmation or failure, including gift cards |
| Card payment (in-controller) | Nexi XPay Greece | Asynchronous notification after card authorization; co-hosted on Adv_checkout (orders) and AdvGiftCardPage (gift cards) — not in ecommercen/webhooks/ |
Retired REST layer (Advisable-com/ecommercen#721). A parallel REST-routed webhook family —
src/Rest/Webhooks/Controllers/Webhook.php, five routes (POST /rest/webhooks/{stripe,vivawallet,paypal,piraeus,paybybank}) — was declared in 4.99.6 behind theAPP_REST_API_ENABLEDflag, became unconditionally reachable when 4.104.0 extracted it into its own route file, and has now been retired.Webhook::classnever had arest_policies.phpentry, so every request inherited the globalauth => backenddefault and 401'd for the entire span, from the day it first shipped in 4.99.6 through today; no gateway was ever configured to call any of the five URLs. Legacy has always been, and remains, the platform's only functioning payment-webhook surface. See therest_api_versions.phpentry and #721 for the full rationale, including the two known security defects (#620, #621) that made deleting the unreachable handler preferable to giving it a policy entry.
Key architectural difference from the synchronous flow (CF-08):
- Webhooks are triggered by the payment server pushing to the shop. They are retryable by the provider and do not depend on the customer's browser session.
get_response(synchronous) is triggered by the customer's browser redirect back to the shop. It is a single-shot flow that also renders the thank-you page or error page for the customer.- For JCC and Viva Wallet, both flows can fire for the same order. The synchronous
get_responsechecks whether the order status has already been updated by the webhook and acts accordingly (displaying the result without re-processing).
API Reference
Webhook URL Endpoints
| Endpoint URL Pattern | Route Target | HTTP Method | Provider |
|---|---|---|---|
/jccNotification | webhooks/jcc/handleNotification | POST | JCC |
/klarnaAuthorizationCallback/{secretToken} | webhooks/KlarnaPayments/authorizationCallback/$1 | POST | Klarna |
/checkout/get_response/klarna_payments/notification | Adv_checkout::get_response() → klarnaPaymentsNotification() (Adv_checkout.php:2303-2309; no routes.php entry) | POST | Klarna (confirmation notification, #737) |
/handleSkroutzWebhook | webhooks/smartCart/handle | POST | Skroutz SmartCart |
/webrun/skroutzWebhookRequest | webhooks/smartCart/handle | POST | Skroutz SmartCart (legacy alias) |
/vivaWallet/{event} | webhooks/viva/handleWebhook/$1 | POST (or GET for verification) | Viva Wallet |
/checkout/xPayHook | checkout/xPayHook | POST | Nexi XPay (orders) |
/{lang}/checkout/xPayHook | checkout/xPayHook | POST | Nexi XPay (orders, localized) |
/gift-card/xPayHook | gift_cards/gift_card_page/xPayHook (via catch-all gift-card/(.+) at application/config/routes.php:740,742) | POST | Nexi XPay (gift cards) |
Legacy handler routes are defined in application/config/routes.php (lines 552, 565-568). XPay regular-order routes are at routes.php:636-637; the gift-card route uses the catch-all at :740,742.
Viva Wallet Verification Endpoint
Viva Wallet uses a verification handshake before activating webhooks. When Viva sends a GET request to the webhook URL with an empty body, the handler responds with a verification key generated via the Viva API (VivaWallet::generateWebhookVerificationKey()). This calls Viva's /api/messages/config/token endpoint with Basic Auth (merchantId:apiKey).
Code Flow
Controller Inheritance
Each webhook follows the same two-tier class structure:
Base_c (application/core/)
└─ Adv{Handler} (ecommercen/webhooks/) ← business logic
└─ {Handler} (application/controllers/webhooks/) ← empty subclass, client-overridableThe application/controllers/webhooks/ files are thin subclasses (typically empty) that allow client repos to override behavior by extending the same class name in their own application/controllers/webhooks/ directory.
XPay structural exception: The XPay handler does not live in
ecommercen/webhooks/. It is a public method onAdv_checkout(xPayHook, line 4040) for regular orders andAdvGiftCardPage(xPayHook, line 1660) for gift cards. Verification is delegated to the modernAdvisable\PaymentGateways\NexiXPay\XPayservice class — the only legacy webhook to use asrc/-domain helper.
JCC Webhook (AdvJcc)
File: ecommercen/webhooks/AdvJcc.phpController: application/controllers/webhooks/Jcc.phpTrait: OrderForErpHookFireTrait
Step-by-Step Flow
Receive POST at
/jccNotification- Reads all POST parameters via
$this->input->post() - If params are empty, logs error and exits
- Reads all POST parameters via
Look up order
- Queries
jcc_order_idstable bymdOrderparameter to find theshop_order_id - Loads the full order from
shop_orderviaorder_model->getRecordsByJccOrderId() - If no order found, logs error with
mdOrderandorderNumber, exits
- Queries
Validate HMAC-SHA256 checksum
- Retrieves
JCC.CALLBACK_TOKENfrom the registry - Removes the
checksumfield from params - Sorts remaining params alphabetically by key (
ksort) - Builds a parameter string in format:
key1;value1;key2;value2;... - Computes
HMAC-SHA256(paramString, callbackToken)and uppercases it - Compares against the received
checksumvalue
- Retrieves
Calculate status
- Only processes when
operationisapprovedordeposited - If
statusparam is'1'=> order status =PAID; any other value => order status =CANCELED(ecommercen/webhooks/AdvJcc.php:65:($params['status'] === '1') ? 'PAID' : 'CANCELED') - For other
operationvalues, returnsnull(no action)
- Only processes when
Apply status update
- If status is
PAID: firesafterOrderSuccessHooks(orderId)which calls the ERP hook - Updates
shop_orderwithstatusandmeta_data = 'controller:webhooks/jcc' - Returns HTTP 200
- If status is
Side Effects on PAID
internalApiOrderForErpHook($orderId)sends a GET request to the configured internal API ERP endpoint (internalApi.apiOrderWebHooks.erpReady/{orderId}) to notify the ERP system
Relationship with Synchronous Flow
The synchronous jccResponse() in Adv_checkout checks the order status first. If the order is no longer PENDING (because the webhook already processed it), it displays the appropriate success/failure message without re-processing. Only if the order is still PENDING does the synchronous flow query JCC's API for the order status.
Klarna Payments Webhook (AdvKlarnaPayments)
File: ecommercen/webhooks/AdvKlarnaPayments.phpController: application/controllers/webhooks/KlarnaPayments.php
Step-by-Step Flow
Receive POST at
/klarnaAuthorizationCallback/{secretToken}- Validates
secretTokenis not empty (returns 422 if missing) - Reads raw JSON body via
$this->input->raw_input_stream - Returns 422 if body is empty
- Validates
Validate payload
- Checks that
authorization_tokenandsession_idare both present - Logs individual errors for each missing field
- Returns 422 if validation fails
- Checks that
Update authorization token
- Queries
shop_order_klarna_paymentstable bysession_id - If no matching record found, logs error and returns 422
- Updates the
authorization_tokenfield on the matching record - Returns HTTP 200
- Queries
Important: No Status Change
This authorization callback (authorizationCallback) does not change order status; the separate notification arm below can. Klarna uses a decoupled flow:
- Customer authorizes payment on Klarna's side
- Klarna sends the authorization token to this webhook
- Later, during the
get_responseconfirmation stage (klarnaPaymentsConfirmation), the shop uses the stored authorization token to capture the payment - The checkout controller's
getAuthorizationToken()method looks up the token fromshop_order_klarna_paymentsif it was not passed directly in the checkout data - The modern REST
KlarnaAdapterlikewise recovers the stored token fromshop_order_klarna_paymentsvia theOrder\KlarnaPaymentrepository (recoverTokenFromCallback(), #307) when the front-end token is absent inpaymentData
Klarna Payments Notification (KlarnaNotificationHandler, #737)
File: src/Domains/Checkout/Payment/KlarnaNotificationHandler.phpEntry: POST /checkout/get_response/klarna_payments/notification → Adv_checkout::get_response() dispatches case 'klarna_payments', elseif ($get === 'notification') to klarnaPaymentsNotification() (Adv_checkout.php:2303-2309), which passes the raw body to klarnaNotificationHandler()->handle() and sets the returned HTTP status (:3885-3889). The URL is built by PaymentCallbackUrlBuilder::notificationUrl() (src/Domains/Checkout/Payment/PaymentCallbackUrlBuilder.php:156-162) and sent to Klarna as merchant_urls.notification (KlarnaAdapter.php:144-147); it carries no order serial and no secret, and there is no routes.php entry for it. The handler is built lazily because the Klarna client comes from getKlarnaSettings(), not the container (Adv_checkout.php:3895-3903, protected property :53-54).
Klarna posts here only for an order it created with fraud_status: PENDING and decided later. An order Klarna accepted at create-order time is confirmed synchronously by PlaceOrderService (see CF-08 Payment Processing) and is never notified (docblock KlarnaNotificationHandler.php:13-20). A legacy-placed order is unaffected: klarnaCreateOrderSuccess() already wrote PAID (Adv_checkout.php:3784-3787), so the notification stops at the status check.
Step-by-Step Flow
- Read
order_idfrom the JSON body. Missing or empty: answer 200 and log a warning with the body capped at 500 characters (KlarnaNotificationHandler.php:46-55). - Look up the order with
Order\Repository::findByTranTicketAndPayway($klarnaOrderId, 'klarna_payments')(:57;src/Domains/Order/Order/Repository/Repository.php:43). Unknown order: 200 (:59-64). - Status short-circuit. A status outside
OPEN_STATUSES = ['PENDING', 'CANCELED'](:33) answers 200 without calling Klarna (:66-73), because place-order hands the Klarna id to the customer and the URL can be replayed.CANCELEDis not short-circuited, so an "accepted too late" order is still logged. - Re-read the order from Klarna:
Klarna::getOrder()isGET {baseUrl}/ordermanagement/v1/orders/{id}(src/PaymentGateways/Klarna/Klarna.php:152-164). A failed or non-200 read returnsnulland the handler answers 503 so Klarna retries (KlarnaNotificationHandler.php:75-80). - Klarna
statusCANCELLEDorEXPIRED: 200, nothing confirmed (:36,:84-91). fraud_statusother thanACCEPTED(rejected, stopped, still pending): 200 with an info log; the order staysPENDINGfor the abandonment sweep (:93-101).ACCEPTED:PaymentConfirmationService::confirmPayment($orderId, ['transactionId' => $klarnaOrderId])(:103-106), which flipsPENDINGtoPAIDand dispatchesOrderPaid. APaymentTransition::Rejected(the order is no longerPENDING) is logged at error level and still answers 200 (:108-117).
Trust model. The caller is never trusted: the posted order_id only selects which Klarna order to ask about, and only Klarna's own ACCEPTED confirms the order (:18-21, decision #737 D3). Every terminal outcome answers 200; Klarna retries a non-200 notification every 10 minutes for up to 24 hours (docblock :22-24).
Skroutz SmartCart Webhook (AdvSmartCart)
File: ecommercen/webhooks/AdvSmartCart.phpController: application/controllers/webhooks/SmartCart.phpTrait: OrderForErpHookFireTraitModel: ecommercen/eshop/models/Adv_skroutz_orders_model.php
Step-by-Step Flow
Receive POST at
/handleSkroutzWebhook- Checks
SMARTCART.IS_ENABLEDregistry value; returns 500 if disabled - Reads raw JSON input stream; any
event_typeother thannew_order/order_updatedis ignored
- Checks
Fetch the order from Skroutz (#963)
- Skroutz signs nothing and documents no secret: its only published control is the list of source IP ranges, meant for the merchant's firewall. So the body is used only for
event_typeandorder.code order.codemust be letters, digits and dashes; returns 422 if not- The order is fetched with
SkroutzOrders::getOrderData()(GET {SMARTCART.API_URL}/{code}withSMARTCART.API_KEY), and everything below uses that copy - Returns 500 (Skroutz retries) when
API_URLorAPI_KEYis not set, when the fetch fails, or when the fetched order has another code
- Skroutz signs nothing and documents no secret: its only published control is the list of source IP ranges, meant for the merchant's firewall. So the body is used only for
Route by event type
new_orderevent:- Validates that
order.stateisopen; returns 422 if not - Calls
skroutz_orders_model->handleOrderCreation() - Checks for duplicate order by
code - Inserts into
skroutz_orderstable (code, state, invoice, comments, courier details, customer data, pickup/collection point info, express flag) - If
invoiceis true, inserts intoskroutz_invoice_details(company, VAT, DOY, address, VAT exclusion) - Inserts each line item into
skroutz_line_items(product details, quantity, pricing, size, EAN) - Returns 200 on success, 500 on failure
order_updatedevent:- Calls
skroutz_orders_model->handleOrderUpdate() - Updates the existing
skroutz_ordersrecord with new state, pickup window, location, courier voucher, tracking codes - Returns 200 on success, 500 on failure
- Then checks for express order auto-accept
- Validates that
Express order auto-accept (post-update)
- If
order.expressistrueandorder.stateisaccepted - Queries for a matching Skroutz order with
shop_order_id IS NULL(not yet converted to a shop order) - Calls
autoAcceptExpressOrder(code)which:- Creates a guest customer with a generated invalid email
- Builds a fake cart from Skroutz line items with live product data
- Creates a full shop order via
order_model->create_order_admin() - Sets the shop order status to
PAIDwith providerskroutz_smart_cart - Links the Skroutz order to the shop order (
shop_order_idupdate)
- Fires
afterOrderSuccessHooks()(ERP notification)
- If
Viva Wallet Webhook (AdvViva)
File: ecommercen/webhooks/AdvViva.phpController: application/controllers/webhooks/Viva.php
Step-by-Step Flow
Receive request at
/vivaWallet/{event}- Reads raw JSON body
- Verification handshake: if the body is empty AND the request method is GET, returns the webhook verification key via
$this->vivaWallet()->generateWebhookVerificationKey()(AdvViva.php:16-24); if the body is empty and the method is not GET, responds with HTTP 400 instead (AdvViva.php:19-21)
Look up order (dual-path)
- First searches
shop_orderbypayway = 'vivawallet'andtran_ticket = EventData.OrderCode - If not found, flags as gift card and searches
gift_card_ordersbytran_ticket - If neither found, logs error and exits
- First searches
Gateway confirmation gate (
AdvViva.php) — runs before either path below, on both the gift-card and regular-order branches- Events outside
HANDLED_EVENTS(transactionPaymentCreated,transactionFailed) are acknowledged with HTTP 200 before Viva is consulted at all (:8,:53-57) - For a handled event, calls
$this->vivaWallet()->vivaWalletValidateOrderIsPaid($transactionId)to verify the transaction against Viva's own record (:59-62) - If Viva is unreachable, responds with HTTP 502 so the notification is retried rather than lost (
:66-74) gatewayConfirms()(:153-168) must returntruebefore any write happens: it cross-checks the orderCode viatransactionBelongsToOrderCode()(:196-201), and for a success event also cross-checks the amount in integer minor units againstorder->amount(gift card) ororder->total_vat(regular order) viaamountConfirms()(:177-190) — the amount check is skipped (and logged) only when Viva reports the transaction as currency-converted- If
gatewayConfirms()returnsfalse, the handler logs and exits with HTTP 200 without writing anything
- Events outside
Gift card path (if order found in
gift_card_orders; only reached once the gateway confirmation gate above passes)Event Action transactionPaymentCreatedUpdates installments on the gift card order, then calls acceptGiftCard()transactionFailedCalls cancelGiftCard()Other events Exits silently acceptGiftCard()details:- Creates a coupon with type
GiftCard, discount equal to the gift card amount, max 1 usage, 5-year validity - Generates the coupon code
- Updates gift card order: status ->
Completed, setscompleted_at, linkscoupon_id, resetsemail_sentandsms_sentflags - Wrapped in a DB transaction
cancelGiftCard()details:- If status is
Pending: bulk-cancels (setsgift_card_status = Canceled,canceled_attimestamp) - If status is
Completed: deletes the associated coupon, nullscoupon_id, sets canceled status (wrapped in a DB transaction)
Returns HTTP 200 and exits.
- Creates a coupon with type
Regular order path (only reached once the gateway confirmation gate above passes)
- Idempotency guard: If order status is not
PENDING, logs a warning and exits (prevents double-processing) - Sets
meta_data = 'controller:WebhooksHandler:viva'
Event Status Update Additional Fields transactionPaymentCreatedPAIDviva_payway(mapped fromTransactionTypeId),installmentstransactionFailedCANCELEDNone Other events No action (exits) N/A - Calls
order_model->update_order()to persist the status change - Returns HTTP 200
- Idempotency guard: If order status is not
Viva Payment Method Mapping
The getVivaPaymentMethodFromTransaction() helper (in ecommercen/helpers/eshop_helper.php) maps Viva's TransactionTypeId integers to internal payment method strings. Key mappings:
| TransactionTypeId | Internal Method |
|---|---|
| 0, 1, 4-8, 13, 18-19, 22, 31, 69 | vivawallet_credit_card |
| 9, 11 | vivawallet_viva_wallet |
| 15 | vivawallet_dias |
| 16, 17 | vivawallet_cash |
| 23, 24 | vivawallet_ideal |
| 25, 26 | vivawallet_p24 |
| 48, 49 | vivawallet_paypal |
| 52, 53, 80, 81 | vivawallet_klarna |
| 60, 61 | vivawallet_iris |
| 62, 63 | vivawallet_pay_by_bank |
| 68 | vivawallet_pay_on_delivery |
(Plus additional methods: BLIK, PayU, Giropay, SOFORT, EPS, WeChat Pay, BitPay, Trustly, MB Way, Multibanco, Payconiq, Bancomat Pay, TBI Bank, Swish, Bluecode.)
ecommercen/helpers/eshop_helper.php:488
Relationship with Synchronous Flow
The synchronous vivaWalletResponse() in Adv_checkout:
- If order is still
PENDING, queries Viva's API to validate payment - If order is already
PAID(webhook arrived first), skips validation and renders the success page - The synchronous flow handles emails, SMS, stock updates, analytics, and session cleanup -- none of which the webhook handles
Important: The Viva Wallet webhook does not fire the ERP hook, send emails, or trigger any post-order side effects. This is by design -- the synchronous get_response flow handles those. If the synchronous flow arrives after the webhook, it detects the PAID status and still runs the full success pipeline.
XPay Webhook — Orders (Adv_checkout::xPayHook())
File: ecommercen/checkout/controllers/Adv_checkout.php:4040-4120Gateway service: src/PaymentGateways/NexiXPay/XPay.php
Step-by-step flow:
- Reads raw JSON via
$this->input->input_stream()— HTTP 400 on decode failure; audit-logsCALLBACKtoxpay_loggingvialogXPayTransaction(). XPay::parsePaymentNotification($notification)validatesoperation(required — real Greece S2S notifications carry no top-levelorder),operation.operationResult, and an order id inoperation.orderId(falling back to top-levelorder.orderIdonly for the order-creation shape); HTTP 400 onInvalidArgumentException.XPay::verifyNotificationSecurityToken($notification, $orderId)(defaultflow='order') — HTTP 401 on mismatch (see securityToken section below).- Order lookup via
order_model->getOrder(['order_serial' => $orderId])— HTTP 404 on miss. - REFUNDED notifications: logged, exit HTTP 200 with no state change.
- State machine:
shop_order.status | XPay status | Action |
|---|---|---|
| PENDING | PAID | processXPayPaymentResult() → mark PAID |
| PENDING | CANCELED | processXPayPaymentResult() → cancel |
| PAID | CANCELED | processXPayPaymentResult() → reversal |
| CANCELED | PAID | processXPayPaymentResult() → resurrect |
| other | any | log, exit HTTP 200, no change |
PAID side effects (via processXPayPaymentResult(), Adv_checkout.php:4262-4321, PAID case :4277-4295): one conditional claimPaid($serial, <current status>, 'xpay') (sets status, is_paid = 1 and meta_data, Adv_order_model.php:1151-1163) and, only for the caller that wins it, afterOrderSuccessHooks() (ERP) + adv_mailer->order_complete() + sendSmsSuccess() + informLowStock() + applyOrderGifts() (#962). CANCELED side effects: cancelOrder('xpay_callback') + afterOrderCancelHooks().
Note: unlike JCC/Viva, the XPay webhook fires customer-facing emails and SMS directly. See Known Issues.
XPay Webhook — Gift Cards (AdvGiftCardPage::xPayHook())
File: ecommercen/gift_cards/controllers/AdvGiftCardPage.php:1660-1741
Separate from checkout/xPayHook — lookup targets gift_card_orders, not orders. Uses flow='gift_card' to scope the securityToken lookup (cross-flow collision guard).
State machine via xpayWebhookAction(GiftCardStatus $current, string $xpayStatus): string:
Current gift_card_status | XPay status | Action |
|---|---|---|
| Pending | PAID | acceptGiftCard() + acceptPostActions() (mint coupon, Completed) |
| Pending | CANCELED | revokeGiftCard() + cancelPostActions() |
| Completed | CANCELED | revokeGiftCard() — reversal (revokes coupon) |
| other | any | noop (idempotency guard; acceptGiftCard() is not idempotent) |
xpayWebhookAction() is public static, pure, unit-tested at tests/Legacy/GiftCards/AdvGiftCardPageTest.php:28-114.
The webhook loads the order through giftCardForPayway($orderId, 'xpay') (AdvGiftCardPage.php:1688, helper :1187-1193), which answers HTTP 404 unless the gift-card order exists and was placed with the xpay payway. The CANCELED arm calls revokeGiftCard() (:1729), which cancels the order whatever its status and deletes a Completed order's coupon (AdvGiftCardOrdersModel.php:150-160); only this verified webhook reversal uses it. The browser returns (xPaySuccess() :1610, xPayCancel() :1638) reach cancelGiftCard() (:1201) instead, which cancels only a still-Pending order and returns a bool (AdvGiftCardOrdersModel.php:139-144), and errorView() runs cancelPostActions() only when it did (:1319-1324) (#957).
XPay securityToken Verification
XPay Greece's only documented webhook-authentication mechanism is the securityToken echo-back (no HMAC, per developer.nexigroup.com/xpaygreece/en-EU/api/notification-api-v1/).
Token lifecycle:
XPay::createHostedPaymentOrder()logs the Nexi HPP creation RESPONSE row toxpay_logging, which includessecurityTokeninresponse_data(src/PaymentGateways/NexiXPay/XPay.php:144).- On every notification, Nexi echoes the same token in
notification.securityToken. XPay::verifyNotificationSecurityToken()(:289) reads the stored token fromxpay_loggingfiltered by(order_serial, flow, transaction_type='RESPONSE', status='SUCCESS')ordered bycreated_at DESC(getStoredSecurityToken(),:315-342), then compares withhash_equals()(:304).
Fail-closed on all error paths: missing token field, non-string value, empty string, no stored row, malformed JSON, DB exception — all return false (regression tests at XPayTest.php:408-518, helpers from :380).
Cross-flow collision guard: the flow filter ('order' or 'gift_card') ensures a gift-card webhook cannot resolve a regular order's stored token even when GIFT_CARDS.ORDER_PREFIX is empty. Regression test at XPayTest.php:519-536.
Covering index: idx_token_lookup (order_serial, flow, transaction_type, status, created_at) on xpay_logging (database/migrations/20251117205429_create_xpay_logging_table.php:28-31).
ApcoPay Status Listener (Adv_checkout::apcopay_status())
File: ecommercen/checkout/controllers/Adv_checkout.php:2973-3030; route checkout/apcopay_status/(.+) (application/config/routes.php:620; the checkout/apcoPayFail/(.+) route points at the same method, :622). ApcoPay posts an XML result to this URL server-to-server; the handler is co-hosted on the checkout controller, not in ecommercen/webhooks/.
- Reads
ResultandOReffrom the XML (:2979-2992). - Calls
apcoPayGateway()->validateResponse($xml)once, before the resultswitch(:2997). That call asks ApcoPay for the transaction byORefand throws when ApcoPay returns nothing or a differentORef(src/ApcoPay/Response.php:27-75); the handler'scatchanswers 400 (:3022-3029), so a notification ApcoPay cannot confirm writes nothing, whatever result it claims. OK->apcoPaySuccessFromListener()(:2954-2971): the winner ofclaimPaid($serial, 'PENDING', 'apcopay_status')fires the ERP hook, mail, SMS, stock alert andapplyOrderGifts(); a loser returns.NOTOK,DECLINED,CANCEL->apcoPayFailFromListener()(:2934-2952): requires aPENDINGorder of paywayapcopay(isPendingOrderOfPayway(),:2253-2258) and winsclaimCanceled($serial, 'PENDING', 'get_response:apcopay')beforecancelOrder()andafterOrderCancelHooks()run.PENDINGand any other result are acknowledged without a change.
The browser-return page apcoPaySuccess() is a separate entry that renders only for the order the session placed; see CF-08 Payment Processing for the ownership rule (#958, #962).
Retired REST Webhook Handlers (Advisable-com/ecommercen#721)
Webhook::stripe(), vivawallet(), paypal(), piraeus(), and paybybank() — the five REST-routed handlers on the now-deleted src/Rest/Webhooks/Controllers/Webhook.php — are gone, along with their route file (application/config/webhook_routes.php), DI registration, and six-file unit test suite. See the retirement callout under Business Context above for why, and docs/decisions/721-retire-rest-webhooks.md for the full record. Two of the five gateways' payment adapters (PiraeusAdapter, PayByBankAdapter) had docblocks correcting their confirmation-mechanism citation from the deleted routes to the legacy checkout/get_response/{gateway} callback (Adv_checkout::piraeusResponse(), payByBankResponse()).
PaymentConfirmationService — No Longer Webhook-Driven
src/Domains/Checkout/PaymentConfirmationService.php (confirmPayment(), cancelPayment()) provided the idempotent order-status logic for the five retired REST webhook handlers. Since #754 confirmPayment() no longer sets shop_order.is_paid (PaymentConfirmationService.php:44-62), and the payment-status / confirm-payment responses dropped isPaid. Since #880 both methods are single conditional writes (transitionStatus PENDING to PAID at :84, PENDING to CANCELED inside transactional(...) at :172-180), only the call that wins the write runs the side effects (:15-24), and both return PaymentTransition (Applied, AlreadyApplied, Rejected); see CF-08 Payment Processing for the full contract. It was not deleted — it has other consumers unaffected by the retirement: the JWT-authenticated POST /rest/checkout/confirm-payment/{orderId} and cancel-payment/{orderId} client endpoints (src/Rest/Checkout/Controllers/Checkout.php:1760, and :2006 for the cancel, which goes through cancelByCustomer(): it wraps cancelPayment() with the PayByBank gateway step, #795, see CF-08 Payment Processing), Rest\Order\Controllers\Order (through cancelByCustomer(), src/Rest/Order/Controllers/Order.php:319), and the Jobs/PollPayByBankStatus polling job (PollPayByBankStatus.php:107, :121, :128). Two more consumers arrived with #737: PlaceOrderService confirms a gateway-accepted order synchronously (PlaceOrderService.php:857, see CF-08 Payment Processing) and the Klarna notification arm confirms a pending-review order (KlarnaNotificationHandler.php:103, the section above) — the second is the one webhook consumer. KlarnaAdapter itself is still not a consumer: it never calls the service and only returns PaymentInitResult::confirmed = true (src/Domains/Checkout/Payment/Adapters/KlarnaAdapter.php:172-177). Apart from the Klarna notification none of these is a webhook, so the service and its OrderPaid/OrderCanceled event-bus dispatch are otherwise out of scope for this doc — see CF-06 Order Preview for the confirm-payment endpoint and the full OrderPaid listener chain.
Domain Layer
Modern Domain (src/Domains/...)
Modern-domain files that served the retired REST webhook family are out of scope here (PaymentConfirmationService and StockService — see the note above; and Repository::findBySerialAndPayway(), which now has no production caller — its only consumer was the deleted controller; findByTranTicketAndPayway() is used again by the Klarna notification handler, KlarnaNotificationHandler.php:57). The modern-domain files still load-bearing for a live webhook:
| File | Responsibility |
|---|---|
src/Domains/Checkout/Payment/KlarnaNotificationHandler.php | Klarna merchant_urls.notification arm: order lookup by tran_ticket, re-read from Klarna, confirmation through PaymentConfirmationService (#737) |
src/PaymentGateways/NexiXPay/XPay.php | Nexi XPay Greece gateway service: HPP creation, order status query, notification parsing, securityToken verification (shared by both the orders and gift-card webhook paths) |
Legacy Layer (ecommercen/...)
Class Diagram
application/controllers/webhooks/
Jcc.php ─extends─> AdvJcc (ecommercen/webhooks/)
KlarnaPayments.php ─extends─> AdvKlarnaPayments (ecommercen/webhooks/)
SmartCart.php ─extends─> AdvSmartCart (ecommercen/webhooks/)
Viva.php ─extends─> AdvViva (ecommercen/webhooks/)| File | Responsibility |
|---|---|
ecommercen/webhooks/AdvJcc.php | JCC card payment notification handler; HMAC-SHA256 checksum validation |
ecommercen/webhooks/AdvKlarnaPayments.php | Klarna authorization token delivery; stores token in shop_order_klarna_payments |
ecommercen/webhooks/AdvSmartCart.php | Skroutz SmartCart order creation, update, and express auto-accept |
ecommercen/webhooks/AdvViva.php | Viva Wallet payment confirmation/failure; dual lookup for gift card orders |
ecommercen/checkout/controllers/Adv_checkout.php (xPayHook, processXPayPaymentResult, logXPayTransaction) | XPay webhook for regular orders; co-hosted on checkout controller |
ecommercen/gift_cards/controllers/AdvGiftCardPage.php (xPayHook, xpayWebhookAction) | XPay webhook for gift cards; co-hosted on gift-card controller |
application/controllers/webhooks/Jcc.php | Thin subclass; client-overridable entry point |
application/controllers/webhooks/KlarnaPayments.php | Thin subclass; client-overridable entry point |
application/controllers/webhooks/SmartCart.php | Thin subclass; client-overridable entry point |
application/controllers/webhooks/Viva.php | Thin subclass; client-overridable entry point |
All upstream handler classes extend Base_c (which extends Adv_base_controller). This gives them access to:
$this->registry(DB-backed configuration)$this->input(CI input class withpost(),raw_input_stream,inputStream())$this->load->model()(model loading)$this->output->set_header()(HTTP response headers)
ERP Hook Chain
OrderForErpHookFireTrait::internalApiOrderForErpHook($orderId)
└─ InternalApiOrderForErpHook::fireHook($orderId) [application/libraries/internal/]
└─ AdvInternalApiOrderForErpHook [ecommercen/libraries/internal/]
├─ FireHookTrait::fireHook()
│ ├─ IsApiEnabledTrait::isApiEnabled() ← checks config('internalApi.useApi')
│ ├─ getUrl($orderId) ← builds URL from config('internalApi.apiOrderWebHooks.erpReady')
│ └─ call($url, $orderId) ← Guzzle GET with Bearer token + timeout
└─ HookGetClientOptionsTrait
├─ getClient() ← Guzzle client with Authorization, Accept, Content-Type headers
└─ defaultRequestOptions() ← connect_timeout and timeout from configThe ERP hook is only fired by JCC and SmartCart webhooks via this trait. The Viva Wallet webhook and the Klarna authorization callback do not fire it. The Klarna notification arm reaches the ERP through a different route: confirmPayment() dispatches OrderPaid, and FireErpWebhookListener (registered with addPaidListener, src/Domains/Order/container.php:159) defers InternalApiOrderForErpHook::fireHook() (src/Domains/Order/Event/Listeners/FireErpWebhookListener.php:27-38). XPay also fires the ERP hook (via afterOrderSuccessHooks() in Adv_checkout::processXPayPaymentResult()).
Data Model
Database Tables Affected
| Table | Handler | Operation | Purpose |
|---|---|---|---|
shop_order | JCC, Viva | UPDATE | Status change (PAID/CANCELED), meta_data, viva_payway, installments |
shop_order | SmartCart (auto-accept) | INSERT + UPDATE | Creates new shop order, sets status to PAID |
jcc_order_ids | JCC | READ | Maps JCC mdOrder to shop_order_id |
shop_order_klarna_payments | Klarna (authorization callback) | READ + UPDATE | Stores/updates authorization_token by session_id |
shop_order | Klarna (notification) | READ + UPDATE | Looked up by tran_ticket + payway = 'klarna_payments'; confirmPayment() writes status and tran_ticket (KlarnaNotificationHandler.php:57, :103-106) |
skroutz_orders | SmartCart | INSERT + UPDATE | Stores marketplace order data |
skroutz_line_items | SmartCart | INSERT | Stores order line items |
skroutz_invoice_details | SmartCart | INSERT | Stores invoice data for business orders |
gift_card_orders | Viva (gift card) | READ + UPDATE | Status changes, installment updates |
coupons | Viva (gift card accept) | INSERT | Creates gift card coupon |
coupons | Viva (gift card cancel) | DELETE | Removes coupon if gift card was completed |
product_codes | SmartCart (auto-accept) | UPDATE | Stock decrement via create_order_admin |
shop_customer | SmartCart (auto-accept) | INSERT | Creates guest customer for marketplace order |
shop_order_basket | SmartCart (auto-accept) | INSERT | Order line items for the shop order |
xpay_logging | XPay (both flows) | INSERT + READ | Audit trail and securityToken lookup source |
gift_card_orders | XPay (gift cards) | UPDATE | Status (Completed/Canceled), coupon_id |
The Klarna notification lookup keys on shop_order.tran_ticket, which is now varchar(64) with index idx_shop_order_tran_ticket (added only when no index already leads with tran_ticket; a Klarna order id is a 36-character UUID and the column was varchar(32)). The migration has an empty down() and no backfill, so an existing REST Klarna order whose id was truncated at 32 characters still cannot be matched (database/migrations/20261110120000_widen_and_index_shop_order_tran_ticket.php:8-22, :35-38, :44-47; baseline database/initial/initial.sql:1387). See AD-03 Order Management for the shop_order schema.
Order Status Values
| Status | Meaning | Layer |
|---|---|---|
PENDING | Order created, awaiting payment confirmation | All (legacy webhook + synchronous) |
PAID | Payment confirmed successfully | All |
CANCELED | Payment failed or was rejected | All |
Gift Card Status Values (Spatie Enum)
| Status | Value | Meaning |
|---|---|---|
Pending | 1 | Awaiting payment |
Completed | 10 | Payment confirmed, coupon created |
Canceled | 11 | Payment failed or coupon deleted |
meta_data Field Tracing
The shop_order.meta_data field tracks which code path last modified the order:
| Value | Source |
|---|---|
controller:webhooks/jcc | JCC webhook |
controller:WebhooksHandler:viva | Viva Wallet legacy webhook |
model:set_status:CANCELED:update_order | update_order() when canceling (JCC/Viva legacy) |
model:set_is_paid | set_is_paid() in synchronous flow |
Historical only — orders placed before Advisable-com/ecommercen#721 may still carry a webhook:stripe, webhook:vivawallet (or :failed), webhook:paypal:{eventType}, webhook:piraeus (or :failed), or webhook:paybybank (or :cancelled / :ready_to_cancel) value, written by the now-deleted REST webhook controller. No live code path writes any webhook:* value today.
Configuration
Registry Keys
| Group | Key | Used By | Purpose |
|---|---|---|---|
JCC | CALLBACK_TOKEN | AdvJcc | HMAC-SHA256 secret for checksum validation |
SMARTCART | IS_ENABLED | AdvSmartCart | Feature flag to enable/disable SmartCart webhooks |
XPAY | API_KEY | XPay gateway service | X-API-KEY header for Nexi XPay Greece API calls |
XPAY | IS_PRODUCTION | XPay gateway service | Toggles between sandbox and production base URL |
STRIPE.WEBHOOK_SECRET and a Piraeus-keys-via-PiraeusConfig::fromArray() row previously appeared here — both were consumed only by the retired REST webhook handler. STRIPE.WEBHOOK_SECRET now has no reader anywhere in the codebase; Piraeus's config resolution for payment initialization (CF-08) uses PaymentInitializerFactory, not this doc's webhook confirmation path.
Application Config
| Config Path | Used By | Purpose |
|---|---|---|
internalApi.useApi | ERP hook | Master switch for internal API hooks |
internalApi.apiOrderWebHooks.erpReady | ERP hook | Base URL for ERP notification endpoint |
internalApi.apiToken | ERP hook | Bearer token for internal API auth |
internalApi.clientConnectTimeout | ERP hook | Guzzle connection timeout (seconds) |
Viva Wallet Config (via Factories::vivaWallet())
| Registry/Config | Purpose |
|---|---|
Viva merchantId | Basic Auth username for webhook verification |
Viva apiKey | Basic Auth password for webhook verification |
Viva isProduction | Determines verification URL (production vs demo) |
Client Extension Points
Overriding Webhook Handlers
Client repos can override any webhook handler by creating a class with the same name in application/controllers/webhooks/:
php
// application/controllers/webhooks/Jcc.php (client repo)
class Jcc extends AdvJcc
{
protected function afterOrderSuccessHooks(int $orderId): void
{
parent::afterOrderSuccessHooks($orderId);
// Client-specific logic (e.g., custom ERP integration, notifications)
}
}Key Override Points per Handler
| Handler | Overridable Methods | Purpose |
|---|---|---|
| AdvJcc | afterOrderSuccessHooks(), validateChecksum(), calculateStatus() | Custom ERP hooks, alternative validation, custom status logic |
| AdvKlarnaPayments | checkPayload(), updateShopOrderKlarnaPayment() | Additional validation, custom storage logic |
| AdvSmartCart | afterOrderSuccessHooks(), checkAndAutoAcceptExpressOrder() | Custom ERP hooks, custom auto-accept logic |
| AdvViva | handleWebhook() (entire method) | Full custom handling |
| Adv_checkout (xPayHook) | processXPayPaymentResult(), logXPayTransaction() — both protected | Custom side effects on PAID/CANCELED, custom audit logging |
| AdvGiftCardPage (xPayHook) | acceptGiftCard(), cancelGiftCard(), revokeGiftCard(), acceptPostActions(), cancelPostActions() — all protected (cancelGiftCard() is Pending-only and returns a bool; revokeGiftCard() is the webhook reversal) | Customize coupon issuance/revocation, post-acceptance side effects |
Adding New Webhook Handlers
To add a new payment webhook in a client repo:
- Create the handler class in
ecommercen/webhooks/Adv{Provider}.php(main repo) or directly inapplication/controllers/webhooks/{Provider}.php(client repo) - Add a route in
application/config/routes.php - If the handler needs to fire the ERP hook, use
OrderForErpHookFireTrait
Business Rules
| Rule | Description | Handler(s) |
|---|---|---|
| Legacy PENDING guard | Legacy Viva/JCC handlers only process orders in PENDING status and exit if the order is in any other state | Viva (legacy), JCC |
| Order existence check | All handlers verify the order exists before processing | All |
| HMAC validation | JCC validates callback authenticity via HMAC-SHA256 checksum | JCC |
| Feature flag | SmartCart requires SMARTCART.IS_ENABLED registry flag | SmartCart |
| ERP notification | ERP hook fires on successful payment (only if internalApi.useApi is enabled) | JCC, SmartCart (direct); XPay via afterOrderSuccessHooks() |
| No emails from legacy webhooks | Legacy webhook handlers do not send confirmation emails -- the synchronous flow handles this | JCC, Viva (XPay is an exception — see Known Issues) |
| Klarna authorization callback is decoupled | The authorization callback only stores the authorization token; payment capture happens at confirmation stage | Klarna (authorization callback) |
| Klarna notification is re-read, never trusted | The posted order_id only selects the Klarna order to read back; only Klarna's own fraud_status: ACCEPTED (and a Klarna status other than CANCELLED/EXPIRED) confirms the order (KlarnaNotificationHandler.php:75-103) | Klarna (notification) |
| Klarna notification 503 vs 200 | A failed Klarna read answers 503 so Klarna retries; every terminal outcome answers 200 (KlarnaNotificationHandler.php:77-80, :117) | Klarna (notification) |
Klarna notification OPEN_STATUSES short-circuit | An order whose status is not PENDING or CANCELED is answered 200 without a Klarna call (KlarnaNotificationHandler.php:33, :66-73) | Klarna (notification) |
| Express auto-accept | Skroutz express orders are automatically converted to shop orders when state becomes accepted | SmartCart |
| Gift card dual lookup | Viva webhook checks both shop_order and gift_card_orders tables | Viva |
| Gift card coupon lifecycle | Accept creates a coupon (5-year validity, 1 use); cancel deletes the coupon if already created | Viva |
| Webhook-first for JCC | JCC synchronous flow defers to webhook result if order is no longer PENDING | JCC |
| Viva pre-auth handling | Synchronous Viva flow detects when webhook already confirmed payment and renders success without reprocessing | Viva |
| Stock management (legacy cancel) | Legacy cancel via update_order triggers set_status('CANCELED') which calls returnOrderStock() to restore stock | JCC, Viva (legacy) |
| Meta data tracing | Each handler writes its identity into shop_order.meta_data for audit trail | JCC, Viva |
| XPay state machine (orders) | PENDING+PAID, PENDING+CANCELED, PAID+CANCELED (reversal), CANCELED+PAID (resurrect) — other combinations are noop (Adv_checkout.php:4098-4108) | XPay (orders) |
| XPay state machine (gift cards) | Pending+PAID→accept; Pending/Completed+CANCELED→cancel; all others noop to prevent duplicate coupon minting (AdvGiftCardPage.php:1763-1778) | XPay (gift cards) |
| XPay REFUND filter | REFUNDED notifications dropped silently by both handlers | XPay |
| XPay sends emails/SMS from webhook | Unlike JCC/Viva, the XPay webhook fires adv_mailer->order_complete(), sendSmsSuccess(), and informLowStock() on PAID | XPay (orders) |
Webhook vs. Synchronous Side Effects Comparison
The table below applies to the legacy webhook layer — the platform's only payment-webhook layer since Advisable-com/ecommercen#721 retired the REST family.
| Side Effect | Legacy Webhook | Synchronous (get_response) |
|---|---|---|
| Update order status | Yes | Yes |
| Fire ERP hook | JCC + SmartCart only (XPay also fires it via afterOrderSuccessHooks()) | Yes (all gateways) |
| Send confirmation email | No (except XPay orders webhook — see Known Issues) | Yes |
| Send confirmation SMS | No (except XPay orders webhook — see Known Issues) | Yes |
| Low stock notification | No (except XPay orders webhook — see Known Issues) | Yes |
| Analytics reporting (Matomo, Meta, Manago) | No | Yes |
| Destroy cart session | No | Yes |
| Guest customer logout | No | Yes |
| Render thank-you page | No | Yes |
Set is_paid = 1 | Legacy gateway handlers (incl. the XPay orders webhook, whose claimPaid() sets it in the same UPDATE as the status, Adv_checkout.php:4278, Adv_order_model.php:1151); the legacy synchronous path also sets it via set_is_paid() (Adv_order_model.php:1950-1952). REST PaymentConfirmationService::confirmPayment() no longer writes is_paid (#754, PaymentConfirmationService.php:44-62; the same comment names the legacy set_is_paid() sites) | Yes |
| Reserve stock at placement | All payways — reduceStockForOrder() at PlaceOrderService.php:823 (#282) | All payways — legacy create_order / POS |
| Restore stock on cancel | JCC/Viva via set_status('CANCELED', stockMode='+'); XPay via cancelOrder('xpay_callback') ('+' direction) | set_status('CANCELED', stockMode='+') |
Known Issues & Security Gaps
Items formerly numbered here for the REST webhook handlers (signature verification, gift-card support, unmatched-order handling, duplicate event dispatch, etc.) are removed: that controller and its
PaymentConfirmationServiceevent-bus consumers are retired or out of scope for this doc (Advisable-com/ecommercen#721 — see the callout under Business Context, anddocs/decisions/721-retire-rest-webhooks.mdfor the resolution history of each).
XPay webhook stamps
shop_order.meta_datathrough the order model, not itself: neitherxPayHook()norprocessXPayPaymentResult()writesmeta_datadirectly. The PAID branch'sclaimPaid()writesmodel:claimPaid:<fromStatus>:xpayand setsis_paid = 1in the same UPDATE (Adv_order_model.php:1151-1163); the CANCELED branch goes throughcancelOrder()->set_status(), which writesmodel:set_status:CANCELED:xpay_callback(Adv_checkout.php:4299-4305,Adv_checkout.php:2461-2469,Adv_order_model.php:1807-1810). The values are model-shaped, not thecontroller:...shape JCC and Viva write. Resolved for the PAID path by #962.XPay PAID→CANCELED reversal stock behavior:
cancelOrder()is called with'+'(positive) stock direction arg, restoring stock. Verify whetherset_status('PAID')previously decremented stock; if not, this reversal may double-credit. (ecommercen/checkout/controllers/Adv_checkout.php:4297-4309)XPay CANCELED→PAID resurrection re-sends customer emails/SMS: The PAID branch of
processXPayPaymentResult()always firesadv_mailer->order_complete()+sendSmsSuccess(), with no guard for prior sends. (ecommercen/checkout/controllers/Adv_checkout.php:4277-4295)XPay webhook fires emails/SMS — diverges from JCC/Viva contract; duplicate sends RESOLVED (#962): the webhook and
xPaySuccess()both reachprocessXPayPaymentResult(), whose PAID branch runs the mail, SMS, stock alert and gift stock only for the caller that winsclaimPaid(); a loser logs "was already moved" and breaks (ecommercen/checkout/controllers/Adv_checkout.php:4278-4292, log at:4279). The divergence from the JCC/Viva contract (the webhook itself sends customer mail) remains.RESOLVED (Advisable-com/ecommercen#962) — the success arm no longer writes request input to the order and acts only on the order the session placed. SeexPaySuccess()trusts request input before the gateway answersdocs/decisions/962-success-page-ownership.md.PayByBank legacy callback has no authenticationRESOLVED (Advisable-com/ecommercen#619, #780) —Adv_checkout::payByBankResponse()(ecommercen/checkout/controllers/Adv_checkout.php:1082-1153) now scopes the order lookup bypayway='paybybank'and requires a live PayByBank gateway confirmation (payByBankReportsPaid()/payByBankReportsCancelled(),:1176-1199) before moving the order to PAID or CANCELED; every exit path answers identically viaacknowledgePayByBankCallback()(:1164-1168), removing the serial-enumeration oracle. Seedocs/decisions/619-paybybank-forged-callback.mdanddocs/decisions/780-paybybank-cancel-arm-gate.md.xPayCancel()cancels aPENDINGorder on an unverified request (open, tracked as Advisable-com/ecommercen#849): the browser-return cancel armGET checkout/get_response/xpay/cancel/{serial}?paymentid=<anything>(Adv_checkout.php:2312->xpayResponse():4362-4369) reachesxPayCancel()(:4215-4252), whose only guard is that apaymentidquery value is present (:4222-4225). It overwritestran_ticketwith that value (:4227-4228) and cancels anyPENDINGorder whatever its payway, with no gateway check (:4231-4239:cancelOrder(... 'get_response:xpay' ...)+afterOrderCancelHooks()). ContrastxPaySuccess(), which requirespayway === 'xpay'(:4133), and the ApcoPay and Piraeus cancel arms, which #958 closed. Row (d) of #849 names this route, anddocs/decisions/962-success-page-ownership.mdlistsxPayCancel()as out of scope for #962 and #958. The gift-cardxPayCancel()is not affected: it loads the order throughgiftCardForPayway($orderId, 'xpay')and cancels only a Pending order (AdvGiftCardPage.php:1638-1649,:1187-1193).Klarna notification endpoint is unauthenticated by design (documented trade-off, #737 D3):
checkout/get_response/klarna_payments/notificationcarries no secret and no serial, so anyone can POST to it. The only cost of a repeat call is one Klarna Order Management read, and only for aPENDINGorCANCELEDorder; every other status is answered before Klarna is called (KlarnaNotificationHandler.php:66-73). A forged call cannot confirm an order, because only Klarna's answer does (:93-103). See decision record 737.The 180-minute sweep can cancel an order still in Klarna fraud review (open, #1043): Klarna's pending fraud review exists only for US/UK merchants (
KlarnaAdapter.php:42-46). If the review outlasts the sweep,AdvCancelIncompleteOrderscancels the order first; a laterACCEPTEDnotification then finds itCANCELED,confirmPayment()returnsRejected, and the handler only logs at error level and answers 200 (KlarnaNotificationHandler.php:108-117; sweepAdvCancelIncompleteOrders.php:91-99). See SY-03.A confirmation that throws after Klarna charged leaves the order
PENDINGwith no webhook to follow (open, #1043):PlaceOrderServicecatches the exception, logs it withlog_message('error', ...)and keeps the response atPENDING(PlaceOrderService.php:874-885); Klarna does not notify an order it accepted synchronously, so only the sweep (and so a cancel of a paid order) ends it. See CF-08 Payment Processing.REST
verifyWithGateway()has no Klarna arm (open, #1044): theconfirm-paymentgateway check handles onlystripe,vivawalletandpaypaladvanced(src/Rest/Checkout/Controllers/Checkout.php:2054-2089), so aklarna_paymentsorder cannot be settled through the client endpoint and depends on the synchronous confirmation or the notification arm above.
Tests
| Test File | What It Covers |
|---|---|
tests/Unit/PaymentGateways/NexiXPay/XPayTest.php | 45 tests on gateway service: parsePaymentNotification, mapOperationResultToStatus, verifyNotificationSecurityToken (11 cases incl. cross-flow guard), HTTP-mocked HPP creation and order status, API-key redaction. Does NOT cover the controller-level xPayHook() — only the gateway helper. |
tests/Legacy/GiftCards/AdvGiftCardPageTest.php | 3 xpayWebhookAction tests (decision-matrix provider, exhaustive matrix walk, regression guard; AdvGiftCardPageTest.php:28-114); the file also holds Piraeus, installment and mail-rule tests |
tests/Unit/Checkout/Payment/KlarnaNotificationHandlerTest.php, tests/Legacy/Checkout/AdvCheckoutKlarnaNotificationTest.php | The Klarna notification arm (#737): handler outcomes (200 / 503, OPEN_STATUSES short-circuit, ACCEPTED confirm) and the Adv_checkout::klarnaPaymentsNotification() wiring |
tests/Integration/Domains/Checkout/KlarnaRestConfirmationFlowTest.php | Klarna REST confirmation end to end (needs the test DB) |
tests/Unit/PaymentGateways/Klarna/KlarnaTest.php | Klarna::getOrder() among the Klarna client cases |
tests/Legacy/Webhooks/AdvVivaTest.php + AdvSmartCartTest.php | 38 combined tests: handleWebhook/handle dispatch, payload validation, status transitions via reflection + mocked models |
No unit tests exist for the legacy webhook controllers ( RESOLVED (commit AdvJcc, AdvKlarnaPayments, AdvSmartCart, AdvViva).4fd81ed1e, Advisable-com/ecommercen#34) — see AdvVivaTest/AdvSmartCartTest above. (The REST Webhook controller's own six-file test suite, added by the same effort for Stripe/Viva/PayPal/Piraeus/PayByBank, was removed along with the controller in Advisable-com/ecommercen#721.) The controller-level XPay webhook flow (Adv_checkout::xPayHook()) also has no controller test; only the underlying XPay gateway service and the gift-card state machine are directly unit-tested.
Related Flows
- CF-06 Order Preview & Checkout --
confirm-paymentclient endpoint usesPaymentConfirmationServicefor idempotent status updates; fullOrderPaidlistener chain - CF-07 Order Confirmation -- order creation that triggers payment
- CF-08 Payment Processing -- synchronous
get_responseflow that complements webhooks; Klarna synchronous confirmation inPlaceOrderService - Decision 737 Klarna REST confirmation -- why the notification arm re-reads Klarna, and the known limits
- CF-23 Gift Cards -- Viva Wallet gift card purchase and coupon creation
- AD-03 Order Management -- order status lifecycle and admin actions
- AD-11 Marketplace Orders -- Skroutz SmartCart order management in admin
- IN-08 ERP Integrations -- ERP hook fired by JCC and SmartCart webhooks
- IN-20 Order Webhooks -- general order webhook integrations