Skip to content

Nexi XPay Greece — Hosted Payment Page Integration ​

Flow ID: IN-23 | Module(s): checkout, gift_cards, job, eshop | Complexity: High Last Updated: 2026-11-04 — 4.129.0 resync: xPaySuccess() now answers only for an xpay order the session placed and renders the thank-you page once (#962), and the PAID transition is the conditional claimPaid() claim, so only the winner sends mail and SMS and applies gift stock (#962); gift-card browser returns load the order by payway, cancel only a Pending order, and only the webhook reversal revokes (revokeGiftCard(), #957); xPayCancel() added to Known Issues as the open #849 item; Known Issues 3, 6 and 7 corrected; Adv_checkout.php, Adv_settings.php and AdvCancelPendingGiftCards.php citations re-anchored; previous: 2026-10-13 — 4.127.0 resync: AdvCancelIncompleteOrders.php citations re-anchored after the PayPal sweep rewrite (#916: constant :19 unchanged, handlePendingXpayOrders() :301-327, xPayExpirationSeconds() :397-406), Adv_checkout.php / XPayAdapter.php / PaymentInitializerFactory.php citations re-anchored; previous: 2026-10-02 — 4.125.0 resync: AdvCancelIncompleteOrders.php citations re-anchored (constant :19, handlePendingXpayOrders() :238-264); previous note, 2026-09-29 — Adv_checkout.php / Adv_settings.php citations re-anchored for the 4.124.0 line shift (+3); previous note, 2026-09-14 — Advisable-com/ecommercen#729: getXPaySettings() citation moved again to registry_helper.php:586-594 after getVivaWalletExternalSettings() was inserted between getVivaWalletMergedSettings() and getJccSettings(); the helper itself is unchanged. (Previously moved to :534-542 by #706.)

Business Overview ​

Nexi XPay Greece is a card-payment gateway used by Greek merchants. The integration uses the Hosted Payment Page (HPP) model: the platform creates an order on the Nexi API, receives a redirect URL, and hands the browser off to Nexi's own checkout page. Nexi handles all card-number entry and 3-D Secure challenges. When the customer finishes, Nexi fires a server-to-server webhook and redirects the browser back to the merchant return URLs.

Two independent payment surfaces share the same gateway class:

  • Regular checkout (checkout module) — for standard shop orders stored in the shop_order table.
  • Gift card checkout (gift_cards module) — for gift card purchases stored in gift_card_orders.

Both environments (sandbox and production) are supported via a single boolean toggle. URLs:

  • Sandbox: https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/ (src/PaymentGateways/NexiXPay/XPay.php:12)
  • Production: https://xpay.nexigroup.com/api/phoenix-0.0/psp/ (src/PaymentGateways/NexiXPay/XPay.php:11)

API Reference ​

HPP Order Creation ​

Request — POST api/v1/orders/hpp

Headers:

HeaderValue
X-API-KEYMerchant API key from registry
Correlation-IdUUID v4 generated per request
Content-Typeapplication/json

Payload shape (src/PaymentGateways/NexiXPay/XPay.php:84-102):

order.orderId          → merchant order serial
order.amount           → cents (EUR×100)
order.currency         → 'EUR'
order.customerId       → optional
order.description      → optional
order.customerInfo.cardHolderEmail         → optional
order.customerInfo.mobilePhoneCountryCode  → optional
order.customerInfo.mobilePhone             → optional
paymentSession.actionType   → 'PAY'
paymentSession.recurrence.action → 'NO_RECURRING'
paymentSession.amount       → cents
paymentSession.language     → ISO 639-2 (default 'ELL' for Greek)
paymentSession.paymentService → 'cards'
paymentSession.resultUrl    → success redirect URL
paymentSession.cancelUrl    → cancel redirect URL
paymentSession.notificationUrl → server-to-server webhook URL

Success response (HTTP 200):

FieldDescription
hostedPageURL the browser must be redirected to
orderIdNexi-side order identifier (stored as tran_ticket)
securityTokenOpaque token echoed back in every webhook notification

If the response lacks hostedPage, the method returns null and logs an error (src/PaymentGateways/NexiXPay/XPay.php:156-158).

Order Status Query ​

Request — GET api/v1/orders/{xpayOrderId} (src/PaymentGateways/NexiXPay/XPay.php:350)

Returns the latest operation from the operations array (index 0). The caller uses operationResult to determine the current payment state.

operationResult Status Mapping ​

XPay::mapOperationResultToStatus() (src/PaymentGateways/NexiXPay/XPay.php:410-428):

Nexi operationResultInternal status
AUTHORIZED, EXECUTEDPAID
DECLINED, DENIED_BY_RISK, THREEDS_FAILED, VOIDED, FAILED, CANCELEDCANCELED
THREEDS_VALIDATED, PENDINGPENDING
REFUNDEDREFUNDED
anything elseUNKNOWN

Webhook Notification Shape ​

Nexi delivers a JSON body with a top-level operation object. Real Nexi/XPay Greece S2S notifications carry no top-level order — that key only appears in the order-creation response shape (see above). Required fields:

  • operation (object, required)
  • operation.operationResult (string)
  • operation.orderId (merchant order serial) — falls back to a top-level order.orderId only for the order-creation shape
  • securityToken (root level — echoed from HPP creation response)

XPay::parsePaymentNotification() throws \InvalidArgumentException in exactly three cases (src/PaymentGateways/NexiXPay/XPay.php:222-248; fixed in Advisable-com/ecommercen#427):

  • operation absent — "Missing required field in notification: operation"
  • operation.operationResult absent — "Missing operationResult in notification"
  • no order id in either operation.orderId or order.orderId — "Missing orderId in notification"

Code Flow ​

Regular Checkout — Initiation ​

Entry: Adv_checkout::run($checkoutdata = []) dispatches case 'xpay' to xpay() (ecommercen/checkout/controllers/Adv_checkout.php:172).

run() records the order serial in the session before dispatching (rememberPlacedOrder(), Adv_checkout.php:109-111); the return page uses it (see xPaySuccess() below).

  1. Calls getXPaySettings() to load API key and environment flag (Adv_checkout.php:3960).
  2. Loads order and customer records; redirects to preview_order on lookup failure (Adv_checkout.php:3962-3979).
  3. Builds return URLs:
    • successUrl → checkout/get_response/xpay/success/{serial} (Adv_checkout.php:3983)
    • cancelUrl → checkout/get_response/xpay/cancel/{serial} (Adv_checkout.php:3984)
    • notificationUrl → checkout/xPayHook (Adv_checkout.php:3985)
  4. Splits customer phone via PhoneHelper::splitInternationalAndNational() (Adv_checkout.php:3987-4004).
  5. Calls XPay::createHostedPaymentOrder() with amount as $orderData->total_vat in EUR (Adv_checkout.php:4009-4017).
  6. On failure: logs REQUEST_FAILED, sets session error, redirects to preview_order (Adv_checkout.php:4019-4026).
  7. On success: logs REQUEST and redirects browser to $response['hostedPage'] (Adv_checkout.php:4028-4031).

Regular Checkout — Webhook (POST checkout/xPayHook) ​

Adv_checkout::xPayHook() (Adv_checkout.php:4040):

  1. Decodes input_stream() JSON; returns HTTP 400 on failure (Adv_checkout.php:4042-4049).
  2. Logs a CALLBACK row to xpay_logging via logXPayTransaction() before any verification (Adv_checkout.php:4053).
  3. Calls XPay::parsePaymentNotification(); returns HTTP 400 on \Exception (Adv_checkout.php:4055-4062).
  4. Calls XPay::verifyNotificationSecurityToken(); returns HTTP 401 on failure (Adv_checkout.php:4064-4071).
  5. Loads order; returns HTTP 404 if not found (Adv_checkout.php:4074-4080).
  6. Ignores REFUNDED notifications with an info log (Adv_checkout.php:4086-4092).
  7. State machine — updates when the transition is safe (Adv_checkout.php:4098-4108):
    • PENDING + PAID → update
    • PENDING + CANCELED → update
    • PAID + CANCELED → update (reversal)
    • CANCELED + PAID → update (resurrection)
  8. Delegates to processXPayPaymentResult(): for PAID it wins order_model->claimPaid($serial, <current status>, 'xpay') (one conditional UPDATE that also sets is_paid = 1 and meta_data), and only the winner triggers the post-hooks (ERP hook, email, SMS, stock alert, applyOrderGifts()); for CANCELED it calls cancelOrder() (Adv_checkout.php:4262-4321).

Regular Checkout — Return URLs ​

xpayResponse() dispatches get_response/xpay/{action} to xPaySuccess() or xPayCancel() (Adv_checkout.php:4362-4375).

xPaySuccess() (Adv_checkout.php:4126):

  1. Reads order_serial from URI segment 5 and paymentid from query string. Answers inactive_payment() unless the order exists, a paymentid is present and payway === 'xpay' (:4093-4100).
  2. Calls XPay::getOrderStatus() through the xPayGateway() seam (:4102-4103, seam :4341-4344); answers inactive_payment() when the gateway does not answer (:4105-4109).
  3. Maps operationResult; if PAID and the order is not yet PAID, calls processXPayPaymentResult() (:4122-4132). It then renders the success view (checkoutXPaySuccess) only if isPlacedOrder($orderData) (the session marker checkout_placed_order_serial equals this order's serial) and calls forgetPlacedOrder(); otherwise inactive_payment() (:4134-4138). The page runs renderOrderBasket() + reportPurchase() (:4160-4161).
  4. If not PAID, delegates to xPayCancel() (:4169).

It no longer writes tran_ticket from the query string (#962).

xPayCancel() (Adv_checkout.php:4215):

  1. Requires paymentid (:4186-4189), overwrites tran_ticket with it (:4191-4192) and cancels the order via cancelOrder() if it is still PENDING, regardless of payway (:4195-4203) — see Known Issue 11.
  2. Renders the failure view (checkoutXPayFail).

Regular Checkout — Cron Reconciliation ​

See SY-03 Incomplete Order Cancellation for the full reconciliation mechanics and grace-period behavior controlled by the XPAY/EXPIRATION registry key.

Gift Card Checkout — Initiation ​

AdvGiftCardPage::getPayWayFormData() dispatches case 'xpay' to xpayFormData() (ecommercen/gift_cards/controllers/AdvGiftCardPage.php:120).

xpayFormData() (AdvGiftCardPage.php:1560):

  1. Calls getXPaySettings() and builds a customer payload from gift_card_orders + phone splitting.
  2. Calls XPay::createHostedPaymentOrder() with the gift-card amount from $postData['giftCard'], the current store currency code, and the 'gift_card' flow discriminator (AdvGiftCardPage.php:1583-1592).
  3. Stores $response['orderId'] as tran_ticket on the gift card order row (AdvGiftCardPage.php:1601).
  4. Returns a ['type' => 'redirect', 'url' => $response['hostedPage']] envelope.

Gift Card Checkout — Webhook (POST gift-card/xPayHook) ​

AdvGiftCardPage::xPayHook() (AdvGiftCardPage.php:1660):

  1. Decodes input_stream() JSON; returns HTTP 400 on failure.
  2. Parses and verifies securityToken with flow 'gift_card' (AdvGiftCardPage.php:1681); returns HTTP 401 on failure.
  3. Ignores REFUNDED (AdvGiftCardPage.php:1698).
  4. Resolves GiftCardStatus enum from $orderObj->gift_card_status; logs error and returns on unknown value.
  5. Dispatches xpayWebhookAction() result:
    • 'accept' → acceptGiftCard() (issues coupon, marks Completed); acceptPostActions() now runs only when the claim succeeds — a refused claim logs and returns early without issuing a coupon (AdvGiftCardPage.php:1713-1727)
    • 'cancel' → revokeGiftCard() (AdvGiftCardPage.php:1729; cancels whatever the status and deletes a Completed order's coupon) + cancelPostActions()
    • 'noop' → logs and returns without modification

Gift Card — State Machine ​

AdvGiftCardPage::xpayWebhookAction(GiftCardStatus, string): string (AdvGiftCardPage.php:1763):

Current statusXPay statusAction
PendingPAIDaccept
PendingCANCELEDcancel
CompletedCANCELEDcancel (reversal)
CompletedPAIDnoop (outcome selection only — see BR6; duplicate-coupon safety lives in the model UPDATE)
Canceledanynoop (terminal)
anyPENDING / REFUNDED / unknownnoop

REFUNDED is filtered upstream in xPayHook() before xpayWebhookAction() is called (AdvGiftCardPage.php:1698).

Gift Card Checkout — Return URLs ​

The storefront return-URL path is guarded the same way as the webhook (#583). successView() fires acceptPostActions() and renderSuccess() only when the claim succeeds. A refused claim, such as a refreshed return URL, goes to renderResolved(), which shows the page without the coupon code (AdvGiftCardPage.php:1263-1270). renderResolved() (:1292) shows renderCompleted() (:1307, view application/views/main/layouts/gift_cards/completed.php) for a Completed order and the error page otherwise.

xPaySuccess() (AdvGiftCardPage.php:1610), xPayCancel() (:1638) and xPayHook() (:1688) load the order through giftCardForPayway($orderId, 'xpay') (:1187-1193), which answers 404 (HTTP 404 for the hook) unless the gift-card order exists and was placed with the xpay payway. Browser returns reach cancelGiftCard() (:1201), which cancels only a still-Pending order and returns a bool, and errorView() runs cancelPostActions() only when it did (:1319-1324). Only the verified webhook reversal uses revokeGiftCard() (:1210) (#957). AdvGiftCardPage::acceptGiftCard()'s own signature changed from void to bool (AdvGiftCardPage.php:1228).

Admin manual acceptance. POST /admin/giftCards/acceptGiftCard/{orderId} (admin-only; no public REST contract changed) now answers 409 Conflict with {"error": "This gift card order is already completed."} and skips post-actions when the order is already Completed; 404/500 responses are unchanged (AdvGiftCardAdminListing.php:149-152). Full admin-side coverage lives in AD-23 Gift Cards Admin.

Gift Card — Cron Reconciliation ​

AdvCancelPendingGiftCards::cancelPendingXpayOrders() (ecommercen/gift_cards/jobs/AdvCancelPendingGiftCards.php:286-311):

  • Queries pending gift card orders with payway='xpay' and created_at < now() - giftCardDateTimeIntervalToDrop.
  • Calls XPay::getOrderStatus() for each; accepts if PAID, cancels otherwise — the accept call is Pending-only and can be a silent no-op if the order has already moved past Pending (AdvCancelPendingGiftCards.php:307-309).
  • XPay orders are excluded from the bulk-cancel query that handles all other payways (AdvCancelPendingGiftCards.php:44).

Data Model ​

xpay_logging table ​

Created by database/migrations/20251117205429_create_xpay_logging_table.php.

ColumnTypeNotes
idunsigned int, auto-increment PK
order_serialVARCHAR(50) NOT NULLMerchant order serial
flowVARCHAR(20) NOT NULL'order' or 'gift_card'
transaction_idVARCHAR(100) NULLNexi-side order ID (populated on RESPONSE rows)
transaction_typeVARCHAR(50)REQUEST, RESPONSE, CALLBACK, PROCESSED, STATUS_CHECK, REQUEST_FAILED
request_dataTEXT NULLJSON-encoded request payload
response_dataTEXT NULLJSON-encoded response payload (contains securityToken on successful RESPONSE rows)
statusVARCHAR(50) NULLSUCCESS (for REQUEST/RESPONSE rows), FAILED (for errors), raw Nexi operationResult for PROCESSED rows (AUTHORIZED, EXECUTED, DECLINED, etc.), or null (STATUS_CHECK, CALLBACK)
created_atTIMESTAMP DEFAULT CURRENT_TIMESTAMP

Indexes (migration:20-31):

NameColumnsPurpose
idx_order_serialorder_serialOrder lookup
idx_transaction_idtransaction_idNexi-side ID lookup
idx_created_atcreated_atTime-range queries
idx_token_lookup(order_serial, flow, transaction_type, status, created_at)Covering index for getStoredSecurityToken() query

Write sources ​

xpay_logging is written from two separate code paths:

  1. XPay::logToDatabase() (src/PaymentGateways/NexiXPay/XPay.php:527) — writes REQUEST and RESPONSE rows (with flow and securityToken) during createHostedPaymentOrder(), and also writes RESPONSE/FAILED rows on GuzzleException (XPay.php:186-192).
  2. Adv_checkout::logXPayTransaction() (ecommercen/checkout/controllers/Adv_checkout.php:4332) — writes REQUEST, CALLBACK, PROCESSED, STATUS_CHECK, and REQUEST_FAILED rows but does not populate flow or transaction_id.

shop_order table (regular flow) ​

  • status is set to PAID or CANCELED by processXPayPaymentResult().
  • is_paid flag is set to 1 on PAID, by claimPaid() (Adv_checkout.php:4278).

gift_card_orders table (gift card flow) ​

  • tran_ticket is written with the Nexi-side orderId at HPP creation time (AdvGiftCardPage.php:1601).
  • gift_card_status transitions via six writers: acceptGiftCard() (Pending-only, ecommercen/gift_cards/models/AdvGiftCardOrdersModel.php:49), acceptGiftCardManually() (additionally allows Canceled, used only by the admin grid, :62), cancelGiftCard() (:139, now Pending-only: calls cancelPending() and returns whether a row changed), revokeGiftCard() (:150, cancels whatever the status and deletes a Completed order's coupon; used by the admin grid, AdvGiftCardAdminListing.php:123, and the XPay reversal webhook), cancelPending() (:162-175) — the bulk-cancel writer, called directly by the cron's bulk sweep (AdvCancelPendingGiftCards.php:49), bypassing cancelGiftCard() — and the generic update_giftcard_order() (:331-334) used by the Viva webhook path. Both accept paths funnel through acceptGiftCardFrom() (:70).

Domain Layer ​

Modern Layer ​

src/PaymentGateways/NexiXPay/XPay.php — PSR-4 class under Advisable\PaymentGateways\NexiXPay. Constructor accepts optional ?CI_DB_query_builder $db and ?Client $httpClient for testability; production callers use new XPay($config) and receive the autowired DI-container DB handle (XPay.php:36-53).

Public API:

MethodDescription
createHostedPaymentOrder(...)Creates an HPP order on the Nexi API; logs REQUEST and RESPONSE to xpay_logging
getOrderStatus(string $xpayOrderId)Polls GET api/v1/orders/{id}; returns parsed response or null on failure
parsePaymentNotification(array $notification)Validates and normalises a webhook payload; throws on missing required fields
verifyNotificationSecurityToken(array $notification, string $orderSerial, string $flow = 'order')Compares inbound securityToken against stored value using hash_equals; fail-closed
mapOperationResultToStatus(string $operationResult)Maps Nexi enum values to internal PAID / CANCELED / PENDING / REFUNDED / UNKNOWN
generateCorrelationId()Returns UUID v4 as required by the Nexi API header
formatAmount(float $amount, string $currency)Converts to integer cents via (int)round($amount * 100)

REST Adapter ​

The REST checkout path uses XPayAdapter (src/Domains/Checkout/Payment/Adapters/XPayAdapter.php) which wraps XPay for PaymentAdapterInterface. Its initializePayment() delegates to XPay::createHostedPaymentOrder() and returns a PaymentInitResult containing a GET redirect to the hosted page.

renderOrderDescription() (XPayAdapter.php:90-99) calls t(self::ORDER_DESCRIPTION_KEY, [$context->orderSerial, $this->siteName]) using the constant ORDER_DESCRIPTION_KEY = 'checkout.xpay.order_description' (XPayAdapter.php:43). This is the same translation key and argument order used by the legacy storefront, so the Nexi order.description field is byte-for-byte identical and localized whether the order is placed via the legacy storefront or the REST API.

siteName is wired from config_item('site_name') by PaymentInitializerFactory::registerXPay() (src/Domains/Checkout/Payment/PaymentInitializerFactory.php:424-425). The factory reuses the legacy server-to-server webhook URL (checkout/xPayHook) until a dedicated REST webhook handler lands; order_serial is shared between legacy and REST orders so the legacy handler resolves REST-placed orders transparently (PaymentInitializerFactory.php:420-423). See CF-08 Payment Processing for the full REST payment adapter conventions.

Legacy Layer ​

FileRole
ecommercen/checkout/controllers/Adv_checkout.phpRegular checkout — xpay(), xPayHook(), xPaySuccess(), xPayCancel(), xpayResponse(), processXPayPaymentResult(), logXPayTransaction()
ecommercen/gift_cards/controllers/AdvGiftCardPage.phpGift card checkout — xpayFormData(), xPayHook(), xPaySuccess(), xPayCancel(), xpayWebhookAction()
ecommercen/job/libraries/AdvCancelIncompleteOrders.phpRegular order cron reconciliation — handlePendingXpayOrders(), lazy xPay() accessor
ecommercen/gift_cards/jobs/AdvCancelPendingGiftCards.phpGift card cron reconciliation — cancelPendingXpayOrders()
ecommercen/helpers/registry_helper.phpgetXPaySettings() helper — reads XPAY.API_KEY and XPAY.IS_PRODUCTION from the registry (registry_helper.php:586-594)
ecommercen/eshop/libraries/AdvPaymentsRegistry.phpRegisters the xpay provider config with two settings: API_KEY (password type, required) and IS_PRODUCTION (checkbox, default false) (AdvPaymentsRegistry.php:697-706)

Configuration ​

Most XPay settings are stored in the XPAY registry group and surfaced in the admin payment-settings view (write path: ecommercen/settings/controllers/Adv_settings.php:1493-1494; read/render: :1664-1665).

Registry KeyTypeRequiredDescription
XPAY.API_KEYpasswordYesMerchant API key issued by Nexi
XPAY.IS_PRODUCTIONbooleanNo (default false)false = sandbox, true = live production
XPAY.EXPIRATIONstring (DateInterval)No (default 10800 sec)Grace seconds: orders unresolved after this window are dropped by the cron (xPayExpirationSeconds() reader at ecommercen/job/libraries/AdvCancelIncompleteOrders.php:393-402)

getXPaySettings() reads the first two keys and returns an array consumed by new XPay($config) (ecommercen/helpers/registry_helper.php:586-594). Note: getXPaySettings() does NOT read XPAY.EXPIRATION; the cron reads it from the registry via xPayExpirationSeconds() (AdvCancelIncompleteOrders.php:393-402), falling back to the XPAY_DEFAULT_EXPIRATION_SECONDS = 10800 class constant at :21 when the key is unset or non-numeric.

Gift card timeout — $config['giftCardDateTimeIntervalToDrop'] (PHP DateInterval string, validated to default 'PT180M') controls when the AdvCancelPendingGiftCards cron drops unresolved pending XPay gift card orders (application/config/app.php:574).

Client Extension Points ​

The xpay case is handled inside the switch blocks of Adv_checkout::run() and Adv_checkout::get_response(). Client repos that override application/core/Front_c.php or create subclasses of Adv_checkout can:

  • Override processXPayPaymentResult() (marked protected) to add custom post-payment hooks (Adv_checkout.php:4262).
  • Override logXPayTransaction() (marked protected) to route audit rows to a different table or logging backend (Adv_checkout.php:4332).
  • Override AdvGiftCardPage::xpayWebhookAction() (marked public static) or replace the gift card controller entirely, since the state machine is a pure static helper.
  • Inject a custom \GuzzleHttp\Client into XPay to wrap HTTP calls with tenancy-level configuration (proxy, timeout, etc.).

Business Rules ​

  1. The Nexi XPay Greece HPP model transfers 3-D Secure and card-number responsibility to Nexi. The merchant never sees raw card data.
  2. Currency is hard-coded to 'EUR' in the regular checkout path (Adv_checkout.php:4012). The gift card path uses $this->currentCurrency->code (AdvGiftCardPage.php:1586).
  3. Amount must be expressed in integer cents. XPay::formatAmount() converts via (int)round($amount * 100) to avoid floating-point drift (XPay.php:437-442).
  4. The platform's only documented webhook-authenticity mechanism is the securityToken echo-back. There is no HMAC. verifyNotificationSecurityToken() is fail-closed: rejects when either the inbound token or the stored token is missing or empty (XPay.php:289-305).
  5. REFUNDED notifications are explicitly ignored on both webhook handlers — they log and return without touching order state (Adv_checkout.php:4086-4092, AdvGiftCardPage.php:1698).
  6. [RESOLVED — #583, commit f89660a84] acceptGiftCard() is idempotent: the model claims the order with a single conditional UPDATE ... WHERE id = ? AND gift_card_status IN (...) before any coupon row is issued, and rolls back and returns false if zero rows were affected (ecommercen/gift_cards/models/AdvGiftCardOrdersModel.php:88-106). The same UPDATE also clears canceled_at on a Canceled → Completed accept (:97) — required because applyStatusFilter() resolves Completed as completed_at IS NOT NULL AND canceled_at IS NULL; without the clear, the order would vanish from the admin Completed filter. Duplicate-coupon safety now lives in this claim-before-issue model UPDATE, not in the xpayWebhookAction() state machine — per the code's own docblock (AdvGiftCardPage.php:1746-1751), the retained (Completed, PAID) → 'noop' mapping (AdvGiftCardPage.php:1763-1778) now exists to select which outcome the callback takes, not to make the write safe. Scope: #583 fixed this defect for all gift-card payways; XPay and Piraeus were the only two that previously guarded against it, and only at the caller — the state-machine guard documented here is now redundant-but-retained alongside the model-level guard.
  7. Cross-flow token collision is prevented by the flow discriminator column on xpay_logging. The idx_token_lookup covering index ensures the discriminated lookup is efficient (migration:23-31).
  8. 'xpay' is registered in getGiftCardPayWays() (ecommercen/helpers/eshop_helper.php:352-373, return array :360-371, 'xpay' at :369) and in the gift-card Vue payWayInstallments map with an empty array (AdvGiftCardPage.php:1128), matching the iris / alpha / ethniki / vivawallet pattern for payways that carry no installments.

Known Issues & Security Gaps ​

  1. Duplicate writes to xpay_logging on HPP creation. XPay::createHostedPaymentOrder() writes REQUEST and RESPONSE rows via logToDatabase() (XPay.php:130,144). The caller Adv_checkout::xpay() then writes a second REQUEST row (or REQUEST_FAILED) via logXPayTransaction() (Adv_checkout.php:4022 for REQUEST_FAILED, :4029 for REQUEST). A single HPP creation thus produces two REQUEST rows with different schemas (the gateway-level row includes flow, transaction_id, and full payload in request_data; the controller-level row lacks flow and stores the response envelope instead). This makes forensic queries on xpay_logging ambiguous for the HPP-creation event.

  2. logXPayTransaction() never writes the flow column. The controller-level helper (Adv_checkout.php:4332-4353) builds $logData without a flow key, so the column receives its MySQL default. The flow column is VARCHAR(20) NOT NULL with no explicit default (migration :14), so strict-mode-OFF behavior writes an empty string '' (not NULL). All rows written by CALLBACK, PROCESSED, STATUS_CHECK, and REQUEST_FAILED events have flow = '' (empty string). The idx_token_lookup index and the getStoredSecurityToken() query filter on flow, meaning these controller-level rows cannot serve as token sources and do not interfere with token lookup, but the schema contract is violated for audit purposes.

  3. handlePendingXpayOrders() stamps different meta_data per branch. The PAID branch writes meta_data => __METHOD__ (AdvCancelIncompleteOrders.php:321); the cancel branch goes through cancelOrder() -> set_status(..., 'order_debris') (:316-317, :190), which writes model:set_status:CANCELED:order_debris (Adv_order_model.php:1807-1810). Both branches are stamped, but with different shapes (handlePendingXpayOrders() is :282-308). The xpay_logging table provides a parallel audit trail.

  4. xPayCancel() does not guard against a missing paymentid query parameter. The guard at the top of xPayCancel() checks !$orderSerial || !$orderData || !$paymentId and calls inactive_payment() (Adv_checkout.php:4222-4225). However, Nexi's cancellation redirect may not include a paymentid parameter in all edge cases (browser back-button, session expiry). A customer returning without paymentid lands on inactive_payment() rather than a graceful "payment cancelled" page, with no order state update.

  5. xPaySuccess() makes an extra getOrderStatus() API call on every browser redirect. The HPP flow already delivers a server-to-server webhook before the browser redirect completes. If the webhook arrives first and updates the order to PAID, the getOrderStatus() call in xPaySuccess() is redundant (Adv_checkout.php:4139). In the reverse case (webhook delayed), the status check is necessary. There is no mechanism to short-circuit when the order is already PAID from the webhook, so every return-URL visit incurs an outbound API call.

  6. handlePendingXpayOrders() maps the status before it checks for a null answer (cosmetic). At AdvCancelIncompleteOrders.php:314 the status map reads $xpayOrderStatus['operationResult'] ?? '' before the null guard at :316. ?? on a null array is safe in PHP 8 (it yields ''), so this is not an error: a null answer maps to '', then to UNKNOWN, and the order is cancelled at :316-317. Only the ordering is untidy (ecommercen/job/libraries/AdvCancelIncompleteOrders.php:313-319).

  7. Regular checkout xPayHook() does not set an explicit 200 for the Nexi webhook. xPayHook() sets explicit codes for the error paths (400 at :4011 and :4024, 401 at :4033, 404 at :4042) but not for success, which ends at :4084 (the REFUNDED and no-update returns set none either). CodeIgniter's default response is 200, so this is not a runtime bug, but the lack of an explicit set_status_header(200) is inconsistent with the error paths and could cause a silent issue if the framework default changes. (Adv_checkout.php:4040-4120)

  8. Incomplete test coverage for the controller-layer and cron XPay code paths. tests/Unit/PaymentGateways/NexiXPay/XPayTest.php covers the standalone XPay class (58 tests — 45 methods + 13 provider rows). tests/Unit/Jobs/AdvCancelIncompleteOrdersTest.php covers handlePendingXpayOrders() with 4 dedicated test methods plus xPayExpirationSeconds_* variants at :397-452. tests/Legacy/GiftCards/AdvGiftCardPageTest.php covers the xpayWebhookAction() state machine (3 XPay tests at :57, :70 and :94, with the provider at :28), plus 12 Piraeus and installment tests and 2 mail-rule tests (17 test methods in the file). Remaining untested: the regular checkout controller methods xpay(), xPayHook(), xPayCancel(), processXPayPaymentResult(), and the gift card xpayFormData(), xPayHook(), xPaySuccess(), xPayCancel(). The gift card cron helper AdvCancelPendingGiftCards::cancelPendingXpayOrders() is also untested. The 614-line, 13-test tests/Legacy/GiftCards/AdvGiftCardOrdersModelTest.php covers the model-level accept guard (acceptGiftCard() / acceptGiftCardFrom()) that this cron path depends on, and the Pending-only cancelGiftCard() and revokeGiftCard() (#957), though cancelPendingXpayOrders() itself remains uncovered. tests/Legacy/GiftCards/AdvGiftCardReturnUrlTest.php covers the gift-card return URLs against the real model (#957), and the xPay arm of tests/Legacy/Checkout/AdvCheckoutSuccessPageOwnershipTest.php covers the regular-checkout success page (#962); xPayHook() and xPayCancel() still have no controller test.

  9. Stale comments reference a non-existent method. src/Domains/Checkout/Payment/Adapters/XPayAdapter.php:38 and :92 both reference Adv_checkout::_xpay() (with leading underscore), a method that does not exist. The actual method is xpay() (no underscore) at ecommercen/checkout/controllers/Adv_checkout.php:3957 (post-#734 offset).

  10. Width mismatch for transaction IDs across tables. AdvGiftCardPage::xpayFormData() stores the Nexi-returned orderId into gift_card_orders.tran_ticket varchar(32) (AdvGiftCardPage.php:1601; DDL at database/initial/initial.sql:609), while xpay_logging.transaction_id sizes it at varchar(100) (migration :14). With strict mode off, an over-32-char Nexi ID is silently truncated on write to gift_card_orders, diverging from what was logged.

  11. xPayCancel() cancels a PENDING order on an unverified request (open, tracked as Advisable-com/ecommercen#849). GET checkout/get_response/xpay/cancel/{serial}?paymentid=<anything> (Adv_checkout.php:2312 -> xpayResponse() :4362-4369) reaches xPayCancel() (:4215-4252), which checks only that a paymentid query value is present (:4222-4225), overwrites tran_ticket with it (:4227-4228) and cancels the order whatever its payway, with no gateway check (:4231-4239: cancelOrder(... 'get_response:xpay' ...) + afterOrderCancelHooks()). Contrast xPaySuccess(), which requires payway === 'xpay' (:4133), and the ApcoPay and Piraeus cancel arms that #958 closed. Anyone holding an order serial can cancel another customer's PENDING order, which returns its stock, coupon and points. Row (d) of #849 names this route, and docs/decisions/962-success-page-ownership.md lists xPayCancel() as out of scope for #962 and #958. The gift-card xPayCancel() is not affected (AdvGiftCardPage.php:1638-1649; payway-scoped, Pending-only cancel, see Gift Card Checkout — Return URLs).

Tests ​

tests/Unit/PaymentGateways/NexiXPay/XPayTest.php — 58 tests ​

Runs in isolated processes (#[RunTestsInSeparateProcesses], #[PreserveGlobalState(false)]) because the XPay constructor reads config_item('ISO639-2') and config_item('language_abbr') which require a CI3 boot (XPayTest.php:40-41).

Coverage groups:

GroupDescription
ConstructorSandbox/production URL selection, IS_PRODUCTION truthy-string coercion, default-empty API key (XPayTest.php:83-140)
generateCorrelationIdUUID v4 validity and uniqueness across 10 consecutive calls (XPayTest.php:141-166)
mapOperationResultToStatusData-provider across 11 mapped values plus 2 UNKNOWN-fallthrough cases (13 data-provider rows at :167-196)
parsePaymentNotificationHappy path (all fields), three InvalidArgumentException paths, optional-field nullability, rawNotification preservation, status map threading (XPayTest.php:197-372)
verifyNotificationSecurityToken12 tests: match, mismatch, missing token, empty token, non-string token, no stored row, empty response_data, missing securityToken key in stored row, DB exception, query-shape regression including flow filter and gift-card flow isolation (XPayTest.php:373-559)
HTTP-mocked createHostedPaymentOrderHappy path, missing hostedPage, ClientException, ServerException, ConnectException, endpoint assertion, cents conversion, header shape, optional customer data present/absent, language resolution from ISO 639-2 map (11 tests at XPayTest.php:594-785)
HTTP-mocked getOrderStatusHappy path with multiple operations (latest = index 0), empty operations, correct endpoint, ClientException, ServerException (XPayTest.php:786-870)
API key redactionVerifies ***REDACTED*** appears and the raw key never appears in log output via a Monolog\TestHandler + DI container swap (XPayTest.php:871-914)

tests/Legacy/GiftCards/AdvGiftCardPageTest.php — 17 tests ​

Total 17 #[Test] methods covering Piraeus and installments (12 tests), XPay (3 tests) and the mail rule (2 tests).

GroupTestsDescription
Piraeus integration12piraeusSuccessAction() / piraeusFailAction() state machine, HashKey checks, installments and cardholder-name tests (AdvGiftCardPageTest.php:121-380)
XPay integration3xpayWebhookAction() state machine and decision matrix (AdvGiftCardPageTest.php:28-114)
Mail rule2the_mail_rule_* tests (AdvGiftCardPageTest.php:401, :419)

XPay coverage (3 tests):

TestDescription
Data-driven decision matrix10 (GiftCardStatus, xpayStatus) pairs verifying expected action string
Exhaustive 3×6 matrix walkAsserts only 'accept', 'cancel', 'noop' ever escape the function
Regression guardVerifies 'accept' is never returned outside the (Pending, PAID) path