first(); if ( ! $voucher ) { wp_redirect( '/' ); exit; } if ( $this->isAwaitingPayment( $voucher ) && alexr_gift_cards_enabled( $voucher->restaurant_id ) ) { if ( $this->processGatewayReturn( $voucher ) ) { // Post/Redirect/Get: drop the token + gateway params from the URL so a // reload never re-processes them and they are not left in the history. wp_redirect( alexr_view_voucher_url( $voucher->uuid ) ); // our own URL, not user input exit; } $this->refreshFromGateway( $voucher ); } ob_start(); $this->renderConfirmation( $voucher ); die( ob_get_clean() ); } /** * Server-to-server notification for a voucher (PRO routes it here when the * `booking` uuid starts with 'gv'). Redsys posts the signed response params. */ public function gateway_notification( $gateway_param, $uuid ) { $voucher = \Alexr\Models\Voucher::where( 'uuid', sanitize_text_field( $uuid ) )->first(); if ( ! $voucher || ! $this->isAwaitingPayment( $voucher ) ) { return; } if ( ! alexr_gift_cards_enabled( $voucher->restaurant_id ) ) { return; } if ( $gateway_param === 'alexr_gateway_redsys' ) { $this->processRedsysSigned( $voucher, $_POST ); } } // ── Gateway return (the buyer comes back from the gateway) ────────────────── /** * Process the gateway return present in the query, if any. Returns true when * the request WAS a gateway return (handled or not), so the caller redirects * to the clean voucher URL. */ protected function processGatewayReturn( $voucher ) { if ( isset( $_GET['payment_intent'] ) ) { $payment = \Alexr\Models\Payment::where( 'stripe_payment_intent_id', sanitize_text_field( $_GET['payment_intent'] ) ) ->where( 'voucher_id', $voucher->id ) ->where( 'payment_type', 'stripe' ) ->first(); if ( $payment ) { $this->verifyStripe( $voucher, $payment ); } return true; } if ( isset( $_GET['alexr_gateway_mercadopago'] ) ) { $this->returnMercadopago( $voucher ); return true; } if ( isset( $_GET['alexr_gateway_mollie'] ) ) { $this->verifyLatest( $voucher, 'mollie' ); return true; } if ( isset( $_GET['alexr_gateway_square'] ) ) { $this->verifyLatest( $voucher, 'square' ); return true; } if ( isset( $_GET['alexr_gateway_xendit'] ) ) { $this->returnXendit( $voucher ); return true; } if ( isset( $_GET['alexr_gateway_upayments'] ) ) { $this->returnUpayments( $voucher ); return true; } if ( isset( $_GET['alexr_gateway_redsys'] ) ) { $this->returnRedsys( $voucher ); return true; } return false; } /** * Plain visit to a pending voucher: ask the gateway again about the latest * Payment (throttled). This is what makes the "processing" auto-refresh and * the "I have already paid — check again" link actually re-check. */ protected function refreshFromGateway( $voucher ) { $payment = $this->latestPayment( $voucher ); if ( ! $payment ) { return; } $lock = 'alexr_vchk_' . intval( $voucher->id ); if ( get_transient( $lock ) ) { return; // checked a moment ago: render from the stored state } set_transient( $lock, 1, self::CHECK_THROTTLE ); switch ( $payment->payment_type ) { case 'stripe': $this->verifyStripe( $voucher, $payment ); break; case 'mollie': $this->verifyMollie( $voucher, $payment ); break; case 'square': $this->verifySquare( $voucher, $payment ); break; case 'mercadopago': $this->verifyMercadopago( $voucher, $payment ); break; case 'xendit': $this->verifyXendit( $voucher, $payment ); break; case 'upayments': $this->verifyUpayments( $voucher, $payment ); break; case 'redsys': $this->refreshRedsys( $voucher, $payment ); break; case 'paypal': $this->verifyPaypal( $voucher, $payment ); break; } } protected function verifyLatest( $voucher, $type ) { $payment = $this->voucherPayment( $voucher, $type ); if ( ! $payment ) return; if ( $type === 'mollie' ) $this->verifyMollie( $voucher, $payment ); if ( $type === 'square' ) $this->verifySquare( $voucher, $payment ); } // ── Per-gateway verification (authoritative: reads the gateway API) ──────── /** * Stripe: our intent for this voucher must be `succeeded` with the voucher's * amount + currency (+ metadata uuid). requires_* = not paid yet (retry from * the purchase page), processing = in progress, canceled = failed. */ protected function verifyStripe( $voucher, $payment ) { if ( ! defined( 'ALEXR_PRO_VERSION' ) || ! class_exists( '\Alexr\Payments\GatewayStripe' ) ) return; $intentId = (string) $payment->stripe_payment_intent_id; if ( $intentId === '' ) { $this->saveState( $payment, self::STATE_OPEN ); return; } try { $gateway = new \Alexr\Payments\GatewayStripe( $voucher->restaurant_id ); \Stripe\Stripe::setApiKey( $gateway->getPrivateKey() ); $intent = \Stripe\PaymentIntent::retrieve( $intentId ); } catch ( \Throwable $e ) { return; // keep the stored state } if ( ! $intent ) return; $payment->stripe_payment_status = $intent->status; switch ( $intent->status ) { case 'succeeded': $expectedCurrency = strtolower( $voucher->currency ?: ( $voucher->restaurant ? $voucher->restaurant->currency : '' ) ); $metaUuid = isset( $intent->metadata['voucher_uuid'] ) ? (string) $intent->metadata['voucher_uuid'] : ''; if ( intval( $intent->amount_received ) !== intval( $voucher->initial_amount ) || strtolower( (string) $intent->currency ) !== $expectedCurrency || ( $metaUuid !== '' && $metaUuid !== $voucher->uuid ) ) { $this->storeCallback( $payment, 'verification_failed', array( 'amount_received' => $intent->amount_received, 'currency' => $intent->currency, 'metadata_uuid' => $metaUuid, ) ); $this->saveState( $payment, self::STATE_REVIEW ); return; } $payment->status = \Alexr\Enums\PaymentStatus::SUCCEEDED; $this->saveState( $payment, self::STATE_PAID ); $this->clearToken( $voucher ); $this->issue( $voucher, $payment ); return; case 'processing': $this->saveState( $payment, self::STATE_PROCESSING ); return; case 'canceled': $payment->status = \Alexr\Enums\PaymentStatus::CANCELLED; $this->saveState( $payment, self::STATE_FAILED ); $this->clearToken( $voucher ); $this->cancel( $voucher ); return; default: // requires_payment_method / requires_confirmation / requires_action $this->saveState( $payment, self::STATE_OPEN ); } } /** * Mollie: paid (+ amount/currency) issues; open = not paid yet, the same * Mollie checkout can be resumed; pending/authorized = in progress; * canceled/expired/failed = final. */ protected function verifyMollie( $voucher, $payment ) { if ( ! class_exists( '\Alexr\Payments\GatewayMollie' ) ) return; try { $gateway = new \Alexr\Payments\GatewayMollie( $voucher->restaurant_id ); $gp = $gateway->get_gateway_payment( $voucher, $payment ); } catch ( \Throwable $e ) { return; } if ( ! $gp ) return; $this->storeCallback( $payment, 'payment', json_decode( json_encode( $gp ), true ) ); if ( $gp->isPaid() ) { $paidCents = intval( round( floatval( $gp->amount->value ?? 0 ) * 100 ) ); $paidCurrency = strtoupper( (string) ( $gp->amount->currency ?? '' ) ); if ( $paidCents !== intval( $payment->amount ) || $paidCurrency !== strtoupper( (string) $gateway->currency ) ) { $this->storeCallback( $payment, 'verification_failed', array( 'amount' => $paidCents, 'currency' => $paidCurrency ) ); $this->saveState( $payment, self::STATE_REVIEW ); return; } $payment->status = \Alexr\Enums\PaymentStatus::SUCCEEDED; $this->saveState( $payment, self::STATE_PAID ); $this->clearToken( $voucher ); $this->issue( $voucher, $payment ); } elseif ( $gp->isOpen() ) { // Mollie omits _links.checkout once a method was picked; the checkout // URL from creation keeps working while the payment is open. $created = is_array( $payment->settings ) ? ( $payment->settings['mollie'] ?? array() ) : array(); $checkout = $gp->getCheckoutUrl() ?: ( $created['_links']['checkout']['href'] ?? null ); $this->saveState( $payment, self::STATE_OPEN, $checkout ); } elseif ( $gp->isPending() || $gp->isAuthorized() ) { $this->saveState( $payment, self::STATE_PROCESSING ); } else { // canceled / expired / failed $payment->status = \Alexr\Enums\PaymentStatus::CANCELLED; $this->saveState( $payment, self::STATE_FAILED ); $this->clearToken( $voucher ); $this->cancel( $voucher ); } } /** * Square: read the order behind our payment link. No tender yet = not paid * (the payment link can be reused); otherwise read the payment: COMPLETED * (+ amount/currency) issues, APPROVED/PENDING = in progress, FAILED = card * declined (retry on the link), CANCELED = final. We do NOT use the driver's * get_gateway_payment here: it caches non-final snapshots and breaks on an * order without tenders. */ protected function verifySquare( $voucher, $payment ) { if ( ! class_exists( '\Alexr\Payments\GatewaySquare' ) ) return; $settings = is_array( $payment->settings ) ? $payment->settings : array(); $link = $settings['square']['payment_link'] ?? array(); $orderId = (string) ( $link['order_id'] ?? '' ); $linkUrl = $link['url'] ?? ( $link['long_url'] ?? null ); if ( $orderId === '' ) return; try { $gateway = new \Alexr\Payments\GatewaySquare( $voucher->restaurant_id ); $order = $gateway->get_square_order( $orderId ); if ( empty( $order['success'] ) ) return; $o = $order['data']['order'] ?? array(); if ( strtoupper( (string) ( $o['state'] ?? '' ) ) === 'CANCELED' ) { $payment->status = \Alexr\Enums\PaymentStatus::CANCELLED; $this->saveState( $payment, self::STATE_FAILED ); $this->clearToken( $voucher ); $this->cancel( $voucher ); return; } $tenderPaymentId = (string) ( $o['tenders'][0]['payment_id'] ?? '' ); if ( $tenderPaymentId === '' ) { $this->saveState( $payment, self::STATE_OPEN, $linkUrl ); return; } $res = $gateway->get_square_payment( $tenderPaymentId ); if ( empty( $res['success'] ) ) return; $sp = $res['data']['payment'] ?? array(); } catch ( \Throwable $e ) { return; } // Never leave a non-final snapshot in the driver's cache key. unset( $settings['payment'] ); $settings['square_payment'] = $sp; $payment->settings = $settings; $status = strtoupper( (string) ( $sp['status'] ?? '' ) ); $paidCents = intval( $sp['amount_money']['amount'] ?? -1 ); $paidCurrency = strtoupper( (string) ( $sp['amount_money']['currency'] ?? '' ) ); if ( $status === 'COMPLETED' ) { if ( $paidCents !== intval( $payment->amount ) || $paidCurrency !== strtoupper( (string) $gateway->currency ) ) { $this->storeCallback( $payment, 'verification_failed', array( 'amount' => $paidCents, 'currency' => $paidCurrency ) ); $this->saveState( $payment, self::STATE_REVIEW ); return; } $settings = is_array( $payment->settings ) ? $payment->settings : array(); $settings['payment'] = $sp; // final: safe for the driver's cache $payment->settings = $settings; $payment->status = \Alexr\Enums\PaymentStatus::SUCCEEDED; $this->saveState( $payment, self::STATE_PAID ); $this->clearToken( $voucher ); $this->issue( $voucher, $payment ); } elseif ( $status === 'APPROVED' || $status === 'PENDING' ) { $this->saveState( $payment, self::STATE_PROCESSING ); } elseif ( $status === 'CANCELED' ) { $payment->status = \Alexr\Enums\PaymentStatus::CANCELLED; $this->saveState( $payment, self::STATE_FAILED ); $this->clearToken( $voucher ); $this->cancel( $voucher ); } else { // FAILED (declined): the buyer can try again on the same link. $this->saveState( $payment, self::STATE_OPEN, $linkUrl ); } } /** * PayPal: issued in the ajax handler right after capture; here we re-validate * the stored order with PayPal (capture still PENDING, or a validation that * failed transiently). Same rule: bound to this voucher + exact amount. */ protected function verifyPaypal( $voucher, $payment ) { if ( ! class_exists( '\Alexr\Payments\GatewayPaypal' ) ) return; $settings = is_array( $payment->settings ) ? $payment->settings : array(); $orderId = (string) ( $settings['paypal_order_id'] ?? ( $settings['paypal']['id'] ?? '' ) ); if ( $orderId === '' ) { $this->saveState( $payment, self::STATE_OPEN ); return; } try { $gateway = new \Alexr\Payments\GatewayPaypal( $voucher->restaurant_id ); $order = $gateway->validate( $orderId ); } catch ( \Throwable $e ) { return; } if ( ! is_array( $order ) ) { // Unknown to PayPal. Rows created by the ajax handler always carry a // state; one without it (legacy) is simply not paid. if ( $this->storedState( $payment ) === null ) { $this->saveState( $payment, self::STATE_OPEN ); } return; } $check = alexr_voucher_paypal_order_state( $order, $voucher, intval( $payment->amount ), strtoupper( (string) $payment->currency ) ); $this->storeCallback( $payment, 'validate', $order ); if ( $check['state'] === 'paid' ) { $payment->status = \Alexr\Enums\PaymentStatus::SUCCEEDED; $this->storeCallback( $payment, 'paypal_capture_id', $check['capture_id'] ); $this->saveState( $payment, self::STATE_PAID ); $this->issue( $voucher, $payment ); } else { $this->saveState( $payment, $check['state'] ); } } /** * Mercadopago return: carries the MP payment id. Verified by the API (the * payment's external_reference must be this voucher), so no token is needed * to issue; cancelling from the `failure` param alone still requires it. */ protected function returnMercadopago( $voucher ) { $payment = $this->voucherPayment( $voucher, 'mercadopago' ); if ( ! $payment ) return; $status = sanitize_text_field( $_GET['alexr_gateway_mercadopago'] ?? '' ); $mpId = sanitize_text_field( $_GET['payment_id'] ?? ( $_GET['collection_id'] ?? '' ) ); if ( $mpId !== '' && $mpId !== 'null' ) { $this->verifyMercadopago( $voucher, $payment, $mpId ); return; } if ( $status === 'pending' ) { $this->saveState( $payment, self::STATE_PROCESSING ); } elseif ( $status === 'failure' && $this->tokenMatches( $voucher ) ) { $this->saveState( $payment, self::STATE_OPEN, $this->mercadopagoCheckoutUrl( $payment ) ); } } protected function verifyMercadopago( $voucher, $payment, $mpId = '' ) { if ( ! class_exists( '\Alexr\Payments\GatewayMercadopago' ) ) return; try { $gateway = new \Alexr\Payments\GatewayMercadopago( $voucher->restaurant_id ); // Every MP payment made for this voucher (external_reference = uuid): // the one the return URL names plus any found by searching, so a payment // is found even if the buyer never came back or paid on a 2nd attempt. $candidates = array(); if ( $mpId !== '' ) { $one = $gateway->get_pago( $mpId ); if ( $one ) $candidates[] = json_decode( json_encode( $one ), true ); } foreach ( $gateway->search_payments_by_reference( $voucher->uuid ) as $found ) { $candidates[] = $found; } } catch ( \Throwable $e ) { return; } // Only OUR payments are considered. $candidates = array_values( array_filter( $candidates, function ( $mp ) use ( $voucher ) { return is_array( $mp ) && (string) ( $mp['external_reference'] ?? '' ) === $voucher->uuid; } ) ); if ( ! $candidates ) { if ( ! $this->recentlyProcessing( $payment ) ) { $this->saveState( $payment, self::STATE_OPEN, $this->mercadopagoCheckoutUrl( $payment ) ); } return; } $expectedCurrency = strtoupper( $gateway->currency ?: $voucher->currency ); $byStatus = array(); foreach ( $candidates as $mp ) { $byStatus[ strtolower( (string) ( $mp['status'] ?? '' ) ) ][] = $mp; } if ( ! empty( $byStatus['approved'] ) ) { foreach ( $byStatus['approved'] as $mp ) { $mpAmount = intval( round( floatval( $mp['transaction_amount'] ?? 0 ) * 100 ) ); $mpCurrency = strtoupper( (string) ( $mp['currency_id'] ?? '' ) ); $this->storeCallback( $payment, 'mercadopago_result', array( 'payment_id' => $mp['id'] ?? null, 'status' => 'approved', 'amount' => $mpAmount, 'currency' => $mpCurrency, ) ); if ( $mpAmount === intval( $payment->amount ) && ( $mpCurrency === '' || $mpCurrency === $expectedCurrency ) ) { $payment->status = \Alexr\Enums\PaymentStatus::SUCCEEDED; $this->saveState( $payment, self::STATE_PAID ); $this->clearToken( $voucher ); $this->issue( $voucher, $payment ); return; } } $this->saveState( $payment, self::STATE_REVIEW ); // approved, but not what the voucher costs return; } foreach ( array( 'in_process', 'pending', 'authorized' ) as $st ) { if ( ! empty( $byStatus[ $st ] ) ) { $this->saveState( $payment, self::STATE_PROCESSING ); return; } } // Only rejected / cancelled / refunded attempts. The preference can still be // paid again with another method, so this is "not received", not final. $this->saveState( $payment, self::STATE_OPEN, $this->mercadopagoCheckoutUrl( $payment ) ); } protected function mercadopagoCheckoutUrl( $payment ) { $settings = is_array( $payment->settings ) ? $payment->settings : array(); return $settings['mercadopago']['init_point'] ?? null; } /** * Xendit return: find our Payment by the echoed external_id and verify the * invoice via the API (the webhook may also issue — first one wins). */ protected function returnXendit( $voucher ) { $externalId = sanitize_text_field( $_GET['xendit_external_id'] ?? '' ); $status = strtolower( sanitize_text_field( $_GET['xendit_status'] ?? '' ) ); if ( $externalId === '' ) return; $payment = \Alexr\Models\Payment::where( 'payment_type', 'xendit' ) ->where( 'xendit_external_id', $externalId ) ->where( 'voucher_id', $voucher->id ) ->first(); if ( ! $payment ) return; $this->verifyXendit( $voucher, $payment, in_array( $status, array( 'success', 'paid' ), true ) ); } protected function verifyXendit( $voucher, $payment, $returnedSuccess = false ) { if ( ! class_exists( '\Alexr\Payments\GatewayXendit' ) ) return; try { $gateway = new \Alexr\Payments\GatewayXendit( $voucher->restaurant_id ); $invoice = $gateway->getInvoice( $payment->xendit_invoice_id ); } catch ( \Throwable $e ) { return; } if ( ! $invoice ) return; $status = strtoupper( (string) ( $invoice['status'] ?? '' ) ); $settings = is_array( $payment->settings ) ? $payment->settings : array(); $invoiceUrl = $invoice['invoice_url'] ?? ( $settings['invoice']['invoice_url'] ?? null ); if ( $status === 'PAID' || $status === 'SETTLED' ) { $paidCents = intval( round( floatval( $invoice['paid_amount'] ?? ( $invoice['amount'] ?? 0 ) ) * 100 ) ); if ( $paidCents !== intval( $payment->amount ) ) { $this->storeCallback( $payment, 'verification_failed', array( 'amount' => $paidCents ) ); $this->saveState( $payment, self::STATE_REVIEW ); return; } $payment->status = \Alexr\Enums\PaymentStatus::SUCCEEDED; $payment->xendit_invoice_status = $status; $this->saveState( $payment, self::STATE_PAID ); $this->issue( $voucher, $payment ); } elseif ( $status === 'PENDING' ) { // Just paid but not settled yet → processing; otherwise not paid. $state = ( $returnedSuccess || $this->recentlyProcessing( $payment ) ) ? self::STATE_PROCESSING : self::STATE_OPEN; $this->saveState( $payment, $state, $invoiceUrl ); } else { // EXPIRED / FAILED $payment->status = \Alexr\Enums\PaymentStatus::CANCELLED; $payment->xendit_invoice_status = $status; $this->saveState( $payment, self::STATE_FAILED ); $this->cancel( $voucher ); } } /** * Upayments return: gated by our anti-replay token (carried in the return * URL given to the gateway). With a payment id we verify through the API; * without an API answer we fall back to the token-gated `result` param, as * the booking flow does. */ protected function returnUpayments( $voucher ) { if ( ! $this->tokenMatches( $voucher ) ) return; $orderId = sanitize_text_field( $_GET['upayments_order_id'] ?? '' ); $result = strtoupper( sanitize_text_field( $_GET['result'] ?? '' ) ); $paymentId = sanitize_text_field( $_GET['payment_id'] ?? ( $_GET['paymentId'] ?? '' ) ); $payment = null; if ( $orderId ) { $payment = \Alexr\Models\Payment::where( 'payment_type', 'upayments' ) ->where( 'upayments_order_id', $orderId ) ->where( 'voucher_id', $voucher->id ) ->first(); } if ( ! $payment ) { $payment = $this->voucherPayment( $voucher, 'upayments' ); } if ( ! $payment ) return; if ( $paymentId ) { $payment->upayments_payment_id = $paymentId; } $this->verifyUpayments( $voucher, $payment, $result ); } protected function verifyUpayments( $voucher, $payment, $fallbackResult = '' ) { $apiResult = ''; $paymentId = (string) $payment->upayments_payment_id; if ( $paymentId !== '' && class_exists( '\Alexr\Payments\GatewayUpayments' ) ) { try { $gateway = new \Alexr\Payments\GatewayUpayments( $voucher->restaurant_id ); $response = $gateway->checkPaymentStatus( $paymentId ); // {status, message, data}: the top-level status only says the API call // worked; the transaction result lives inside data. if ( is_array( $response ) && ( $response['status'] ?? null ) === true && isset( $response['data'] ) ) { $apiResult = strtoupper( (string) $this->findKeyDeep( $response['data'], array( 'result', 'payment_status' ) ) ); } $this->storeCallback( $payment, 'check_payment_status', $response ); } catch ( \Throwable $e ) {} } $effective = $apiResult !== '' ? $apiResult : strtoupper( (string) $fallbackResult ); if ( in_array( $effective, array( 'CAPTURED', 'SUCCESS', 'PAID' ), true ) ) { $payment->status = \Alexr\Enums\PaymentStatus::SUCCEEDED; $payment->upayments_status = $effective; $this->saveState( $payment, self::STATE_PAID ); $this->clearToken( $voucher ); $this->issue( $voucher, $payment ); } elseif ( in_array( $effective, array( 'NOT CAPTURED', 'NOT_CAPTURED', 'FAILED', 'FAILURE', 'CANCELED', 'CANCELLED' ), true ) ) { $payment->status = \Alexr\Enums\PaymentStatus::FAILED; $payment->upayments_status = $effective; $this->saveState( $payment, self::STATE_FAILED ); $this->clearToken( $voucher ); $this->cancel( $voucher ); } elseif ( $effective === '' && ! $this->storedState( $payment ) ) { $this->saveState( $payment, self::STATE_OPEN ); } else { $payment->save(); } } /** * Redsys browser return (URLOK/URLKO). Signed params (when Redsys sends them) * are verified and issue right here; a bare `ok` only marks "processing" while * we wait for the signed server notification; `ko` (token-gated) means the * buyer did not pay — they can try again from the purchase page. */ protected function returnRedsys( $voucher ) { if ( isset( $_GET['Ds_MerchantParameters'] ) && isset( $_GET['Ds_Signature'] ) ) { $this->processRedsysSigned( $voucher, $_GET ); return; } if ( ! $this->tokenMatches( $voucher ) ) return; $payment = $this->voucherPayment( $voucher, 'redsys' ); if ( ! $payment ) return; $result = sanitize_text_field( $_GET['alexr_gateway_redsys'] ?? '' ); if ( $result === 'ok' ) { $this->saveState( $payment, self::STATE_PROCESSING ); } elseif ( $result === 'ko' ) { $payment->status = \Alexr\Enums\PaymentStatus::CANCELLED; $this->saveState( $payment, self::STATE_OPEN ); } } /** * Redsys has no status API here: only the signed notification can issue. * "processing" (buyer came back with ok) is trusted for PROCESSING_WINDOW; * after that we ask the buyer to contact the restaurant. */ protected function refreshRedsys( $voucher, $payment ) { $state = $this->storedState( $payment ); if ( $state === self::STATE_PROCESSING && ! $this->recentlyProcessing( $payment ) ) { $this->saveState( $payment, self::STATE_REVIEW ); } elseif ( $state === null ) { $this->saveState( $payment, self::STATE_OPEN ); // never came back from Redsys } } /** * Verify a signed Redsys response (redirect params or server notification) * and issue / mark accordingly. Checks signature, authorisation code, amount, * and that the order belongs to the voucher's Redsys payment. */ protected function processRedsysSigned( $voucher, $source ) { if ( ! class_exists( '\Alexr\Payments\GatewayRedsys' ) ) return; $params = isset( $source['Ds_MerchantParameters'] ) && is_string( $source['Ds_MerchantParameters'] ) ? trim( wp_unslash( $source['Ds_MerchantParameters'] ) ) : ''; $signature = isset( $source['Ds_Signature'] ) && is_string( $source['Ds_Signature'] ) ? trim( wp_unslash( $source['Ds_Signature'] ) ) : ''; if ( $params === '' || $signature === '' ) return; $payment = $this->voucherPayment( $voucher, 'redsys' ); if ( ! $payment ) return; try { $gateway = new \Alexr\Payments\GatewayRedsys( $voucher->restaurant_id ); $data = $gateway->verify_response( $params, $signature ); } catch ( \Throwable $e ) { return; } if ( ! $data ) { $this->storeCallback( $payment, 'redsys_invalid_signature', array( 'at' => current_time( 'mysql' ) ) ); $payment->save(); return; } $this->storeCallback( $payment, 'redsys_response', $data ); // The response must be for the order we sent. $settings = is_array( $payment->settings ) ? $payment->settings : array(); $sentOrder = isset( $settings['redsys']['vars']['DS_MERCHANT_ORDER'] ) ? (string) $settings['redsys']['vars']['DS_MERCHANT_ORDER'] : ''; $gotOrder = (string) ( $data['Ds_Order'] ?? '' ); $gotAmount = intval( $data['Ds_Amount'] ?? -1 ); $authorised = \Alexr\Payments\GatewayRedsys::is_response_authorised( $data['Ds_Response'] ?? '' ); if ( $authorised && $gotAmount === intval( $payment->amount ) && ( $sentOrder === '' || $sentOrder === $gotOrder ) ) { $payment->status = \Alexr\Enums\PaymentStatus::SUCCEEDED; $this->saveState( $payment, self::STATE_PAID ); $this->clearToken( $voucher ); $this->issue( $voucher, $payment ); } elseif ( ! $authorised ) { // Denied: that Redsys order is closed; the buyer can buy again. $payment->status = \Alexr\Enums\PaymentStatus::CANCELLED; $this->saveState( $payment, self::STATE_FAILED ); $this->clearToken( $voucher ); $this->cancel( $voucher ); } else { $this->saveState( $payment, self::STATE_REVIEW ); // authorised but amount/order mismatch } } // ── Helpers ───────────────────────────────────────────────────────────────── protected function isPending( $voucher ) { return $voucher->status === \Alexr\Enums\VoucherStatus::PENDING_PAYMENT; } /** * Pending, or cancelled by VoucherHousekeeping as abandoned: a payment the * gateway confirms late must still issue the voucher (markPaid allows it). */ protected function isAwaitingPayment( $voucher ) { if ( $this->isPending( $voucher ) ) { return true; } $settings = is_array( $voucher->settings ) ? $voucher->settings : array(); return $voucher->status === \Alexr\Enums\VoucherStatus::CANCELLED && ! empty( $settings['abandoned_at'] ); } protected function voucherPayment( $voucher, $type ) { return \Alexr\Models\Payment::where( 'voucher_id', $voucher->id ) ->where( 'payment_type', $type ) ->last(); } protected function latestPayment( $voucher ) { return \Alexr\Models\Payment::where( 'voucher_id', $voucher->id )->last(); } /** Persist the normalised gateway state (+ a resumable checkout URL) on the Payment. */ protected function saveState( $payment, $state, $checkoutUrl = null ) { $settings = is_array( $payment->settings ) ? $payment->settings : array(); $previous = $settings['voucher_gateway'] ?? array(); $since = ( ( $previous['state'] ?? null ) === $state && ! empty( $previous['since'] ) ) ? intval( $previous['since'] ) : time(); $settings['voucher_gateway'] = array( 'state' => $state, 'since' => $since, 'checked_at' => time(), 'checkout_url' => $state === self::STATE_OPEN ? ( $checkoutUrl ?: ( $previous['checkout_url'] ?? null ) ) : null, ); $payment->settings = $settings; $payment->save(); } protected function storedState( $payment ) { $settings = is_array( $payment->settings ) ? $payment->settings : array(); return $settings['voucher_gateway']['state'] ?? null; } /** True while a "processing" state is younger than PROCESSING_WINDOW. */ protected function recentlyProcessing( $payment ) { $settings = is_array( $payment->settings ) ? $payment->settings : array(); $vg = $settings['voucher_gateway'] ?? array(); return ( $vg['state'] ?? null ) === self::STATE_PROCESSING && ( time() - intval( $vg['since'] ?? 0 ) ) < self::PROCESSING_WINDOW; } /** First value found for any of $keys in a (nested) array / object. */ protected function findKeyDeep( $data, array $keys ) { if ( is_object( $data ) ) $data = json_decode( json_encode( $data ), true ); if ( ! is_array( $data ) ) return ''; foreach ( $keys as $key ) { if ( isset( $data[ $key ] ) && is_scalar( $data[ $key ] ) ) { return (string) ( is_bool( $data[ $key ] ) ? ( $data[ $key ] ? 'TRUE' : 'FALSE' ) : $data[ $key ] ); } } foreach ( $data as $value ) { if ( is_array( $value ) || is_object( $value ) ) { $found = $this->findKeyDeep( $value, $keys ); if ( $found !== '' ) return $found; } } return ''; } /** * Anti-replay: the return URL carries &token=..., compared (constant-time) * against the token stashed on the voucher when the payment was created. */ protected function tokenMatches( $voucher ) { $token = isset( $_GET['token'] ) ? sanitize_text_field( $_GET['token'] ) : ''; $settings = is_array( $voucher->settings ) ? $voucher->settings : []; $stored = isset( $settings['gateway_token'] ) ? $settings['gateway_token'] : ''; return $token !== '' && $stored !== '' && hash_equals( (string) $stored, (string) $token ); } protected function clearToken( $voucher ) { $settings = is_array( $voucher->settings ) ? $voucher->settings : []; $settings['gateway_token'] = null; $voucher->settings = $settings; $voucher->save(); } protected function cancel( $voucher ) { if ( ! $this->isPending( $voucher ) ) return; // never un-issue an active voucher $voucher->status = \Alexr\Enums\VoucherStatus::CANCELLED; $voucher->save(); } protected function storeCallback( $payment, $key, $value ) { $settings = is_array( $payment->settings ) ? $payment->settings : []; $settings[ $key ] = $value; $payment->settings = $settings; } /** * Mark the voucher paid/active and fire the issued hook (the delivery phase * listens to it to email the buyer / recipient). markPaid() flips the row * atomically, so concurrent returns can never issue twice. */ protected function issue( $voucher, $payment = null ) { $activated = $voucher->markPaid( $payment ); if ( $activated ) { do_action( 'alexr_voucher_issued', $voucher ); } } /** Same-site page the voucher was bought from (fallback: home). */ protected function purchasePageUrl( $voucher ) { $settings = is_array( $voucher->settings ) ? $voucher->settings : array(); $url = (string) ( $settings['source_url'] ?? '' ); $valid = $url !== '' ? wp_validate_redirect( $url, '' ) : ''; return $valid !== '' ? $valid : home_url( '/' ); } // ── Page ──────────────────────────────────────────────────────────────────── /** * Standalone page. Active vouchers show the printable certificate; pending * ones show what the gateway actually says (processing / not received / * under review); cancelled ones explain the voucher was not issued. */ protected function renderConfirmation( $voucher ) { // Translate into the voucher's language (the buyer's, not the site's). // NOTE: __eva() is only an extractor marker — it does NOT translate. $lang = $voucher->language ?: 'en'; $t = function ( $string ) use ( $lang ) { return function_exists( 'alexr_translate_x' ) ? alexr_translate_x( $string, $lang ) : $string; }; $restaurant = $voucher->restaurant; $symbol = \Alexr\Enums\CurrencyType::symbolFor( $voucher->currency ); $isActive = in_array( $voucher->status, array( \Alexr\Enums\VoucherStatus::ACTIVE, \Alexr\Enums\VoucherStatus::REDEEMED ), true ); $isPending = $this->isPending( $voucher ); $isCancelled = $voucher->status === \Alexr\Enums\VoucherStatus::CANCELLED; $amount = $symbol . number_format( 0.01 * intval( $voucher->initial_amount ), 2 ); $settings = is_array( $voucher->settings ) ? $voucher->settings : []; $product_name = $voucher->productLabel( $lang ); // with the persons of a per-person voucher $voucherUrl = alexr_view_voucher_url( $voucher->uuid ); $purchaseUrl = $this->purchasePageUrl( $voucher ); // What the gateway says about a pending voucher. $state = null; $retryUrl = $purchaseUrl; if ( $isPending ) { $payment = $this->latestPayment( $voucher ); if ( ! $payment ) { $state = self::STATE_OPEN; // the payment was never started } else { $ps = is_array( $payment->settings ) ? $payment->settings : array(); $vg = $ps['voucher_gateway'] ?? array(); $state = $vg['state'] ?? self::STATE_PROCESSING; // not checked yet / API error if ( $state === self::STATE_PAID ) { $state = self::STATE_PROCESSING; // paid but issuing raced: re-check } if ( $state === self::STATE_FAILED ) { $state = self::STATE_OPEN; } if ( $state === self::STATE_OPEN && ! empty( $vg['checkout_url'] ) ) { $retryUrl = $vg['checkout_url']; } } } // Fetch the product for its terms (not snapshotted on the voucher). $terms = ''; if ( $isActive && $voucher->product_id ) { $product = \Alexr\Settings\GiftCard::find( $voucher->product_id ); if ( $product ) { $terms = (string) $product->terms; } } $expires = $voucher->expires_at ? date_i18n( get_option( 'date_format' ), strtotime( $voucher->expires_at ) ) : $t( __eva( 'No expiry' ) ); if ( $isActive ) { $title = $t( __eva( 'Your gift voucher is ready!' ) ); } elseif ( $state === self::STATE_PROCESSING ) { $title = $t( __eva( 'Completing your payment…' ) ); } elseif ( $state === self::STATE_OPEN ) { $title = $t( __eva( 'We have not received the payment' ) ); } elseif ( $state === self::STATE_REVIEW ) { $title = $t( __eva( 'We are reviewing your payment' ) ); } elseif ( $isCancelled ) { $title = $t( __eva( 'Payment not completed' ) ); } else { $title = $t( __eva( 'Gift voucher' ) ); } // Processing: re-check every 5 s for a while (each reload asks the gateway). $refreshUrl = ''; if ( $state === self::STATE_PROCESSING ) { $tries = intval( $_GET['r'] ?? 0 ); if ( $tries < self::MAX_REFRESHES ) { $refreshUrl = add_query_arg( array( 'r' => $tries + 1 ), $voucherUrl ); } } ?>