← Back
Editing: class-wc-payments-order-service.php
<?php /** * Class WC_Payments_Order_Service * * @package WooCommerce\Payments */ use WCPay\Constants\Fraud_Meta_Box_Type; use WCPay\Constants\Order_Status; use WCPay\Constants\Intent_Status; use WCPay\Constants\Payment_Method; use WCPay\Constants\Refund_Status; use WCPay\Constants\Refund_Failure_Reason; use WCPay\Exceptions\Order_Not_Found_Exception; use WCPay\Fraud_Prevention\Fraud_Risk_Tools; use WCPay\Fraud_Prevention\Models\Rule; use WCPay\Logger; use WCPay\Core\Server\Request\Get_Intention; use WCPay\Core\Server\Request\Cancel_Intention; use WCPay\Core\Server\Request\Capture_Intention; use WCPay\Internal\Service\Level3Service; use WCPay\Constants\Order_Mode; defined( 'ABSPATH' ) || exit; /** * Class handling order functionality. */ class WC_Payments_Order_Service { const ADD_FEE_BREAKDOWN_TO_ORDER_NOTES = 'wcpay_add_fee_breakdown_to_order_notes'; /** * Meta key used to store intent Id. * * @const string */ const INTENT_ID_META_KEY = '_intent_id'; /** * WC session key holding the payment intent the current session just paid. Written by the gateway * when a payment completes, read on the order confirmation page to recognise the genuine payer * (any WooPayments payment, not only wallets) without trusting query-string params. * * Holds a single intent id, so back-to-back payments in one session keep only the latest: after * paying order B, visiting order A's order-received page no longer matches and falls back to email * verification. Acceptable because the fallback is safe (we ask to verify, never wrongly waive) and * the sequence is rare; a per-order map would be more state to prune for little gain. * * @const string */ const PAID_INTENT_ID_SESSION_KEY = 'wcpay_paid_intent_id'; /** * Key used to store the ID of the WooCommerce session the paid intent ID above was stored in. * * @const string */ const PAID_INTENT_ID_SESSION_OWNER_KEY = 'wcpay_paid_intent_id_session'; /** * Meta key used to store payment method Id. * * @const string */ const PAYMENT_METHOD_ID_META_KEY = '_payment_method_id'; /** * Meta key used to store charge Id. * * @const string */ const CHARGE_ID_META_KEY = '_charge_id'; /** * Meta key used to store intention status. * * @const string */ const INTENTION_STATUS_META_KEY = '_intention_status'; /** * Intent statuses that are terminal: Stripe never transitions an intent back to * `requires_capture` once it reaches one of these, so a cached `_intention_status` * meta of one of these values proves there is no open authorization left to capture, * without needing a live intent lookup. * * @const string[] */ const TERMINAL_INTENT_STATUSES = [ Intent_Status::SUCCEEDED, Intent_Status::CANCELED, ]; /** * Meta key used to store the charge risk level. * * @const string */ const CHARGE_RISK_LEVEL_META_KEY = '_charge_risk_level'; /** * Maximum length of the payment provider's error message in an order note. * * @const int */ private const MAX_PROVIDER_ERROR_LENGTH = 1000; /** * Meta key used to store customer Id. * * @const string */ const CUSTOMER_ID_META_KEY = '_stripe_customer_id'; /** * Meta key holding the Unix time at which another gateway last took the order over from a WooPayments * attempt, whose payment details were removed then. Webhooks compare an intent's creation time against it. * * @const string */ const PAYMENT_DETAILS_REMOVED_META_KEY = '_wcpay_payment_details_removed'; /** * Meta key listing the intents of WooPayments attempts whose payment details were removed because another * gateway took the order over. Webhooks for these intents leave the order alone. * * @const string */ const SUPERSEDED_INTENT_IDS_META_KEY = '_wcpay_superseded_intent_ids'; /** * Meta key used to store WCPay fraud meta box type. * * @const string */ const WCPAY_FRAUD_META_BOX_TYPE_META_KEY = '_wcpay_fraud_meta_box_type'; /** * Meta key used to store WCPay fraud outcome status. * * @const string */ const WCPAY_FRAUD_OUTCOME_STATUS_META_KEY = '_wcpay_fraud_outcome_status'; /** * Meta key used to store the risk filter results that blocked a payment or held it for review, * as a JSON-encoded map of rule key => outcome (e.g. {"avs_verification":"block"}). * * @const string */ const WCPAY_FRAUD_RULESET_RESULTS_META_KEY = '_wcpay_fraud_ruleset_results'; /** * Meta key used to store WCPay intent currency. * * @const string */ const WCPAY_INTENT_CURRENCY_META_KEY = '_wcpay_intent_currency'; /** * Meta key used to store WCPay refund id. * * @const string */ const WCPAY_REFUND_ID_META_KEY = '_wcpay_refund_id'; /** * Meta key used to store WCPay refund transaction id. * * @const string */ const WCPAY_REFUND_TRANSACTION_ID_META_KEY = '_wcpay_refund_transaction_id'; /** * Meta key used to store WCPay refund status. * * @const string */ const WCPAY_REFUND_STATUS_META_KEY = '_wcpay_refund_status'; /** * Meta key used to store WCPay transaction fee. * * @const string */ const WCPAY_TRANSACTION_FEE_META_KEY = '_wcpay_transaction_fee'; /** * Meta key used to store the mode, either 'test', or 'prod' of order. * * @see Order_Mode * * @const string */ const WCPAY_MODE_META_KEY = '_wcpay_mode'; /** * Hook ID suffixes for the WooCommerce order emails that receive a persistent "[Test]" * indicator in their subject and heading when the order was paid in test mode. Covers the * admin notifications (New order, plus Failed/Cancelled order: a test-mode card decline * otherwise produces an admin email indistinguishable from a real failed payment) and the * customer-facing order emails merchants rely on for fulfilment. `customer_invoice` and * `customer_invoice_paid` are both listed because WC_Email_Customer_Invoice fires the `_paid` * filter variant for processing/completed orders (the usual case for an invoice resend) and * the plain variant otherwise. * * @const string[] */ const TEST_MODE_INDICATOR_EMAIL_IDS = [ 'new_order', 'failed_order', 'cancelled_order', 'customer_processing_order', 'customer_completed_order', 'customer_on_hold_order', 'customer_invoice', 'customer_invoice_paid', ]; /** * Option key holding a one-way flag indicating the store has had at least one live WooPayments sale. * * @const string */ const HAS_LIVE_SALE_OPTION = 'wcpay_has_live_sale'; /** * Meta key used to store payment transaction Id. * * @const string */ const WCPAY_PAYMENT_TRANSACTION_ID_META_KEY = '_wcpay_payment_transaction_id'; /** * Meta key used to store the Multibanco entity. * * @const string */ const WCPAY_MULTIBANCO_ENTITY_META_KEY = '_wcpay_multibanco_entity'; /** * Meta key used to store the Multibanco reference. * * @const string */ const WCPAY_MULTIBANCO_REFERENCE_META_KEY = '_wcpay_multibanco_reference'; /** * Meta key used to store the Multibanco expiry. * * @const string */ const WCPAY_MULTIBANCO_EXPIRY_META_KEY = '_wcpay_multibanco_expiry'; /** * Meta key used to store the Multibanco URL. * * @const string */ const WCPAY_MULTIBANCO_URL_META_KEY = '_wcpay_multibanco_url'; /** * Meta key for cached payment method details. * * @const string */ const PAYMENT_METHOD_DETAILS_META_KEY = '_wcpay_payment_method_details'; /** * Meta key used to store the IPP channel from Stripe intent metadata. * * @const string */ const IPP_CHANNEL_META_KEY = '_wcpay_ipp_channel'; /** * Meta key holding the IDs of the disputes recorded against this order that have * not closed yet. The list is order-wide; it is not keyed or scoped per charge. * * A single charge can carry several disputes at once (AmEx and Klarna raise one * per separately shipped item), and nothing in the close webhook says whether the * others are still running, so the plugin has to keep its own tally. * * @const string */ const WCPAY_OPEN_DISPUTE_IDS_META_KEY = '_wcpay_open_dispute_ids'; /** * Meta key used to store the latest early fraud warning received for the order's charge. * * @const string */ const WCPAY_EARLY_FRAUD_WARNING_META_KEY = '_wcpay_early_fraud_warning'; /** * Meta key indexing orders whose stored early fraud warning is still actionable. * * Present only while actionable, so the bounded warning query can filter on it: the * warning itself is a serialized array MySQL cannot read, and its row is never removed * (the order screen keeps showing resolved warnings), so without this key resolved rows * would hold window slots forever and hide older still-actionable ones. * * The value is the warning's Unix `created` timestamp, so `wc_get_orders` can sort by * when the warning arrived rather than when the order was placed. * * @const string */ const WCPAY_EARLY_FRAUD_WARNING_ACTIONABLE_META_KEY = '_wcpay_early_fraud_warning_actionable'; /** * Client for making requests to the WooCommerce Payments API * * @var WC_Payments_API_Client */ protected $api_client; /** * Earlier WooPayments attempts whose removal finishes once the request ends, by order ID: the removed * intent, and whether it is still waiting for 3DS and must be cancelled. * * @var array<int, array{intent_id: string, cancel: bool}> */ private $earlier_attempts_to_finish = []; /** * WC_Payments_Order_Service constructor. * * @param WC_Payments_API_Client $api_client - WooCommerce Payments API client. */ public function __construct( WC_Payments_API_Client $api_client ) { $this->api_client = $api_client; } /** * Registers hooks. * * @return void */ public function init_hooks(): void { add_action( 'woocommerce_order_status_processing', [ $this, 'maybe_record_first_live_sale' ] ); add_action( 'woocommerce_order_status_completed', [ $this, 'maybe_record_first_live_sale' ] ); add_action( 'woocommerce_order_refunded', [ $this, 'maybe_clear_early_fraud_warning_caches' ] ); // Keep these below 50: WooCommerce Subscriptions copies the order's meta into switches and new subscriptions at 50 and 100. add_action( 'woocommerce_checkout_order_processed', [ $this, 'maybe_remove_payment_details_for_other_gateway' ] ); add_action( 'woocommerce_store_api_checkout_order_processed', [ $this, 'maybe_remove_payment_details_for_other_gateway' ] ); // Flag test-mode orders in the emails merchants and shoppers rely on, so an accidental // test-mode sale is noticed before fulfilment. The mode is read from the order meta at // send time (see maybe_add_test_mode_to_email_subject), so the marker reflects how the // order was paid even if the store later switches modes or the email is resent. These // are runtime filters, so the marker only shows while WooPayments is active. foreach ( self::TEST_MODE_INDICATOR_EMAIL_IDS as $email_id ) { add_filter( "woocommerce_email_subject_{$email_id}", [ $this, 'maybe_add_test_mode_to_email_subject' ], 10, 2 ); add_filter( "woocommerce_email_heading_{$email_id}", [ $this, 'maybe_add_test_mode_to_email_heading' ], 10, 2 ); } } /** * Sets the one-way `HAS_LIVE_SALE_OPTION` flag the first time a live WooPayments * order reaches a successful status. Subsequent invocations short-circuit on the * autoloaded option read so they cost nothing for the lifetime of the store. * * @param int $order_id Order ID from the woocommerce_order_status_* hook. * @return void */ public function maybe_record_first_live_sale( $order_id ): void { if ( get_option( self::HAS_LIVE_SALE_OPTION ) ) { return; } $order = wc_get_order( $order_id ); if ( ! $order ) { return; } if ( Order_Mode::PRODUCTION === $order->get_meta( self::WCPAY_MODE_META_KEY ) ) { update_option( self::HAS_LIVE_SALE_OPTION, '1', true ); if ( class_exists( 'WC_Tracks' ) ) { WC_Tracks::record_event( 'wcpay_first_live_sale' ); } } } /** * Prepends a persistent test-mode marker to an order email subject when the order was paid * in test mode. Hooked to `woocommerce_email_subject_{$email_id}` for the order emails in * self::TEST_MODE_INDICATOR_EMAIL_IDS. * * @param string $subject The email subject. * @param mixed $order The object the email concerns; a WC_Order for order emails (other types are ignored). * * @return string The subject, prefixed with a test marker for test-mode orders. */ public function maybe_add_test_mode_to_email_subject( $subject, $order ): string { if ( ! $order instanceof WC_Order || ! $this->is_order_in_test_mode( $order ) ) { return $subject; } return $this->prepend_test_mode_email_marker( $subject ); } /** * Prepends a persistent test-mode marker to an order email heading when the order was paid * in test mode. Hooked to `woocommerce_email_heading_{$email_id}` for the order emails in * self::TEST_MODE_INDICATOR_EMAIL_IDS. * * @param string $heading The email heading. * @param mixed $order The object the email concerns; a WC_Order for order emails (other types are ignored). * * @return string The heading, prefixed with a test marker for test-mode orders. */ public function maybe_add_test_mode_to_email_heading( $heading, $order ): string { if ( ! $order instanceof WC_Order || ! $this->is_order_in_test_mode( $order ) ) { return $heading; } return $this->prepend_test_mode_email_marker( $heading ); } /** * Returns whether the store has had at least one live (production) WooPayments sale. * * Reads the one-way `HAS_LIVE_SALE_OPTION` flag; falls back to a `wc_get_orders` lookup * for `_wcpay_mode = production` orders and writes the flag on hit. The mode filter is * required (it excludes completed test-mode orders), so live orders created before that * meta existed aren't detected. * * @deprecated 11.3.0 Its only callers were the retired activation notice and reminder emails. * * @return bool */ public function has_live_sale(): bool { if ( get_option( self::HAS_LIVE_SALE_OPTION ) ) { return true; } $orders = wc_get_orders( [ 'payment_method' => 'woocommerce_payments', 'limit' => 1, 'return' => 'ids', 'status' => [ 'wc-completed', 'wc-processing' ], // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_key' => self::WCPAY_MODE_META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value 'meta_value' => Order_Mode::PRODUCTION, ] ); if ( ! empty( $orders ) ) { update_option( self::HAS_LIVE_SALE_OPTION, '1', true ); return true; } return false; } /** * Parse the payment intent data and add any necessary notes to the order and update the order status accordingly. * * @param WC_Order $order The order to update. * @param WC_Payments_API_Abstract_Intention $intent Setup or payment intent to pull the data from. */ public function update_order_status_from_intent( $order, $intent ) { // Only orders are completed from an intent, never a subscription. The webhook, the duplicate payment // check and the redirect handler all pass through here. if ( function_exists( 'wcs_is_subscription' ) && wcs_is_subscription( $order ) ) { return; } $intent_data = $this->get_intent_data( $intent ); if ( ! isset( $intent_data['intent_id'] ) || ! $this->order_prepared_for_processing( $order, $intent_data['intent_id'] ) ) { return; } switch ( $intent_data['intent_status'] ) { case Intent_Status::CANCELED: $this->mark_payment_capture_cancelled( $order, $intent_data ); break; case Intent_Status::SUCCEEDED: if ( Intent_Status::REQUIRES_CAPTURE === $this->get_intention_status_for_order( $order ) ) { $this->mark_payment_capture_completed( $order, $intent ); } elseif ( $intent instanceof WC_Payments_API_Payment_Intention && ! $this->intent_amount_matches_order( $intent, $order ) ) { $this->mark_payment_held_for_amount_mismatch( $order, $intent, $intent_data ); } else { $this->mark_payment_completed( $order, $intent_data ); } break; case Intent_Status::PROCESSING: case Intent_Status::REQUIRES_CAPTURE: if ( Rule::FRAUD_OUTCOME_REVIEW === $intent_data['fraud_outcome'] ) { $this->mark_order_held_for_review_for_fraud( $order, $intent_data ); } else { $this->mark_payment_authorized( $order, $intent_data ); } break; case Intent_Status::REQUIRES_ACTION: case Intent_Status::REQUIRES_PAYMENT_METHOD: if ( ! empty( $intent_data['error'] ) ) { $this->unlock_order_payment( $order ); $this->mark_payment_failed( $order, $intent_data['intent_id'], $intent_data['intent_status'], $intent_data['charge_id'], $intent_data['error']['message'] ); } elseif ( in_array( $intent->get_payment_method_type(), Payment_Method::OFFLINE_PAYMENT_METHODS, true ) ) { $this->mark_payment_on_hold( $order, $intent_data ); } else { $this->mark_payment_started( $order, $intent_data ); } break; default: Logger::error( 'Uncaught payment intent status of ' . $intent_data['intent_status'] . ' passed for order id: ' . $order->get_id() ); break; } $this->complete_order_processing( $order ); } /** * Handles the order state when a payment is captured successfully. * Unlike `update_order_status_from_intent`, this method does not check the current order status or skip processing * if the order is already in the "processing" state. This ensures the order status is updated correctly upon a * successful capture, preventing issues where the capture is not reflected in the order details or transaction screens * due to the order status being in the processing state. * * @param WC_Order $order The order to update. * @param WC_Payments_API_Abstract_Intention $intent The intent object containing payment or setup data. */ public function process_captured_payment( $order, $intent ) { $this->mark_payment_capture_completed( $order, $intent ); $this->complete_order_processing( $order, $intent->get_status() ); } /** * Updates an order to failed status, while adding a note with a link to the transaction. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $intent_status The status of the intent related to this order. * @param string $charge_id The charge ID related to the intent/order. * @param string $message Optional message to add to the failed note. * * @return void */ public function mark_payment_failed( $order, $intent_id, $intent_status, $charge_id, $message = '' ) { if ( ! $this->order_prepared_for_processing( $order, $intent_id ) ) { return; } $note = $this->get_payment_failure_note( $order, $intent_id, $charge_id, $message ); if ( $this->order_note_exists( $order, $note ) || $order->has_status( [ Order_Status::FAILED ] ) ) { $this->complete_order_processing( $order ); return; } $this->update_order_status( $order, Order_Status::FAILED ); $order->add_order_note( $note ); $this->complete_order_processing( $order, $intent_status ); } /** * Updates an order to failed status after the payment provider declined the payment, * adding a note with the provider's decline details. * * The `payment_intent.payment_failed` webhook adds the same note for BNPL payment methods * without changing the order status, so an existing note does not stop the status change. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string|null $intent_status The status of the intent related to this order. * @param string|null $charge_id The charge ID related to the intent/order. * @param array $error The payment provider's error. * * @return void */ public function mark_payment_declined( $order, $intent_id, $intent_status, $charge_id, array $error ): void { if ( ! $this->order_prepared_for_processing( $order, $intent_id ) ) { return; } // Another request for the same intent (e.g. a reloaded return page) may have failed the order // after this one loaded it. The existing note can't stop the status change here, so check the // stored status to avoid failing the order and sending the failed order emails twice. if ( $order->has_status( [ Order_Status::FAILED ] ) || $this->get_stored_order( $order )->has_status( [ Order_Status::FAILED ] ) ) { $this->complete_order_processing( $order ); return; } $note = $this->get_payment_failure_note( $order, $intent_id, $charge_id, $this->get_provider_decline_message( $error ) ); $this->update_order_status( $order, Order_Status::FAILED ); if ( ! $this->order_note_exists( $order, $note ) ) { $order->add_order_note( $note ); } $this->complete_order_processing( $order, $intent_status ); } /** * Get content for the payment failure order note. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * @param string $message Optional message to add to the note. * * @return string Note content. */ public function get_payment_failure_note( $order, $intent_id, $charge_id, $message = '' ) { return $this->generate_payment_failure_note( $intent_id, $charge_id, $message, $this->get_order_amount( $order ) ); } /** * Gets the payment provider's decline details for a failure note. * * @param array $error The payment provider's error. * * @return string The formatted decline message. */ public function get_provider_decline_message( array $error ): string { $decline_code = $error['decline_code'] ?? ''; $provider_error = (string) ( $error['message'] ?? '' ); if ( '' === $provider_error ) { $provider_error = (string) ( $error['code'] ?? '' ); } if ( '' === $provider_error ) { $provider_error = __( "We're not able to process this payment. Please try again later.", 'woocommerce-payments' ); } // Keep the note well within the comment size limit, otherwise it is not saved. if ( mb_strlen( $provider_error ) > self::MAX_PROVIDER_ERROR_LENGTH ) { $provider_error = mb_substr( $provider_error, 0, self::MAX_PROVIDER_ERROR_LENGTH ) . '…'; } if ( ! empty( $decline_code ) ) { $message = sprintf( /* translators: %1$s: the payment provider's error message, %2$s: the decline code returned by the payment provider. */ __( 'With the following message: <code>%1$s</code>. Decline code: <code>%2$s</code>.', 'woocommerce-payments' ), esc_html( $provider_error ), esc_html( $decline_code ) ); } else { // translators: %s Stripe error message. $message = sprintf( __( 'With the following message: <code>%s</code>', 'woocommerce-payments' ), esc_html( $provider_error ) ); } if ( ! empty( $error['doc_url'] ) ) { $message .= ' ' . sprintf( /* translators: %1$s: a URL with more information about the declined payment. */ __( '<a href="%1$s" target="_blank" rel="noopener noreferrer">More information</a>', 'woocommerce-payments' ), esc_url( $error['doc_url'] ) ); } return $message; } /** * Leaves order in current status (should be on-hold), adds a note with a link to the transaction. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string|null $intent_status The status of the intent related to this order. * @param string $charge_id The charge ID related to the intent/order. * @param string $message Optional message to add to the note. * * @return void */ public function mark_payment_capture_failed( $order, $intent_id, $intent_status, $charge_id, $message = '' ) { if ( ! $this->order_prepared_for_processing( $order, $intent_id ) ) { return; } $note = $this->generate_capture_failed_note( $order, $intent_id, $charge_id, $message ); if ( $this->order_note_exists( $order, $note ) ) { $this->complete_order_processing( $order ); return; } if ( Rule::FRAUD_OUTCOME_REVIEW === $this->get_fraud_outcome_status_for_order( $order ) ) { $this->set_fraud_meta_box_type_for_order( $order, Fraud_Meta_Box_Type::REVIEW_FAILED ); } $order->add_order_note( $note ); $this->complete_order_processing( $order, $intent_status ); } /** * Update an order to failed status, and add note with a link to the transaction. * * Context - when a Payment Intent expires. Changing the status to failed will enable the buyer to re-attempt payment. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $intent_status The status of the intent related to this order. * @param string $charge_id The charge ID related to the intent/order. * * @return void */ public function mark_payment_capture_expired( $order, $intent_id, $intent_status, $charge_id ) { if ( ! $this->order_prepared_for_processing( $order, $intent_id ) ) { return; } $note = $this->generate_capture_expired_note( $intent_id, $charge_id ); if ( $this->order_note_exists( $order, $note ) ) { $this->complete_order_processing( $order ); return; } if ( Rule::FRAUD_OUTCOME_REVIEW === $this->get_fraud_outcome_status_for_order( $order ) ) { $this->set_fraud_meta_box_type_for_order( $order, Fraud_Meta_Box_Type::REVIEW_EXPIRED ); } $this->update_order_status( $order, Order_Status::FAILED ); $order->add_order_note( $note ); $this->complete_order_processing( $order, $intent_status ); } /** * Leaves order status as Pending, adds fraud meta data, and adds the fraud blocked note. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $intent_status The status of the intent related to this order. * @param array $ruleset_results The risk filter results that blocked the payment, as a map of rule key => outcome. * * @return void */ public function mark_order_blocked_for_fraud( $order, $intent_id, $intent_status, array $ruleset_results = [] ) { if ( ! $this->order_prepared_for_processing( $order, $intent_id ) ) { return; } $note = $this->generate_fraud_blocked_note( $order, $intent_id, $ruleset_results ); if ( $this->order_note_exists( $order, $note ) ) { $this->complete_order_processing( $order ); return; } if ( [] !== $ruleset_results ) { $this->set_fraud_ruleset_results_for_order( $order, $ruleset_results ); } $this->set_fraud_outcome_status_for_order( $order, Rule::FRAUD_OUTCOME_BLOCK ); $this->set_fraud_meta_box_type_for_order( $order, Fraud_Meta_Box_Type::BLOCK ); $order->add_order_note( $note ); $this->complete_order_processing( $order, $intent_status ); } /** * Updates the order to on-hold status and adds a note about the dispute. * * @param WC_Order $order Order object. * @param string $charge_id The ID of the disputed charge associated with this order. * @param string $amount The disputed amount – formatted currency value. * @param string $reason The reason for the dispute – human-readable text. * @param string $due_by The deadline for responding to the dispute - formatted date string. * @param string $status The status of the dispute. * @param string $dispute_id The ID of the dispute. Distinguishes the notes when a charge carries more than one dispute. * * @return void */ public function mark_payment_dispute_created( $order, $charge_id, $amount, $reason, $due_by, $status = '', $dispute_id = '' ) { if ( ! is_a( $order, 'WC_Order' ) ) { return; } $is_inquiry = strpos( $status, 'warning_' ) === 0; $note = $this->generate_dispute_created_note( $charge_id, $amount, $reason, $due_by, $is_inquiry, $dispute_id ); if ( $this->order_note_exists( $order, $note ) ) { return; } $this->update_order_status( $order, Order_Status::ON_HOLD ); $order->add_order_note( $note ); $this->add_open_dispute_id( $order, $dispute_id ); $order->save(); } /** * Updates the order status based on dispute status and adds a note about the dispute. * * @param WC_Order $order Order object. * @param string $charge_id The ID of the disputed charge associated with this order. * @param string $status The status of the dispute. * @param array $dispute_summary Dispute summary information. * @param string $dispute_id The ID of the dispute. Keeps the note (and its refund) distinct when a charge carries more than one dispute. * * @return void */ public function mark_payment_dispute_closed( $order, $charge_id, $status, $dispute_summary = [], $dispute_id = '' ): void { if ( ! is_a( $order, 'WC_Order' ) ) { return; } $is_inquiry = strpos( $status, 'warning_' ) === 0; $note = $this->generate_dispute_closed_note( $charge_id, $status, $is_inquiry, $dispute_id ); if ( $this->order_note_exists( $order, $note ) ) { return; } // Order `completed` and `refunded` emails should both be blocked when disputes are closed. add_filter( 'woocommerce_email_enabled_customer_completed_order', '__return_false' ); add_filter( 'woocommerce_email_enabled_customer_refunded_order', '__return_false' ); add_filter( 'woocommerce_email_enabled_customer_completed_renewal_order', '__return_false' ); $open_dispute_ids = $this->close_open_dispute_id( $order, $dispute_id ); if ( 'lost' === $status ) { // Use dispute summary data if available to determine refund amount. $refund_amount = $order->get_remaining_refund_amount(); $line_items = $order->get_items(); if ( ! empty( $dispute_summary ) ) { $disputed_amount = isset( $dispute_summary['disputed_amount'] ) ? $dispute_summary['disputed_amount'] : 0; if ( $disputed_amount > 0 ) { // Use disputed amount for refund if available. $currency = strtolower( isset( $dispute_summary['currency'] ) ? $dispute_summary['currency'] : $order->get_currency() ); // Convert amounts to the correct format based on currency (e.g. cents to dollars). $disputed_amount = WC_Payments_Utils::interpret_stripe_amount( (int) $disputed_amount, $currency ); // Use the appropriate amount, but don't exceed order total. $refund_amount = min( $refund_amount, $disputed_amount ); if ( $disputed_amount < (float) $order->get_total() ) { // For partial disputes pass empty line_items to avoid inconsistency in the order view. $line_items = []; } } } wc_create_refund( [ 'amount' => $refund_amount, 'reason' => __( 'Dispute lost.', 'woocommerce-payments' ), 'order_id' => $order->get_id(), 'line_items' => $line_items, ] ); } elseif ( ! empty( $open_dispute_ids ) ) { // Another dispute on the same charge is still running its evidence deadline, and // the hold it put on the order has to outlive this one. Leave the status alone // rather than picking a new one: the sibling's own close will resolve it. $order->add_order_note( sprintf( /* translators: %d: the number of disputes on this payment that are still open */ _n( 'The order was not marked as completed because %d other dispute on this payment is still open.', 'The order was not marked as completed because %d other disputes on this payment are still open.', count( $open_dispute_ids ), 'woocommerce-payments' ), count( $open_dispute_ids ) ) ); } elseif ( $this->is_order_fully_refunded( $order ) ) { // Promoting a fully refunded order to completed would make Analytics count it // as revenue again. It still has to leave the dispute hold, though: no other // webhook will arrive to move it off on-hold. if ( ! $order->has_status( Order_Status::REFUNDED ) ) { $this->update_order_status( $order, Order_Status::REFUNDED ); } $order->add_order_note( __( 'The order was not marked as completed because it has already been fully refunded.', 'woocommerce-payments' ) ); } else { // TODO: Revert to the status the order held before the dispute. Nothing records // the pre-dispute status, so completed is the best guess available here. $this->update_order_status( $order, Order_Status::COMPLETED ); $order->save(); } // Restore completed and refunded order emails. remove_filter( 'woocommerce_email_enabled_customer_completed_order', '__return_false' ); remove_filter( 'woocommerce_email_enabled_customer_refunded_order', '__return_false' ); remove_filter( 'woocommerce_email_enabled_customer_completed_renewal_order', '__return_false' ); $order->add_order_note( $note ); } /** * Stores the latest early fraud warning on the order and adds a private note about it. * * Early fraud warnings are independent of the fraud outcome: an approved charge can still * receive one. The meta always reflects the latest warning; the note is only added once * per warning state. * * @param WC_Order $order Order object. * @param string $charge_id The ID of the charge the early fraud warning relates to. * @param string $efw_id The ID of the early fraud warning object. * @param bool $actionable Whether the payment can still be refunded to prevent a dispute. * @param string $fraud_type The fraud type reported by the card network. * @param int $created Unix timestamp of when the early fraud warning was created. * * @return void */ public function mark_payment_early_fraud_warning( $order, string $charge_id, string $efw_id, bool $actionable, string $fraud_type, int $created ) { if ( ! is_a( $order, 'WC_Order' ) ) { return; } $this->set_early_fraud_warning_for_order( $order, [ 'efw_id' => $efw_id, 'efw_actionable' => $actionable, 'efw_type' => $fraud_type, 'created' => $created, ] ); $note = $this->generate_early_fraud_warning_note( $charge_id, $actionable, $fraud_type ); if ( $this->order_note_exists( $order, $note ) ) { return; } $order->add_order_note( $note ); } /** * Updates a terminal order to completed status, while adding a note with a link to the transaction. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $intent_status The status of the intent related to this order. * * @return void */ public function mark_terminal_payment_completed( $order, $intent_id, $intent_status ) { /** * Filters the order status value after a successful terminal payment. * * This filter can be used to override the order status from `completed` to `processing` after a successful terminal charge. * * @since 6.7.0 */ $order_status = apply_filters( 'wcpay_terminal_payment_completed_order_status', Order_Status::COMPLETED ); $this->update_order_status( $order, $order_status, $intent_id ); $this->set_fraud_meta_box_type_for_order( $order, Fraud_Meta_Box_Type::TERMINAL_PAYMENT ); $this->complete_order_processing( $order, $intent_status ); } /** * Mark terminal payment failed function. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $intent_status The status of the intent related to this order. * @param string $charge_id The charge ID related to the intent/order. * @param string $message Optional message to add to the failed note. * * @return void */ public function mark_terminal_payment_failed( $order, string $intent_id, string $intent_status, string $charge_id, string $message ) { if ( ! $this->order_prepared_for_processing( $order, $intent_id ) ) { return; } $order_status_before_update = $order->get_status(); $this->update_order_status( $order, Order_Status::FAILED ); $note = $this->generate_terminal_payment_failure_note( $intent_id, $charge_id, $message, $this->get_order_amount( $order ) ); if ( $this->order_note_exists( $order, $note ) ) { $this->complete_order_processing( $order ); return; } $order->add_order_note( $note ); $this->complete_order_processing( $order, $intent_status ); // When the order is already in 'failed' status, WC core won't fire notification hooks (status didn't change). Manually trigger them so the merchant is notified on every terminal payment failure. if ( Order_Status::FAILED === $order_status_before_update ) { do_action( 'woocommerce_order_status_pending_to_failed_notification', $order->get_id(), $order ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- WooCommerce core hook, not defined by WooPayments. do_action( 'woocommerce_order_status_failed_notification', $order->get_id(), $order ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- WooCommerce core hook, not defined by WooPayments. } } /** * Check if a note content has already existed in the order. * * @param WC_Order $order The order object to add the note. * @param string $note_content Note content. * * @return bool true if the note content exists, false otherwise. */ public function order_note_exists( WC_Order $order, string $note_content ): bool { // Get current notes of the order. $current_notes = wc_get_order_notes( [ 'order_id' => $order->get_id() ] ); foreach ( $current_notes as $current_note ) { if ( $current_note->content === $note_content ) { return true; } } return false; } /** * Adds a note with the fee breakdown for the order. * * @param string $order_id WC Order Id. * @param string $intent_id The intent id for the payment. * @param bool $is_test_mode Whether to run the CRON job in test mode. */ public function add_fee_breakdown_to_order_notes( $order_id, $intent_id, $is_test_mode = false ) { // Since this CRON job may have been created in test_mode, when the CRON job runs, it // may lose the test_mode context. So, instead, we pass that context when creating // the CRON job and apply the context here. $apply_test_mode_context = function () use ( $is_test_mode ) { return $is_test_mode; }; add_filter( 'wcpay_test_mode', $apply_test_mode_context ); $order = wc_get_order( $order_id ); try { $events = $this->api_client->get_timeline( $intent_id ); if ( ! isset( $events['data'] ) || ! is_array( $events['data'] ) ) { Logger::log( sprintf( 'Timeline data missing or malformed for intent_id %s.', $intent_id ) ); return; } $captured_event = current( array_filter( $events['data'], function ( array $event ) { return 'captured' === $event['type']; } ) ); if ( ! is_array( $captured_event ) ) { Logger::log( sprintf( 'No captured event found in timeline for intent_id %s.', $intent_id ) ); return; } $details = ( new WC_Payments_Captured_Event_Note( $captured_event ) )->generate_html_note(); // Add fee breakdown details to the note. $title = WC_Payments_Utils::esc_interpolated_html( // phpcs:ignore WordPress.WP.I18n.NoHtmlWrappedStrings __( '<strong>Fee details:</strong>', 'woocommerce-payments' ), [ 'strong' => '<strong>', ] ); $note = $title . $details; // Update the order with the new note. $order->add_order_note( $note ); $order->save(); } catch ( Exception $e ) { Logger::log( sprintf( 'Can not generate the detailed note for intent_id %1$s. Reason: %2$s', $intent_id, $e->getMessage() ) ); } } /** * Get the payment metadata for intent id. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_intent_id_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::INTENT_ID_META_KEY, true ); } /** * Set the payment metadata for intent id. * * @param WC_Order $order The order object. * @param string $intent_id The value to be set. * * @throws Order_Not_Found_Exception */ public function set_intent_id_for_order( $order, $intent_id ) { $order = $this->get_order( $order ); $order->update_meta_data( self::INTENT_ID_META_KEY, $intent_id ); $order->save_meta_data(); /** * Hook: When the order meta data _intent_id is updated. * * @since 5.4.0 */ do_action( 'wcpay_order_intent_id_updated' ); } /** * Get the payment metadata for payment method id. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_payment_method_id_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::PAYMENT_METHOD_ID_META_KEY, true ); } /** * Set the payment metadata for payment method id. * * @param mixed $order The order. * @param string $payment_method_id The value to be set. * * @throws Order_Not_Found_Exception */ public function set_payment_method_id_for_order( $order, $payment_method_id ) { $order = $this->get_order( $order ); $order->update_meta_data( self::PAYMENT_METHOD_ID_META_KEY, $payment_method_id ); $order->save_meta_data(); /** * Hook: When the order meta data _payment_method_id is updated. * * @since 5.4.0 */ do_action( 'wcpay_order_payment_method_id_updated' ); } /** * Set the payment metadata for charge id. * * @param mixed $order The order. * @param string $charge_id The value to be set. * * @throws Order_Not_Found_Exception */ public function set_charge_id_for_order( $order, $charge_id ) { $order = $this->get_order( $order ); $order->update_meta_data( self::CHARGE_ID_META_KEY, $charge_id ); $order->save_meta_data(); } /** * Set the payment metadata for payment transaction id. * * @param mixed $order The order. * @param string $payment_transaction_id The value to be set. * * @throws Order_Not_Found_Exception */ public function set_payment_transaction_id_for_order( $order, $payment_transaction_id ) { if ( ! isset( $payment_transaction_id ) || null === $payment_transaction_id ) { return; } $order = $this->get_order( $order ); $order->update_meta_data( self::WCPAY_PAYMENT_TRANSACTION_ID_META_KEY, $payment_transaction_id ); $order->save_meta_data(); } /** * Set the payment metadata for risk level. * * @param mixed $order The order. * @param string $risk_level The value to be set. * * @throws Order_Not_Found_Exception */ public function set_charge_risk_level_for_order( $order, $risk_level ) { if ( ! isset( $risk_level ) || null === $risk_level ) { return; } $order = $this->get_order( $order ); $order->update_meta_data( self::CHARGE_RISK_LEVEL_META_KEY, $risk_level ); $order->save_meta_data(); } /** * Get the risk level for an order. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_charge_risk_level_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::CHARGE_RISK_LEVEL_META_KEY, true ); } /** * Get the payment metadata for charge id. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_charge_id_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::CHARGE_ID_META_KEY, true ); } /** * Set the payment metadata for intention status. * * @param mixed $order The order. * @param string $intention_status The value to be set. * * @throws Order_Not_Found_Exception */ public function set_intention_status_for_order( $order, $intention_status ) { $order = $this->get_order( $order ); $order->update_meta_data( self::INTENTION_STATUS_META_KEY, $intention_status ); $order->save_meta_data(); } /** * Get the payment metadata for intention status. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_intention_status_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::INTENTION_STATUS_META_KEY, true ); } /** * Checks if order has an open (uncaptured) authorization. * * @param mixed $order The order Id or order object. * * @return bool * * @throws Order_Not_Found_Exception */ public function has_open_authorization( $order ): bool { $order = $this->get_order( $order ); return Intent_Status::REQUIRES_CAPTURE === $order->get_meta( self::INTENTION_STATUS_META_KEY, true ); } /** * Set the payment metadata for customer id. * * @param mixed $order The order. * @param string $customer_id The value to be set. * * @throws Order_Not_Found_Exception */ public function set_customer_id_for_order( $order, $customer_id ) { $order = $this->get_order( $order ); $order->update_meta_data( self::CUSTOMER_ID_META_KEY, $customer_id ); $order->save_meta_data(); } /** * Removes the payment details of an earlier WooPayments attempt from an order paid with another gateway. * * WooCommerce can reuse a pending or failed order at checkout, which keeps what an earlier WooPayments * attempt stored on it. Every attempt stores its mode with its details and this cleanup removes it, so a * mode means an attempt since the last cleanup. Other gateways, such as WooCommerce Stripe, store * `_stripe_customer_id` too, and never the mode, so what they store stays. * * @param int|WC_Order $order The order, or its ID. * * @return void */ public function maybe_remove_payment_details_for_other_gateway( $order ): void { $order = $order instanceof WC_Order ? $order : wc_get_order( $order ); if ( ! $order instanceof WC_Order || 0 === strpos( $order->get_payment_method(), WC_Payment_Gateway_WCPay::GATEWAY_ID ) || '' === (string) $order->get_meta( self::WCPAY_MODE_META_KEY ) ) { return; } $intent_status = $this->get_intention_status_for_order( $order ); // A payment that went through is not an earlier attempt: the merchant reopened a paid order. if ( in_array( $intent_status, Intent_Status::AUTHORIZED_STATUSES, true ) ) { return; } // An attached intent is often still the order's transaction id, which the capture and cancel actions act // on, and a 3DS step left open can still charge the card. A setup intent (`seti_`) can't charge, and the // payment intent cancel endpoint doesn't take it. Both are dealt with once the request ends, because a // Store API cart update during the checkout can save the session's earlier gateway on the order. $intent_id = $this->get_intent_id_for_order( $order ); $cancel = 0 === strpos( $intent_id, 'pi_' ) && Intent_Status::REQUIRES_ACTION === $intent_status; if ( $cancel || ( '' !== $intent_id && $order->get_transaction_id() === $intent_id ) ) { $this->earlier_attempts_to_finish[ $order->get_id() ] = [ 'intent_id' => $intent_id, 'cancel' => $cancel, ]; add_action( 'shutdown', [ $this, 'finish_removing_earlier_attempts' ] ); } // With no intent on the order, the paths that read it (3DS callback, redirect return, duplicate payment // check, capture) have nothing to act on. Webhooks find the order through the intent's metadata, so the // removed intent is listed, and the time covers older attempts the order no longer named. $superseded_intent_ids = $order->get_meta( self::SUPERSEDED_INTENT_IDS_META_KEY ); $superseded_intent_ids = is_array( $superseded_intent_ids ) ? $superseded_intent_ids : []; if ( '' !== $intent_id && ! in_array( $intent_id, $superseded_intent_ids, true ) ) { $superseded_intent_ids[] = $intent_id; } $order->delete_meta_data( self::CUSTOMER_ID_META_KEY ); $order->delete_meta_data( self::PAYMENT_METHOD_ID_META_KEY ); $order->delete_meta_data( self::INTENT_ID_META_KEY ); $order->delete_meta_data( self::INTENTION_STATUS_META_KEY ); $order->delete_meta_data( self::WCPAY_MODE_META_KEY ); if ( ! empty( $superseded_intent_ids ) ) { $order->update_meta_data( self::SUPERSEDED_INTENT_IDS_META_KEY, $superseded_intent_ids ); } $order->update_meta_data( self::PAYMENT_DETAILS_REMOVED_META_KEY, (string) time() ); $order->save_meta_data(); if ( '' === $intent_id ) { $order->add_order_note( __( 'The payment details of an earlier WooPayments attempt were removed because this order is being paid with another payment method.', 'woocommerce-payments' ) ); } else { $this->add_note_naming_intent( $order, /* translators: %1: the ID of a WooPayments payment. */ __( 'The payment details of an earlier WooPayments attempt (<code>%1$s</code>) were removed because this order is being paid with another payment method.', 'woocommerce-payments' ), $intent_id ); } } /** * Adds an order note whose message names a WooPayments payment in its `<code>%1$s</code>` placeholder. * * @param WC_Order $order The order. * @param string $message The translated message, with the `<code>` tag around `%1$s`. * @param string $intent_id The payment to name. * * @return void */ private function add_note_naming_intent( WC_Order $order, string $message, string $intent_id ): void { $order->add_order_note( sprintf( WC_Payments_Utils::esc_interpolated_html( $message, [ 'code' => '<code>' ] ), $intent_id ) ); } /** * Whether an intent belongs to a WooPayments attempt from before another gateway took the order over. * * Webhooks find the order through the intent's metadata rather than the intent on the order. An intent * the cleanup removed is named on the order, which is exact. An older attempt the order no longer named * at the takeover is told apart by its creation time against the takeover time, which compares Stripe's * clock with the store's, so it can miss an attempt started within the clock difference of the takeover. * That comparison stops once a new WooPayments attempt writes the mode back: a store clock ahead of * Stripe's would otherwise make a retry seconds after a failed takeover look superseded, and for a method * that pays later the skipped webhook is what completes the order. * * @param WC_Order $order The order. * @param string $intent_id The intent. * @param int $intent_created_at When the intent was created, as a Unix time; 0 when unknown. * * @return bool */ public function is_intent_from_superseded_attempt( WC_Order $order, string $intent_id, int $intent_created_at ): bool { $superseded_intent_ids = $order->get_meta( self::SUPERSEDED_INTENT_IDS_META_KEY ); if ( is_array( $superseded_intent_ids ) && in_array( $intent_id, $superseded_intent_ids, true ) ) { return true; } if ( '' !== (string) $order->get_meta( self::WCPAY_MODE_META_KEY ) ) { return false; } $taken_over_at = (int) $order->get_meta( self::PAYMENT_DETAILS_REMOVED_META_KEY ); return 0 < $taken_over_at && 0 < $intent_created_at && $intent_created_at < $taken_over_at; } /** * Finishes removing earlier WooPayments attempts from orders another gateway took over in this request. * * Runs on `shutdown`, once the checkout has saved the order: clears each attempt's transaction id and * cancels an attempt still waiting for 3DS. Each attempt is handled once. An uncaught error is fatal on * `shutdown`, so both steps catch every throwable, and a failed clear doesn't stop the cancel. * * @internal * * @return void */ public function finish_removing_earlier_attempts(): void { $earlier_attempts = $this->earlier_attempts_to_finish; $this->earlier_attempts_to_finish = []; foreach ( $earlier_attempts as $order_id => $earlier_attempt ) { $order = wc_get_order( $order_id ); if ( ! $order instanceof WC_Order ) { continue; } $this->clear_transaction_id_of_earlier_attempt( $order, $earlier_attempt['intent_id'] ); if ( $earlier_attempt['cancel'] ) { $this->cancel_intent_of_earlier_attempt( $order, $earlier_attempt['intent_id'] ); } } } /** * Clears the transaction id of an order when it is the intent of an earlier WooPayments attempt. * * The capture and cancel actions on the authorizations screen act on the transaction id. A transaction id * another gateway set stays. * * @param WC_Order $order The order. * @param string $intent_id The intent of the earlier attempt. * * @return void */ private function clear_transaction_id_of_earlier_attempt( WC_Order $order, string $intent_id ): void { if ( $order->get_transaction_id() !== $intent_id ) { return; } try { $order->set_transaction_id( '' ); $order->save(); } catch ( \Throwable $e ) { Logger::error( sprintf( 'Could not clear transaction id %1$s of order %2$d: %3$s', $intent_id, $order->get_id(), $e->getMessage() ) ); } } /** * Cancels the intent of an earlier WooPayments attempt on an order another gateway took over, and notes * whether it worked. * * @param WC_Order $order The order. * @param string $intent_id The intent of the earlier attempt. * * @return void */ private function cancel_intent_of_earlier_attempt( WC_Order $order, string $intent_id ): void { try { $request = Cancel_Intention::create( $intent_id ); $request->set_hook_args( $order ); $request->send(); /* translators: %1: the ID of a WooPayments payment. */ $message = __( 'The earlier WooPayments payment <code>%1$s</code> was cancelled because this order was paid with another payment method.', 'woocommerce-payments' ); } catch ( \Throwable $e ) { Logger::error( sprintf( 'Could not cancel intent %1$s of order %2$d: %3$s', $intent_id, $order->get_id(), $e->getMessage() ) ); /* translators: %1: the ID of a WooPayments payment. */ $message = __( 'The earlier WooPayments payment <code>%1$s</code> could not be cancelled when this order was paid with another payment method. Check that it was not charged.', 'woocommerce-payments' ); } try { $this->add_note_naming_intent( $order, $message, $intent_id ); } catch ( \Throwable $e ) { Logger::error( sprintf( 'Could not note the cancel of intent %1$s on order %2$d: %3$s', $intent_id, $order->get_id(), $e->getMessage() ) ); } } /** * Get the payment metadata for customer id. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_customer_id_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::CUSTOMER_ID_META_KEY, true ); } /** * Set the payment metadata for intent currency. * * @param mixed $order The order. * @param string $wcpay_intent_currency The value to be set. * * @throws Order_Not_Found_Exception */ public function set_wcpay_intent_currency_for_order( $order, $wcpay_intent_currency ) { $order = $this->get_order( $order ); $order->update_meta_data( self::WCPAY_INTENT_CURRENCY_META_KEY, $wcpay_intent_currency ); $order->save_meta_data(); } /** * Get the payment metadata for intent currency. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_wcpay_intent_currency_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::WCPAY_INTENT_CURRENCY_META_KEY, true ); } /** * Set WCPay refund ID as metadata for refund object. * * @param WC_Order_Refund $wc_refund The refund instance. * @param string $wcpay_refund_id The value to be set. * * @throws Order_Not_Found_Exception */ public function set_wcpay_refund_id_for_refund( $wc_refund, $wcpay_refund_id ) { $wc_refund = $this->get_order( $wc_refund ); $wc_refund->update_meta_data( self::WCPAY_REFUND_ID_META_KEY, $wcpay_refund_id ); $wc_refund->save_meta_data(); } /** * Set the payment metadata for refund transaction id. * * @param WC_Order_Refund $order The order. * @param string $wcpay_transaction_id The value to be set. * * @throws Order_Not_Found_Exception */ public function set_wcpay_refund_transaction_id_for_order( WC_Order_Refund $order, string $wcpay_transaction_id ) { $order = $this->get_order( $order ); $order->update_meta_data( self::WCPAY_REFUND_TRANSACTION_ID_META_KEY, $wcpay_transaction_id ); $order->save_meta_data(); } /** * Get the payment metadata for refund id. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_wcpay_refund_id_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::WCPAY_REFUND_ID_META_KEY, true ); } /** * Set the payment metadata for refund status. * * @param mixed $order The order. * @param string $wcpay_refund_status The value to be set. * * @throws Order_Not_Found_Exception */ public function set_wcpay_refund_status_for_order( $order, $wcpay_refund_status ) { $order = $this->get_order( $order ); $order->update_meta_data( self::WCPAY_REFUND_STATUS_META_KEY, $wcpay_refund_status ); $order->save_meta_data(); } /** * Get the payment metadata for refund status. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_wcpay_refund_status_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::WCPAY_REFUND_STATUS_META_KEY, true ); } /** * Set the fraud_outcome_status for an order. * * @param mixed $order The order. * @param string $fraud_outcome_status The value to be set. * * @throws Order_Not_Found_Exception */ public function set_fraud_outcome_status_for_order( $order, $fraud_outcome_status ) { $order = $this->get_order( $order ); $order->update_meta_data( self::WCPAY_FRAUD_OUTCOME_STATUS_META_KEY, $fraud_outcome_status ); $order->save_meta_data(); } /** * Get the fraud_outcome_status for an order. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_fraud_outcome_status_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::WCPAY_FRAUD_OUTCOME_STATUS_META_KEY, true ); } /** * Set the fraud ruleset results for an order. * * @param mixed $order The order. * @param array $ruleset_results The ruleset results, as a map of rule key => outcome. * * @throws Order_Not_Found_Exception */ public function set_fraud_ruleset_results_for_order( $order, array $ruleset_results ) { $order = $this->get_order( $order ); $order->update_meta_data( self::WCPAY_FRAUD_RULESET_RESULTS_META_KEY, wp_json_encode( $ruleset_results ) ); $order->save_meta_data(); } /** * Get the fraud ruleset results for an order. * * @param mixed $order The order Id or order object. * * @return array The ruleset results, as a map of rule key => outcome. Empty when none were stored. * * @throws Order_Not_Found_Exception */ public function get_fraud_ruleset_results_for_order( $order ): array { $order = $this->get_order( $order ); return $this->decode_ruleset_results( (string) $order->get_meta( self::WCPAY_FRAUD_RULESET_RESULTS_META_KEY, true ) ); } /** * Set the fraud_meta_box_type for an order. * * @param mixed $order The order. * @param string $fraud_meta_box_type The value to be set. * * @throws Order_Not_Found_Exception */ public function set_fraud_meta_box_type_for_order( $order, $fraud_meta_box_type ) { $order = $this->get_order( $order ); $order->update_meta_data( self::WCPAY_FRAUD_META_BOX_TYPE_META_KEY, $fraud_meta_box_type ); $order->save_meta_data(); } /** * Get the fraud_meta_box_type for an order. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_fraud_meta_box_type_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::WCPAY_FRAUD_META_BOX_TYPE_META_KEY, true ); } /** * Set the early fraud warning data for an order. * * @param mixed $order The order. * @param array{efw_id: string, efw_actionable: bool, efw_type: string, created: int} $early_fraud_warning The early fraud warning data to be set. * * @throws Order_Not_Found_Exception */ public function set_early_fraud_warning_for_order( $order, array $early_fraud_warning ) { $order = $this->get_order( $order ); $order->update_meta_data( self::WCPAY_EARLY_FRAUD_WARNING_META_KEY, $early_fraud_warning ); if ( ! empty( $early_fraud_warning['efw_actionable'] ) ) { $order->update_meta_data( self::WCPAY_EARLY_FRAUD_WARNING_ACTIONABLE_META_KEY, (int) ( $early_fraud_warning['created'] ?? 0 ) ); } else { $order->delete_meta_data( self::WCPAY_EARLY_FRAUD_WARNING_ACTIONABLE_META_KEY ); } $order->save_meta_data(); } /** * Get the early fraud warning data for an order. * * @param mixed $order The order Id or order object. * * @return array{efw_id: string, efw_actionable: bool, efw_type: string, created: int}|null The early fraud warning data, or null when none was received. * * @throws Order_Not_Found_Exception */ public function get_early_fraud_warning_for_order( $order ): ?array { $order = $this->get_order( $order ); $early_fraud_warning = $order->get_meta( self::WCPAY_EARLY_FRAUD_WARNING_META_KEY, true ); return is_array( $early_fraud_warning ) ? $early_fraud_warning : null; } /** * Returns orders whose latest early fraud warning is still actionable. * * Inspects the $limit most recent actionable warnings by warning date, so * the result is a lower bound on very large stores. Callers should cache * the result — the meta query is too slow to run on every admin request. * * The actionable index stores the warning timestamp, so the query itself * returns the newest warnings first even when a warning lands long after * the order was placed. * * @param int $limit Maximum number of warning-carrying orders to inspect. * * @return array[] Arrays with `order_id`, `order_number`, `charge_id` and `created` keys, newest warning first. */ public function get_actionable_early_fraud_warning_orders( int $limit = 100 ): array { $orders = wc_get_orders( [ 'limit' => $limit, 'orderby' => 'meta_value_num', 'order' => 'DESC', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_key' => self::WCPAY_EARLY_FRAUD_WARNING_ACTIONABLE_META_KEY, ] ); $is_test_mode = WC_Payments::mode()->is_test(); $actionable_orders = []; foreach ( $orders as $order ) { // A warning stored in the other mode can never clear: the webhook that would // resolve it is discarded as a mode mismatch. Orders predating the mode meta // read as live, matching has_live_sale(). if ( $is_test_mode !== $this->is_order_in_test_mode( $order ) ) { continue; } $early_fraud_warning = $this->get_early_fraud_warning_for_order( $order ); if ( empty( $early_fraud_warning['efw_actionable'] ) ) { continue; } // Refunding is the action the warning asks for, so treat a fully refunded order // as resolved rather than waiting on a webhook that may never arrive. $total = (float) $order->get_total(); if ( $total > 0 && (float) $order->get_total_refunded() >= $total ) { continue; } $actionable_orders[] = [ 'order_id' => $order->get_id(), 'order_number' => $order->get_order_number(), 'charge_id' => $this->get_charge_id_for_order( $order ), 'created' => (int) $order->get_meta( self::WCPAY_EARLY_FRAUD_WARNING_ACTIONABLE_META_KEY, true ), ]; } return $actionable_orders; } /** * Drops the cached early fraud warning lists when a flagged order is refunded. * * Only a warning webhook invalidates them otherwise, which leaves the refunded-order * guard in get_actionable_early_fraud_warning_orders() unreachable on a cache hit — * exactly when no resolving webhook is coming. What counts as resolved stays in that * query, so this only decides that the list may be stale. * * @param int $order_id The refunded order's ID. * * @return void */ public function maybe_clear_early_fraud_warning_caches( $order_id ) { $order = wc_get_order( $order_id ); if ( ! $order || ! $order->get_meta( self::WCPAY_EARLY_FRAUD_WARNING_META_KEY ) ) { return; } WC_Payments::get_database_cache()->delete_early_fraud_warning_caches(); } /** * Set the IPP channel for an order. * * @param mixed $order The order ID or order object. * @param string $channel The IPP channel value (e.g. 'mobile_pos', 'mobile_store_management'). * * @return void * * @throws Order_Not_Found_Exception */ public function set_ipp_channel_for_order( $order, string $channel ): void { $order = $this->get_order( $order ); $order->update_meta_data( self::IPP_CHANNEL_META_KEY, $channel ); $order->save_meta_data(); } /** * Get the IPP channel for an order. * * @param mixed $order The order Id or order object. * * @return string * * @throws Order_Not_Found_Exception */ public function get_ipp_channel_for_order( $order ): string { $order = $this->get_order( $order ); return $order->get_meta( self::IPP_CHANNEL_META_KEY ); } /** * Given the payment intent data, adds it to the given order as metadata and parses any notes that need to be added * * @param WC_Order $order The order. * @param WC_Payments_API_Payment_Intention|WC_Payments_API_Setup_Intention $intent The payment or setup intention object. * @param bool $allow_update_on_success Whether the payment is being changed for a subscription. * * @throws Order_Not_Found_Exception */ public function attach_intent_info_to_order( WC_Order $order, $intent, $allow_update_on_success = false ) { // We don't want to allow metadata for a successful payment to be disrupted (except for when changing payment method for subscription or renewing subscription). if ( Intent_Status::SUCCEEDED === $this->get_intention_status_for_order( $order ) && ! $allow_update_on_success ) { return; } // first, let's prepare all the metadata needed for refunds, required for status change etc. $intent_id = $intent->get_id(); $intent_status = $intent->get_status(); $payment_method = $intent->get_payment_method_id(); $customer_id = $intent->get_customer_id(); $currency = $intent instanceof WC_Payments_API_Payment_Intention ? $intent->get_currency() : $order->get_currency(); $charge = $intent instanceof WC_Payments_API_Payment_Intention ? $intent->get_charge() : null; $charge_id = $charge ? $charge->get_id() : null; $payment_transaction = $charge ? $charge->get_balance_transaction() : null; $payment_transaction_id = $payment_transaction['id'] ?? ''; $outcome = $charge ? $charge->get_outcome() : null; $risk_level = $outcome ? $outcome['risk_level'] : null; // next, save it in order meta. $this->attach_intent_info_to_order__legacy( $order, $intent_id, $intent_status, $payment_method, $customer_id, $charge_id, $currency, $payment_transaction_id, $risk_level ); // Store payment method details when available. if ( null !== $charge ) { $payment_method_details = $charge->get_payment_method_details(); if ( $payment_method_details ) { $this->store_payment_method_details( $order, $payment_method_details ); } } // Store IPP channel from intent metadata if present. $metadata = $intent->get_metadata(); $ipp_channel = $metadata['ipp_channel'] ?? ''; $allowed_channels = [ 'mobile_pos', 'mobile_store_management' ]; if ( in_array( $ipp_channel, $allowed_channels, true ) ) { $this->set_ipp_channel_for_order( $order, $ipp_channel ); } } /** * Legacy version of the attach_intent_info_to_order method. * * TODO: This method should ultimately be merged with `attach_intent_info_to_order` and then removed. * * @param WC_Order $order The order. * @param string $intent_id The intent ID. * @param string $intent_status Intent status. * @param string $payment_method Payment method ID. * @param string $customer_id Customer ID. * @param string $charge_id Charge ID. * @param string $currency Currency code. * @param string $payment_transaction_id The transaction ID of the linked charge. * @param string $risk_level The risk level of the payment. * * @throws Order_Not_Found_Exception */ public function attach_intent_info_to_order__legacy( $order, $intent_id, $intent_status, $payment_method, $customer_id, $charge_id, $currency, $payment_transaction_id = null, $risk_level = null ) { // first, let's save all the metadata that needed for refunds, required for status change etc. $order->set_transaction_id( $intent_id ); $this->set_intent_id_for_order( $order, $intent_id ); $this->set_payment_method_id_for_order( $order, $payment_method ); $this->set_charge_id_for_order( $order, $charge_id ); $this->set_intention_status_for_order( $order, $intent_status ); $this->set_customer_id_for_order( $order, $customer_id ); $this->set_wcpay_intent_currency_for_order( $order, $currency ); $this->set_payment_transaction_id_for_order( $order, $payment_transaction_id ); $this->set_charge_risk_level_for_order( $order, $risk_level ); $order->save(); } /** * Create the shipping data array to send to Stripe when making a purchase. * * @param WC_Order $order The order that is being paid for. * @return array The shipping data to send to Stripe. */ public function get_shipping_data_from_order( WC_Order $order ): array { return [ 'name' => implode( ' ', array_filter( [ $order->get_shipping_first_name(), $order->get_shipping_last_name(), ] ) ), 'address' => [ 'line1' => $order->get_shipping_address_1(), 'line2' => $order->get_shipping_address_2(), 'postal_code' => $order->get_shipping_postcode(), 'city' => $order->get_shipping_city(), 'state' => $order->get_shipping_state(), 'country' => $order->get_shipping_country(), ], ]; } /** * Create the billing data array to send to Stripe when making a purchase, based on order's billing data. * It only returns the fields that are present in the billing section of the checkout. * * @param WC_Order $order The order that is being paid for. * @return array The shipping data to send to Stripe. */ public function get_billing_data_from_order( WC_Order $order ): array { $billing_fields = array_keys( WC()->countries->get_address_fields( $order->get_billing_country() ) ); $address_field_to_key = [ 'billing_city' => 'city', 'billing_country' => 'country', 'billing_address_1' => 'line1', 'billing_address_2' => 'line2', 'billing_postcode' => 'postal_code', 'billing_state' => 'state', ]; $field_to_key = [ 'billing_email' => 'email', 'billing_phone' => 'phone', ]; $billing_details = [ 'address' => [] ]; foreach ( $billing_fields as $field ) { if ( isset( $address_field_to_key[ $field ] ) ) { $billing_details['address'][ $address_field_to_key[ $field ] ] = $order->{"get_{$field}"}(); } elseif ( isset( $field_to_key[ $field ] ) ) { $billing_details[ $field_to_key[ $field ] ] = $order->{"get_{$field}"}(); } } if ( in_array( 'billing_first_name', $billing_fields, true ) && in_array( 'billing_last_name', $billing_fields, true ) ) { $billing_details['name'] = trim( $order->get_formatted_billing_full_name() ); } // The country field can't ever be empty, so we remove it if it is. if ( empty( $billing_details['address']['country'] ) ) { unset( $billing_details['address']['country'] ); } return $billing_details; } /** * Creates an "authorization cancelled" order note if not already present. * * @param WC_Order $order The order. * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * @return boolean True if the note was added, false otherwise. */ public function post_unique_capture_cancelled_note( $order, $intent_id, $charge_id ): bool { $note = $this->generate_capture_cancelled_note( $intent_id, $charge_id ); if ( ! $this->order_note_exists( $order, $note ) ) { $order->add_order_note( $note ); return true; } return false; } /** * Creates an "authorization captured" order note if not already present. * * @param WC_Order $order The order. * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * @return boolean True if the note was added, false otherwise. */ public function post_unique_capture_complete_note( $order, $intent_id, $charge_id ) { $note = $this->generate_capture_success_note( $order, $intent_id, $charge_id ); if ( ! $this->order_note_exists( $order, $note ) ) { $order->add_order_note( $note ); return true; } return false; } /** * Updates an order to cancelled status, while adding a note with a link to the transaction. * * @param WC_Order $order Order object. * @param array $intent_data The intent data associated with this order. * * @return void */ private function mark_payment_capture_cancelled( $order, $intent_data ) { if ( false === $this->post_unique_capture_cancelled_note( $order, $intent_data['intent_id'], $intent_data['charge_id'] ) ) { $this->complete_order_processing( $order ); return; } /** * If we have a status for the fraud outcome, we want to add the proper meta data. */ if ( isset( $intent_data['fraud_outcome'] ) && Rule::is_valid_fraud_outcome_status( $intent_data['fraud_outcome'] ) && Rule::FRAUD_OUTCOME_ALLOW !== $intent_data['fraud_outcome'] ) { $this->set_fraud_outcome_status_for_order( $order, $intent_data['fraud_outcome'] ); $this->set_fraud_meta_box_type_for_order( $order, Fraud_Meta_Box_Type::REVIEW_BLOCKED ); } // Remove transaction fee since the authorization was canceled and no payment was processed. $order->delete_meta_data( self::WCPAY_TRANSACTION_FEE_META_KEY ); $order->delete_meta_data( '_wcpay_net' ); $this->update_order_status( $order, Order_Status::CANCELLED ); $this->complete_order_processing( $order, $intent_data['intent_status'] ); } /** * Updates an order to processing/completed status, while adding a note with a link to the transaction. * * @param WC_Order $order Order object. * @param array $intent_data The data of the intent associated with this order. * * @return void */ private function mark_payment_completed( $order, $intent_data ) { $note = $this->is_order_in_test_mode( $order ) ? $this->generate_test_mode_payment_success_note( $intent_data['intent_id'], $intent_data['charge_id'], $this->get_order_amount( $order ) ) : $this->generate_payment_success_note( $intent_data['intent_id'], $intent_data['charge_id'], $this->get_order_amount( $order ) ); if ( $this->order_note_exists( $order, $note ) ) { return; } // Check if a capture note already exists for this payment intent. // This prevents adding a duplicate "charged" note when the payment was already // processed via manual capture (race condition between capture flow and webhooks). $capture_note = $this->generate_capture_success_note( $order, $intent_data['intent_id'], $intent_data['charge_id'] ); if ( $this->order_note_exists( $order, $capture_note ) ) { return; } // Update the note with the fee breakdown details async, update order status, add order note. $this->enqueue_add_fee_breakdown_to_order_notes( $order, $intent_data['intent_id'] ); /** * If we have a status for the fraud outcome, we want to add the proper meta data. * If auth/capture is enabled and the transaction is allowed, it will be 'allow'. * If it was held for review for any reason, it will be 'review'. */ if ( '' !== $intent_data['fraud_outcome'] && Rule::is_valid_fraud_outcome_status( $intent_data['fraud_outcome'] ) ) { $fraud_meta_box_type = Order_Status::ON_HOLD === $order->get_status() ? Fraud_Meta_Box_Type::REVIEW_ALLOWED : Fraud_Meta_Box_Type::ALLOW; $this->set_fraud_outcome_status_for_order( $order, $intent_data['fraud_outcome'] ); $this->set_fraud_meta_box_type_for_order( $order, $fraud_meta_box_type ); } if ( ! $this->intent_has_card_payment_type( $intent_data ) ) { $this->set_fraud_meta_box_type_for_order( $order, Fraud_Meta_Box_Type::NOT_CARD ); } $this->update_order_status( $order, 'payment_complete', $intent_data['intent_id'] ); $order->add_order_note( $note ); $this->set_intention_status_for_order( $order, $intent_data['intent_status'] ); } /** * Checks whether a payment intent is for the order's current total and currency. * * The order total can change after the intent is created, for example when a merchant edits a pending order. * * @param WC_Payments_API_Payment_Intention $intent The intent to compare. * @param WC_Order $order The order to compare against. * * @return bool */ private function intent_amount_matches_order( WC_Payments_API_Payment_Intention $intent, WC_Order $order ): bool { return strtolower( $intent->get_currency() ) === strtolower( $order->get_currency() ) && (int) $intent->get_amount() === WC_Payments_Utils::prepare_amount( $order->get_total(), $order->get_currency() ); } /** * Puts an order on hold when its payment succeeded for an amount or currency that differs from the order total. * * @param WC_Order $order Order object. * @param WC_Payments_API_Payment_Intention $intent The succeeded intent. * @param array $intent_data The data of the intent associated with this order. * * @return void */ private function mark_payment_held_for_amount_mismatch( $order, WC_Payments_API_Payment_Intention $intent, $intent_data ) { $charged_currency = strtoupper( $intent->get_currency() ); $order_currency = strtoupper( $order->get_currency() ); // Always show the codes: USD and CAD both render as "$", and single-currency stores hide codes by default. $charged_amount = wc_price( WC_Payments_Utils::interpret_stripe_amount( (int) $intent->get_amount(), $charged_currency ), [ 'currency' => $charged_currency ] ) . ' ' . $charged_currency; $order_amount = wc_price( $order->get_total(), [ 'currency' => $order_currency ] ) . ' ' . $order_currency; $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_data['intent_id'], $intent_data['charge_id'] ); $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the charged amount, %2: WooPayments, %3: transaction ID of the payment, %4: the order total, %5: transaction details URL */ __( 'A payment of %1$s was charged using %2$s (<a>%3$s</a>), but the order total is %4$s. The order was put <strong>on hold</strong>; review it before fulfilling.', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%5$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $charged_amount, 'WooPayments', WC_Payments_Utils::get_transaction_url_id( $intent_data['intent_id'], $intent_data['charge_id'] ), $order_amount, $transaction_url ); if ( $this->order_note_exists( $order, $note ) ) { return; } Logger::error( sprintf( 'Order %1$d put on hold: intent %2$s succeeded for %3$d %4$s, but the order total is %5$s %6$s.', $order->get_id(), $intent_data['intent_id'], $intent->get_amount(), $intent->get_currency(), $order->get_total(), $order->get_currency() ) ); $this->update_order_status( $order, Order_Status::ON_HOLD ); $order->add_order_note( $note ); $this->set_intention_status_for_order( $order, $intent_data['intent_status'] ); } /** * Updates an order to on-hold status, while adding a note with a link to the transaction. * * @param WC_Order $order Order object. * @param array $intent_data The intent data associated with this order. * * @return void */ private function mark_payment_authorized( $order, $intent_data ) { $note = $this->generate_payment_authorized_note( $order, $intent_data['intent_id'], $intent_data['charge_id'] ); if ( $this->order_note_exists( $order, $note ) || $order->has_status( [ Order_Status::ON_HOLD ] ) ) { return; } if ( Rule::FRAUD_OUTCOME_ALLOW === $intent_data['fraud_outcome'] ) { $this->set_fraud_outcome_status_for_order( $order, Rule::FRAUD_OUTCOME_ALLOW ); $this->set_fraud_meta_box_type_for_order( $order, Fraud_Meta_Box_Type::ALLOW ); } $this->update_order_status( $order, Order_Status::ON_HOLD ); $order->add_order_note( $note ); $this->set_intention_status_for_order( $order, $intent_data['intent_status'] ); } /** * Updates an order to on-hold status, while adding a note with a link to the transaction. * * @param WC_Order $order Order object. * @param array $intent_data The intent data associated with this order. * * @return void */ private function mark_payment_on_hold( $order, $intent_data ) { $note = $this->generate_payment_started_note( $order, $intent_data['intent_id'] ); if ( $this->order_note_exists( $order, $note ) ) { return; } $fraud_meta_box_type = $this->intent_has_card_payment_type( $intent_data ) ? Fraud_Meta_Box_Type::PAYMENT_STARTED : Fraud_Meta_Box_Type::NOT_CARD; $this->set_fraud_meta_box_type_for_order( $order, $fraud_meta_box_type ); $this->update_order_status( $order, Order_Status::ON_HOLD ); $order->add_order_note( $note ); $this->set_intention_status_for_order( $order, $intent_data['intent_status'] ); } /** * Updates an order to processing/completed status, while adding a note with a link to the transaction. * * @param WC_Order $order Order object. * @param WC_Payments_API_Payment_Intention $intent The intent instance. * * @return void */ private function mark_payment_capture_completed( $order, $intent ) { $intent_id = $intent->get_id(); $note = $this->generate_capture_success_note( $order, $intent_id, $intent->get_charge()->get_id() ); if ( $this->order_note_exists( $order, $note ) ) { return; } // Update the note with the fee breakdown details async. $this->enqueue_add_fee_breakdown_to_order_notes( $order, $intent_id ); /** * If we have a status for the fraud outcome, we want to add the proper meta data. * If auth/capture is enabled and the transaction is allowed, it will be 'allow'. * If it was held for review for any reason, it will be 'review'. */ $fraud_outcome = $intent->get_metadata()['fraud_outcome'] ?? ''; if ( '' !== $fraud_outcome && Rule::is_valid_fraud_outcome_status( $fraud_outcome ) ) { $fraud_meta_box_type = Rule::FRAUD_OUTCOME_REVIEW === $this->get_fraud_outcome_status_for_order( $order ) ? Fraud_Meta_Box_Type::REVIEW_ALLOWED : Fraud_Meta_Box_Type::ALLOW; $this->set_fraud_outcome_status_for_order( $order, $fraud_outcome ); $this->set_fraud_meta_box_type_for_order( $order, $fraud_meta_box_type ); } $this->attach_transaction_fee_to_order( $order, $intent->get_charge() ); $this->update_order_status( $order, 'payment_complete', $intent_id ); $order->add_order_note( $note ); $this->set_intention_status_for_order( $order, $intent->get_status() ); } /** * Leaves an order in pending status, while adding a note with a link to the transaction. * * @param WC_Order $order Order object. * @param array $intent_data The intent data associated with this order. * * @return void */ private function mark_payment_started( $order, $intent_data ) { $note = $this->generate_payment_started_note( $order, $intent_data['intent_id'] ); if ( $this->order_note_exists( $order, $note ) || ! $order->has_status( [ Order_Status::PENDING ] ) ) { return; } $fraud_meta_box_type = $this->intent_has_card_payment_type( $intent_data ) ? Fraud_Meta_Box_Type::PAYMENT_STARTED : Fraud_Meta_Box_Type::NOT_CARD; $this->set_fraud_meta_box_type_for_order( $order, $fraud_meta_box_type ); $order->add_order_note( $note ); $this->set_intention_status_for_order( $order, $intent_data['intent_status'] ); } /** * Changes status to On-Hold, adds fraud meta data, and adds the fraud held for review note. * * @param WC_Order $order Order object. * @param array $intent_data The intent data associated with this order. * * @return void */ private function mark_order_held_for_review_for_fraud( $order, $intent_data ) { $ruleset_results = $intent_data['fraud_ruleset_results'] ?? []; $note = $this->generate_fraud_held_for_review_note( $order, $intent_data['intent_id'], $intent_data['charge_id'], $ruleset_results ); if ( $this->order_note_exists( $order, $note ) ) { return; } if ( [] !== $ruleset_results ) { $this->set_fraud_ruleset_results_for_order( $order, $ruleset_results ); } $this->update_order_status( $order, Order_Status::ON_HOLD ); $this->set_fraud_outcome_status_for_order( $order, Rule::FRAUD_OUTCOME_REVIEW ); $this->set_fraud_meta_box_type_for_order( $order, Fraud_Meta_Box_Type::REVIEW ); $order->add_order_note( $note ); $this->set_intention_status_for_order( $order, $intent_data['intent_status'] ); } /** * Given the charge, adds the application_fee_amount from the charge to the given order as metadata. * * @param WC_Order $order The order to update. * @param WC_Payments_API_Charge|null $charge The charge to get the application_fee_amount from. */ public function attach_transaction_fee_to_order( $order, $charge ) { try { if ( ! $charge || ! $charge->is_captured() ) { return; } // FEE_BREAKDOWN_FORK_PATCH: remove when envelope is the only path. // Prefer the server-driven fee_breakdown_v1 envelope when present. // totals.fee.amount is authoritative for every merchant-facing // surface — the order page row, the _wcpay_net meta, and the // timeline all read from the same place. Falls back to the // legacy application_fee_amount inference for older servers. $fee_breakdown_v1 = $charge->get_fee_breakdown_v1(); if ( is_array( $fee_breakdown_v1 ) && isset( $fee_breakdown_v1['totals']['fee']['amount'], $fee_breakdown_v1['totals']['fee']['currency'] ) ) { $order->update_meta_data( self::WCPAY_TRANSACTION_FEE_META_KEY, WC_Payments_Utils::interpret_stripe_amount( (int) $fee_breakdown_v1['totals']['fee']['amount'], $fee_breakdown_v1['totals']['fee']['currency'] ) ); if ( isset( $fee_breakdown_v1['totals']['net']['amount'], $fee_breakdown_v1['totals']['net']['currency'] ) ) { $order->update_meta_data( '_wcpay_net', WC_Payments_Utils::interpret_stripe_amount( (int) $fee_breakdown_v1['totals']['net']['amount'], $fee_breakdown_v1['totals']['net']['currency'] ) ); } $order->save_meta_data(); return; } if ( null !== $charge->get_application_fee_amount() ) { $order->update_meta_data( self::WCPAY_TRANSACTION_FEE_META_KEY, WC_Payments_Utils::interpret_stripe_amount( $charge->get_application_fee_amount(), $charge->get_currency() ) ); $order->save_meta_data(); } } catch ( Exception $e ) { // Log the error and don't block checkout. Logger::log( 'Error saving transaction fee into metadata for the order ' . $order->get_id() . ': ' . $e->getMessage() ); } } /** * Cancels uncaptured authorizations on order cancel. * * @param int $order_id - Order ID. */ public function cancel_authorizations_on_order_status_change( $order_id ) { $order = new WC_Order( $order_id ); if ( null !== $order ) { $intent_id = $this->get_intent_id_for_order( $order ); if ( null !== $intent_id && '' !== $intent_id && ! in_array( $this->get_intention_status_for_order( $order ), self::TERMINAL_INTENT_STATUSES, true ) ) { try { $request = Get_Intention::create( $intent_id ); $request->set_hook_args( $order ); $intent = $request->send(); $charge = $intent->get_charge(); /** * Successful but not captured Charge is an authorization * that needs to be cancelled. */ if ( null !== $charge && false === $charge->is_captured() && Intent_Status::SUCCEEDED === $charge->get_status() && Intent_Status::REQUIRES_CAPTURE === $intent->get_status() ) { $request = Cancel_Intention::create( $intent_id ); $request->set_hook_args( $order ); $intent = $request->send(); $this->post_unique_capture_cancelled_note( $order, $intent_id, $charge->get_id() ); // Remove transaction fee since the authorization was canceled and no payment was processed. $order->delete_meta_data( self::WCPAY_TRANSACTION_FEE_META_KEY ); $order->delete_meta_data( '_wcpay_net' ); } $this->set_intention_status_for_order( $order, $intent->get_status() ); $order->save(); } catch ( \Exception $e ) { $order->add_order_note( WC_Payments_Utils::esc_interpolated_html( __( 'Canceling authorization <strong>failed</strong> to complete.', 'woocommerce-payments' ), [ 'strong' => '<strong>' ] ) ); } } } } /** * Handles the change of an order status. * * This function is triggered when the status of an order is changed. * It performs necessary actions based on the new status of the order. * * @param int $order_id The ID of the order. * @return void */ public function capture_authorization_on_order_status_change( int $order_id ) { // wc_get_order() returns false for a missing order, where `new WC_Order` throws. $order = wc_get_order( $order_id ); if ( $order instanceof WC_Order ) { $intent_id = $this->get_intent_id_for_order( $order ); if ( null !== $intent_id && '' !== $intent_id && ! in_array( $this->get_intention_status_for_order( $order ), self::TERMINAL_INTENT_STATUSES, true ) ) { try { $request = Get_Intention::create( $intent_id ); $request->set_hook_args( $order ); $intent = $request->send(); $charge = $intent->get_charge(); /** * Successful but not captured Charge is an authorization * that needs to be captured. */ if ( null !== $charge && false === $charge->is_captured() && Intent_Status::SUCCEEDED === $charge->get_status() && Intent_Status::REQUIRES_CAPTURE === $intent->get_status() ) { $request = Capture_Intention::create( $intent_id ); $request->set_amount_to_capture( WC_Payments_Utils::prepare_amount( $order->get_total(), $order->get_currency() ) ); // Without fresh Level 3 data, Stripe checks the capture against the data saved at // authorization and refuses an edited total. Same Level 3 rule as capture_charge(). if ( 'woocommerce_payments_amazon_pay' !== $order->get_payment_method() ) { $request->set_level3( wcpay_get_container()->get( Level3Service::class )->get_data_from_order( $order->get_id() ) ); } $request->set_hook_args( $order ); $intent = $request->send(); $this->post_unique_capture_complete_note( $order, $intent_id, $charge->get_id() ); $this->enqueue_add_fee_breakdown_to_order_notes( $order, $intent_id ); } $this->set_intention_status_for_order( $order, $intent->get_status() ); $order->save(); } catch ( \Exception $e ) { $order->add_order_note( WC_Payments_Utils::esc_interpolated_html( __( 'Capture authorization <strong>failed</strong> to complete.', 'woocommerce-payments' ), [ 'strong' => '<strong>' ] ) ); } } } } /** * Creates a refund for the given order. * * @param WC_Order $order The order to refund. * @param float $amount The amount to refund. * @param string $reason The reason for the refund. * @param array $line_items The line items to refund. * * @throws Exception If the refund creation fails. */ public function create_refund_for_order( WC_Order $order, float $amount, string $reason = '', array $line_items = [] ) { $refund_params = [ 'amount' => wc_format_decimal( $amount, wc_get_price_decimals() ), 'reason' => $reason, 'order_id' => $order->get_id(), ]; if ( $line_items ) { $refund_params['line_items'] = $line_items; } $refund = wc_create_refund( $refund_params ); if ( is_wp_error( $refund ) ) { throw new Exception( esc_html( $refund->get_error_message() ) ); } return $refund; } /** * Adds a note and metadata for a refund. * * @param WC_Order $order The order to refund. * @param WC_Order_Refund $wc_refund The WC refund object. * @param string $refund_id The refund ID. * @param string|null $refund_balance_transaction_id The balance transaction ID of the refund. * @param bool $is_pending Created refund status can be either pending or succeeded. Default false, i.e. succeeded. * @throws Order_Not_Found_Exception * @throws Exception */ public function add_note_and_metadata_for_created_refund( WC_Order $order, WC_Order_Refund $wc_refund, string $refund_id, ?string $refund_balance_transaction_id, bool $is_pending = false ): void { $note = $this->generate_payment_created_refund_note( $wc_refund->get_amount(), $wc_refund->get_currency(), $refund_id, $wc_refund->get_reason(), $order, $is_pending ); if ( ! $this->order_note_exists( $order, $note ) ) { $order->add_order_note( $note ); } // Use `successful` to maintain the backward compatibility with the previous WooPayments versions. $this->set_wcpay_refund_status_for_order( $order, $is_pending ? Refund_Status::PENDING : 'successful' ); $this->set_wcpay_refund_id_for_refund( $wc_refund, $refund_id ); if ( isset( $refund_balance_transaction_id ) ) { $this->set_wcpay_refund_transaction_id_for_order( $wc_refund, $refund_balance_transaction_id ); } $order->save(); } /** * Handle a failed refund by adding a note, updating metadata, and optionally deleting the refund. * * @param WC_Order $order The order to add the note to. * @param string $refund_id The ID of the failed refund. * @param int $amount The refund amount in cents. * @param string $currency The currency code. * @param WC_Order_Refund|null $wc_refund The WC refund object to delete if provided. * @param bool $is_cancelled Whether this is a cancellation rather than a failure. Default false. * @param string|null $failure_reason The reason for the refund failure. Default null. * @return void */ public function handle_failed_refund( WC_Order $order, string $refund_id, int $amount, string $currency, ?WC_Order_Refund $wc_refund = null, bool $is_cancelled = false, ?string $failure_reason = null ): void { // Delete the refund if it exists. if ( $wc_refund ) { $wc_refund->delete(); } $formatted_amount = WC_Payments_Explicit_Price_Formatter::get_explicit_price( wc_price( WC_Payments_Utils::interpret_stripe_amount( $amount, $currency ), [ 'currency' => strtoupper( $currency ) ] ), $order ); // Handle insufficient balance case first to avoid duplicate notes. if ( Refund_Failure_Reason::INSUFFICIENT_FUNDS === $failure_reason ) { $this->handle_insufficient_balance_for_refund( $order, $amount ); } else { $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1$s: the refund amount, %2$s: status (cancelled/unsuccessful), %3$s: WooPayments, %4$s: ID of the refund, %5$s: failure message or period */ __( 'A refund of %1$s was <strong>%2$s</strong> using %3$s (<code>%4$s</code>)%5$s', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'code' => '<code>', ] ), $formatted_amount, $is_cancelled ? __( 'cancelled', 'woocommerce-payments' ) : __( 'unsuccessful', 'woocommerce-payments' ), 'WooPayments', $refund_id, $is_cancelled ? '.' : ': ' . Refund_Failure_Reason::get_failure_message( $failure_reason ?? Refund_Failure_Reason::UNKNOWN ), ); if ( $this->order_note_exists( $order, $note ) ) { return; } $order->add_order_note( $note ); } // If order has been fully refunded, change status to failed. if ( Order_Status::REFUNDED === $order->get_status() ) { $order->update_status( Order_Status::FAILED ); } $this->set_wcpay_refund_status_for_order( $order, Refund_Status::FAILED ); $order->save(); } /** * Determines whether the order was paid while WooPayments was in test mode, based on the * mode persisted to the order meta at payment time. Reading from the order (never the * current global mode) keeps the determination correct across later mode switches and on * email resends. The order note this drives is a stored DB row that persists even after * WooPayments is deactivated; the email marker is applied by runtime filters, so it only * shows while the plugin is active. * * @param WC_Order $order Order object. * * @return bool */ private function is_order_in_test_mode( WC_Order $order ): bool { return Order_Mode::TEST === $order->get_meta( self::WCPAY_MODE_META_KEY ); } /** * Prefixes an order email subject or heading with the localized test-mode marker. * * @param string $text The subject or heading to prefix. * * @return string */ private function prepend_test_mode_email_marker( string $text ): string { /* translators: %s: the original email subject or heading. The leading "[Test]" flags an order paid in WooPayments test mode. */ return sprintf( __( '[Test] %s', 'woocommerce-payments' ), $text ); } /** * Get content for the success order note. * * @param string $intent_id The payment intent ID related to the intent/order. * @param string $charge_id The charge ID related to the intent/order. * @param string $formatted_amount The formatted order total. * * @return string Note content. */ private function generate_payment_success_note( $intent_id, $charge_id, $formatted_amount ) { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id ); return sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the successfully charged amount, %2: WooPayments, %3: transaction ID of the payment, %4: transaction details URL */ __( 'A payment of %1$s was <strong>successfully charged</strong> using %2$s (<a>%3$s</a>).', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%4$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $formatted_amount, 'WooPayments', WC_Payments_Utils::get_transaction_url_id( $intent_id, $charge_id ), $transaction_url ); } /** * Get content for the success order note when the payment was made in test mode. Kept * separate from generate_payment_success_note() so the production note stays untouched. * * @param string $intent_id The payment intent ID related to the intent/order. * @param string $charge_id The charge ID related to the intent/order. * @param string $formatted_amount The formatted order total. * * @return string Note content. */ private function generate_test_mode_payment_success_note( $intent_id, $charge_id, $formatted_amount ) { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id ); return sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the charged amount, %2: WooPayments, %3: transaction ID of the payment, %4: transaction details URL */ __( 'A test payment of %1$s was processed using %2$s in <strong>test mode</strong> (<a>%3$s</a>). No real funds were collected.', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%4$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $formatted_amount, 'WooPayments', WC_Payments_Utils::get_transaction_url_id( $intent_id, $charge_id ), $transaction_url ); } /** * Get content for the failure order note and additional message, if included. * * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * @param string $message Optional message to add to the note. * @param string $formatted_amount The formatted order total. * * @return string Note content. */ private function generate_payment_failure_note( $intent_id, $charge_id, $message, $formatted_amount ) { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id ); $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the authorized amount, %2: WooPayments, %3: transaction ID of the payment, %4: transaction details URL */ __( 'A payment of %1$s <strong>failed</strong> using %2$s (<a>%3$s</a>).', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%4$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $formatted_amount, 'WooPayments', WC_Payments_Utils::get_transaction_url_id( $intent_id, $charge_id ), $transaction_url ); if ( ! empty( $message ) ) { $note .= ' ' . $message; } return $note; } /** * Get content for the failure order note and additional message, if included. * * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * @param string $message Optional message to add to the note. * @param string $formatted_amount The formatted order total. * * @return string Note content. */ private function generate_terminal_payment_failure_note( $intent_id, $charge_id, $message, $formatted_amount ) { // Add charge_id to the transaction URL instead of intent_id for uniqueness. $transaction_url = WC_Payments_Utils::compose_transaction_url( '', $charge_id ); $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the authorized amount, %2: WooPayments, %3: transaction ID of the payment, %4: transaction details URL */ __( 'A terminal payment of %1$s <strong>failed</strong> using %2$s (<a>%3$s</a>)', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%4$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $formatted_amount, 'WooPayments', $intent_id ?? $charge_id, $transaction_url ); if ( ! empty( $message ) ) { $note .= ' ' . $message; } return $note; } /** * Generates the payment authorized order note. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * * @return string */ private function generate_payment_authorized_note( $order, $intent_id, $charge_id ): string { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id ); $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the authorized amount, %2: WooPayments, %3: transaction ID of the payment, %4: transaction details URL */ __( 'A payment of %1$s was <strong>authorized</strong> using %2$s (<a>%3$s</a>).', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%4$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $this->get_order_amount( $order ), 'WooPayments', WC_Payments_Utils::get_transaction_url_id( $intent_id, $charge_id ), $transaction_url ); return $note; } /** * Generates the payment started order note. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * * @return string */ private function generate_payment_started_note( $order, $intent_id ): string { $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the authorized amount, %2: WooPayments, %3: intent ID of the payment */ __( 'A payment of %1$s was <strong>started</strong> using %2$s (<code>%3$s</code>).', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'code' => '<code>', ] ), $this->get_order_amount( $order ), 'WooPayments', $intent_id ); return $note; } /** * Generates the successful capture order note. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * * @return string */ private function generate_capture_success_note( $order, $intent_id, $charge_id ) { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id ); $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the successfully charged amount, %2: WooPayments, %3: transaction ID of the payment, %4: transaction details URL */ __( 'A payment of %1$s was <strong>successfully captured</strong> using %2$s (<a>%3$s</a>).', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%4$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $this->get_order_amount( $order ), 'WooPayments', WC_Payments_Utils::get_transaction_url_id( $intent_id, $charge_id ), $transaction_url ); return $note; } /** * Generates the failure order note and additional message, if included. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * @param string $message Optional message to add to the note. * * @return string */ private function generate_capture_failed_note( $order, $intent_id, $charge_id, $message ): string { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id ); $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the authorized amount, %2: WooPayments, %3: transaction ID of the payment, %4: transaction details URL */ __( 'A capture of %1$s <strong>failed</strong> to complete using %2$s (<a>%3$s</a>).', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%4$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $this->get_order_amount( $order ), 'WooPayments', WC_Payments_Utils::get_transaction_url_id( $intent_id, $charge_id ), $transaction_url ); if ( ! empty( $message ) ) { $note .= ' ' . $message; } return $note; } /** * Get content for the capture expired note. * * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * * @return string Note content. */ private function generate_capture_expired_note( $intent_id, $charge_id ) { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id ); return sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: transaction ID of the payment, %2: transaction details URL */ __( 'Payment authorization has <strong>expired</strong> (<a>%1$s</a>).', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%2$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), WC_Payments_Utils::get_transaction_url_id( $intent_id, $charge_id ), $transaction_url ); } /** * Generates the capture cancelled order note. * * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * * @return string */ private function generate_capture_cancelled_note( $intent_id, $charge_id ): string { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id ); return sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: transaction ID of the payment, %2: transaction details URL */ __( 'Payment authorization was successfully <strong>cancelled</strong> (<a>%1$s</a>).', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => ! empty( $transaction_url ) ? '<a href="%2$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), WC_Payments_Utils::get_transaction_url_id( $intent_id, $charge_id ), $transaction_url ); } /** * Generates the fraud held for review order note. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * @param string $charge_id The charge ID related to the intent/order. * @param array $ruleset_results The risk filter results that held the payment for review, as a map of rule key => outcome. * * @return string */ private function generate_fraud_held_for_review_note( $order, $intent_id, $charge_id, array $ruleset_results = [] ): string { $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id, [ 'status_is' => Rule::FRAUD_OUTCOME_REVIEW, 'type_is' => 'order_note', ] ); return $this->generate_fraud_note( $order, $transaction_url, $ruleset_results, /* translators: %1: the amount held for review, %2: the list of risk filters that held the payment for review */ __( '⛔ A payment of %1$s was <strong>held for review</strong> by the following risk filters:<br>%2$s<br><br><a>View more details</a>.', 'woocommerce-payments' ), /* translators: %1: the amount held for review */ __( '⛔ A payment of %1$s was <strong>held for review</strong> by one or more risk filters.<br><br><a>View more details</a>.', 'woocommerce-payments' ) ); } /** * Generates the fraud blocked order note. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the payment intent that was blocked, when one exists. * @param array $ruleset_results The risk filter results that blocked the payment, as a map of rule key => outcome. * * @return string */ private function generate_fraud_blocked_note( $order, $intent_id, array $ruleset_results = [] ): string { // Key the link on the specific payment intent so each blocked attempt on an order points to // its own transaction; fall back to the order id for rule engine blocks, which have no intent. $transaction_url = WC_Payments_Utils::compose_transaction_url( $intent_id, (string) $order->get_id(), [ 'status_is' => Rule::FRAUD_OUTCOME_BLOCK, 'type_is' => 'order_note', ] ); return $this->generate_fraud_note( $order, $transaction_url, $ruleset_results, /* translators: %1: the blocked amount, %2: the list of risk filters that blocked the payment */ __( '🚫 A payment of %1$s was <strong>blocked</strong> by the following risk filters:<br>%2$s<br><br><a>View more details</a>.', 'woocommerce-payments' ), /* translators: %1: the blocked amount */ __( '🚫 A payment of %1$s was <strong>blocked</strong> by one or more risk filters.<br><br><a>View more details</a>.', 'woocommerce-payments' ) ); } /** * Builds the fraud blocked/held-for-review order note, choosing between a template listing the * fired risk filters and a generic fallback when none are known (e.g. card-testing-prevention * blocks, which carry no ruleset data). * * @param WC_Order $order Order object. * @param string $transaction_url Transaction details URL, or an empty string when none is available. * @param array $ruleset_results The risk filter results, as a map of rule key => outcome. * @param string $with_filters_template Translated template used when the fired risk filters are known. Takes the amount, the risk filter list, and the transaction URL, in that order. * @param string $generic_template Translated fallback template used when no risk filters are known. Takes the amount and the transaction URL, in that order. * * @return string */ private function generate_fraud_note( WC_Order $order, string $transaction_url, array $ruleset_results, string $with_filters_template, string $generic_template ): string { $labels = Fraud_Risk_Tools::get_ruleset_result_labels( $ruleset_results ); if ( [] !== $labels ) { $rules_list = '• ' . implode( '<br>• ', array_map( 'esc_html', $labels ) ); return sprintf( WC_Payments_Utils::esc_interpolated_html( $with_filters_template, [ 'strong' => '<strong>', 'br' => '<br>', 'a' => ! empty( $transaction_url ) ? '<a href="%3$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $this->get_order_amount( $order ), $rules_list, $transaction_url ); } return sprintf( WC_Payments_Utils::esc_interpolated_html( $generic_template, [ 'strong' => '<strong>', 'br' => '<br>', 'a' => ! empty( $transaction_url ) ? '<a href="%2$s" target="_blank" rel="noopener noreferrer">' : '<code>', ] ), $this->get_order_amount( $order ), $transaction_url ); } /** * Get content for the dispute created order note. * * @param string $charge_id The ID of the disputes charge associated with this order. * @param string $amount The disputed amount – formatted currency value. * @param string $reason The reason for the dispute – human-readable text. * @param string $due_by The deadline for responding to the dispute - formatted date string. * @param bool $is_inquiry Whether the dispute is an inquiry or not. * @param string $dispute_id The ID of the dispute, appended so a charge's several disputes each get a distinct note. * * @return string Note content. */ private function generate_dispute_created_note( $charge_id, $amount, $reason, $due_by, $is_inquiry = false, $dispute_id = '' ) { $dispute_url = $this->compose_dispute_url( $charge_id ); // Get merchant-friendly dispute reason description. $reason = WC_Payments_Utils::get_dispute_reason_description( $reason ); if ( $is_inquiry ) { $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the disputed amount and currency; %2: the dispute reason; %3 the deadline date for responding to the inquiry */ __( 'A payment inquiry has been raised for %1$s with reason "%2$s". <a>Response due by %3$s</a>.', 'woocommerce-payments' ), [ 'a' => '<a href="%4$s" target="_blank" rel="noopener noreferrer">', ] ), $amount, $reason, $due_by, $dispute_url ); } else { $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the disputed amount and currency; %2: the dispute reason; %3 the deadline date for responding to dispute */ __( 'Payment has been disputed for %1$s with reason "%2$s". <a>Response due by %3$s</a>.', 'woocommerce-payments' ), [ 'a' => '<a href="%4$s" target="_blank" rel="noopener noreferrer">', ] ), $amount, $reason, $due_by, $dispute_url ); } // A charge can carry several disputes with identical amount, reason and // deadline; without the dispute ID their notes are byte-identical and // order_note_exists() collapses them into one. It also keeps a // re-delivered webhook for the same dispute de-duplicated. if ( '' !== $dispute_id ) { $note .= ' ' . sprintf( /* translators: %s: the dispute ID */ esc_html__( '(Dispute ID: %s)', 'woocommerce-payments' ), esc_html( $dispute_id ) ); } return $note; } /** * Get content for the dispute closed order note. * * @param string $charge_id The ID of the disputed charge associated with this order. * @param string $status The status of the dispute. * @param bool $is_inquiry Whether the dispute is an inquiry or not. * @param string $dispute_id The ID of the dispute, appended so a charge's several disputes each get a distinct note. * * @return string Note content. */ private function generate_dispute_closed_note( $charge_id, $status, $is_inquiry = false, $dispute_id = '' ) { $dispute_url = $this->compose_dispute_url( $charge_id ); if ( $is_inquiry ) { $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the dispute status */ __( 'Payment inquiry has been closed with status %1$s. See <a>payment status</a> for more details.', 'woocommerce-payments' ), [ 'a' => '<a href="%2$s" target="_blank" rel="noopener noreferrer">', ] ), $status, $dispute_url ); } else { $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the dispute status */ __( 'Dispute has been closed with status %1$s. See <a>dispute overview</a> for more details.', 'woocommerce-payments' ), [ 'a' => '<a href="%2$s" target="_blank" rel="noopener noreferrer">', ] ), $status, $dispute_url ); } // Two disputes that close with the same status make identical note text, and // order_note_exists() dedups on it. That check also gates the refund, so without // the dispute ID the second lost dispute's refund just gets skipped. The ID keeps // each note (and its refund) distinct; a re-delivered webhook still de-dupes. if ( '' !== $dispute_id ) { $note .= ' ' . sprintf( /* translators: %s: the dispute ID */ esc_html__( '(Dispute ID: %s)', 'woocommerce-payments' ), esc_html( $dispute_id ) ); } return $note; } /** * Get content for the early fraud warning order note. * * @param string $charge_id The ID of the charge the early fraud warning relates to. * @param bool $actionable Whether the payment can still be refunded to prevent a dispute. * @param string $fraud_type The fraud type reported by the card network. * * @return string Note content. */ private function generate_early_fraud_warning_note( $charge_id, $actionable, $fraud_type ) { $transaction_url = WC_Payments_Utils::compose_transaction_url( '', $charge_id ); if ( ! $actionable ) { return sprintf( WC_Payments_Utils::esc_interpolated_html( __( 'The early fraud warning received for this payment is no longer actionable, because the payment was refunded or disputed. See <a>payment details</a> for more information.', 'woocommerce-payments' ), [ 'a' => '<a href="%1$s" target="_blank" rel="noopener noreferrer">', ] ), $transaction_url ); } // Get merchant-friendly fraud type description. $reason = WC_Payments_Utils::get_early_fraud_warning_fraud_type_description( $fraud_type ); // The refund phrase carries the `wcpay-efw-refund-link` class so admin // order JS can open WooCommerce's inline refund panel in place (see // client/order/index.js); the payment details href is its fallback. if ( '' === $reason ) { return sprintf( WC_Payments_Utils::esc_interpolated_html( __( 'Payment has received an early fraud warning. <refund>Refunding the payment now</refund> can prevent a dispute. See <a>payment details</a> for more information.', 'woocommerce-payments' ), [ 'refund' => '<a href="%1$s" class="wcpay-efw-refund-link" target="_blank" rel="noopener noreferrer">', 'a' => '<a href="%1$s" target="_blank" rel="noopener noreferrer">', ] ), $transaction_url ); } return sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the early fraud warning reason, e.g. "Made with stolen card" */ __( 'Payment has received an early fraud warning with reason "%1$s". <refund>Refunding the payment now</refund> can prevent a dispute. See <a>payment details</a> for more information.', 'woocommerce-payments' ), [ 'refund' => '<a href="%2$s" class="wcpay-efw-refund-link" target="_blank" rel="noopener noreferrer">', 'a' => '<a href="%2$s" target="_blank" rel="noopener noreferrer">', ] ), $reason, $transaction_url ); } /** * Generates the HTML note for a refunded payment. * * @param float $refunded_amount Amount refunded. * @param string $refunded_currency Refund currency. * @param string $wcpay_refund_id WCPay Refund ID. * @param string $refund_reason Refund reason. * @param WC_Order $order Order object. * @param bool $is_pending Created refund status can be either pending or succeeded. Default false, i.e. succeeded. * * @return string HTML note. */ private function generate_payment_created_refund_note( float $refunded_amount, string $refunded_currency, string $wcpay_refund_id, string $refund_reason, WC_Order $order, bool $is_pending ): string { $multi_currency_instance = WC_Payments_Multi_Currency(); $formatted_price = WC_Payments_Explicit_Price_Formatter::get_explicit_price( $multi_currency_instance->get_backend_formatted_wc_price( $refunded_amount, [ 'currency' => strtoupper( $refunded_currency ) ] ), $order ); $status_text = $is_pending ? sprintf( '<a href="https://woocommerce.com/document/woopayments/managing-money/#pending-refunds" target="_blank" rel="noopener noreferrer">%1$s</a>', __( 'is pending', 'woocommerce-payments' ) ) : __( 'was successfully processed', 'woocommerce-payments' ); if ( empty( $refund_reason ) ) { $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the refund amount, %2: WooPayments, %3: ID of the refund, %4: status text */ __( 'A refund of %1$s %4$s using %2$s (<code>%3$s</code>).', 'woocommerce-payments' ), [ 'code' => '<code>', ] ), $formatted_price, 'WooPayments', $wcpay_refund_id, $status_text ); } else { $note = sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1: the refund amount, %2: WooPayments, %3: reason, %4: refund id, %5: status text */ __( 'A refund of %1$s %5$s using %2$s. Reason: %3$s. (<code>%4$s</code>)', 'woocommerce-payments' ), [ 'code' => '<code>', ] ), $formatted_price, 'WooPayments', $refund_reason, $wcpay_refund_id, $status_text ); } return $note; } /** * Composes url for dispute details page. * * @param string $charge_id The disputed charge ID. * * @return string Transaction details page url. */ private function compose_dispute_url( $charge_id ) { return add_query_arg( [ 'page' => 'wc-admin', 'path' => rawurlencode( '/payments/transactions/details' ), 'id' => $charge_id, ], admin_url( 'admin.php' ) ); } /** * Check if order is locked for payment processing * * @param WC_Order $order The order that is being paid. * @param string $intent_id The id of the intent that is being processed. * * @return bool A flag that indicates whether the order is already locked. */ private function is_order_locked( $order, $intent_id = null ) { $order_id = $order->get_id(); $transient_name = 'wcpay_processing_intent_' . $order_id; $processing = get_transient( $transient_name ); // Block the process if the same intent is already being handled. return ( '-1' === $processing || ( isset( $intent_id ) && $processing === $intent_id ) ); } /** * Lock an order for payment intent processing for 5 minutes. * * @param WC_Order $order The order that is being paid. * @param string $intent_id The id of the intent that is being processed. * * @return void */ private function lock_order_payment( $order, $intent_id = null ) { $order_id = $order->get_id(); $transient_name = 'wcpay_processing_intent_' . $order_id; set_transient( $transient_name, empty( $intent_id ) ? '-1' : $intent_id, 5 * MINUTE_IN_SECONDS ); } /** * Unlocks an order for processing by payment intents. * * @param WC_Order $order The order that is being unlocked. * * @return void */ private function unlock_order_payment( $order ) { $order_id = $order->get_id(); delete_transient( 'wcpay_processing_intent_' . $order_id ); } /** * Refreshes the order from the database, checks if it is locked, and locks it. * * TODO: Update to throw exceptions so try/catch can be used. * TODO: Maybe add checks to see if there is already a successful intent, or the intent status passed is already set. * * @param WC_Order $order Order object. * @param string $intent_id The ID of the intent associated with this order. * * @return bool */ private function order_prepared_for_processing( $order, $intent_id ) { if ( ! is_a( $order, 'WC_Order' ) ) { return false; } if ( $this->is_order_paid( $order ) ) { return false; } if ( $this->is_order_locked( $order, $intent_id ) ) { return false; } // Lock the order. $this->lock_order_payment( $order, $intent_id ); return true; } /** * Checks whether the order has already been refunded in full. * * @param WC_Order $order The order being checked. * * @return bool True if the whole order total has been refunded, false otherwise. */ private function is_order_fully_refunded( WC_Order $order ): bool { // Two independent clauses: has_status() catches WooCommerce's standard // fully-refunded transition, the remaining-amount check catches stores that // redirect it via woocommerce_order_fully_refunded_status, plus over-refunds. // The total clamp guards only the second clause, since on a zero-total order // (free / 100% coupon) the remaining amount is trivially 0. return $order->has_status( Order_Status::REFUNDED ) || ( (float) $order->get_total() > 0 && (float) $order->get_remaining_refund_amount() <= 0 ); } /** * Reads the IDs of the charge's disputes that have not closed yet. * * @param WC_Order $order The order the disputed charge belongs to. * * @return string[] The open dispute IDs, empty when none were ever recorded. */ private function get_open_dispute_ids( WC_Order $order ): array { $open_dispute_ids = $order->get_meta( self::WCPAY_OPEN_DISPUTE_IDS_META_KEY, true ); return is_array( $open_dispute_ids ) ? array_values( $open_dispute_ids ) : []; } /** * Records a dispute as open on the order. Does not save the order. * * @param WC_Order $order The order the disputed charge belongs to. * @param string $dispute_id The ID of the dispute that was created. * * @return void */ private function add_open_dispute_id( WC_Order $order, string $dispute_id ) { if ( empty( $dispute_id ) ) { return; } $open_dispute_ids = $this->get_open_dispute_ids( $order ); if ( in_array( $dispute_id, $open_dispute_ids, true ) ) { return; } $open_dispute_ids[] = $dispute_id; $order->update_meta_data( self::WCPAY_OPEN_DISPUTE_IDS_META_KEY, $open_dispute_ids ); } /** * Drops a dispute from the order's open list and reports which disputes are left. * * @param WC_Order $order The order the disputed charge belongs to. * @param string $dispute_id The ID of the dispute that closed. * * @return string[] The disputes still open on the charge. */ private function close_open_dispute_id( WC_Order $order, string $dispute_id ): array { // Without an ID there is no telling which of the charge's disputes just closed, so // leave the record untouched and report nothing open. Callers still on the older // signature — and orders whose disputes predate this bookkeeping — keep the // behaviour they had before. if ( '' === $dispute_id ) { return []; } $open_dispute_ids = $this->get_open_dispute_ids( $order ); $remaining = array_values( array_diff( $open_dispute_ids, [ $dispute_id ] ) ); if ( $remaining === $open_dispute_ids ) { return $remaining; } if ( empty( $remaining ) ) { $order->delete_meta_data( self::WCPAY_OPEN_DISPUTE_IDS_META_KEY ); } else { $order->update_meta_data( self::WCPAY_OPEN_DISPUTE_IDS_META_KEY, $remaining ); } // Nothing further down this method is guaranteed to save the order: the lost branch // refunds through a separate order instance and the sibling-open branch changes no // status at all. $order->save(); return $remaining; } /** * Checks to see if the current order, and a fresh copy of the order from the database are paid. * * @param WC_Order $order The order being checked. * * @return boolean True if it has a paid status, false if not. */ private function is_order_paid( $order ) { // Read the latest order properties from the database to avoid race conditions if webhook was handled during this request. $clone_order = $this->get_stored_order( $order ); // Check if the order is already complete. if ( function_exists( 'wc_get_is_paid_statuses' ) ) { if ( $order->has_status( wc_get_is_paid_statuses() ) || $clone_order->has_status( wc_get_is_paid_statuses() ) ) { return true; } } return false; } /** * Reads a copy of the order as currently stored, bypassing the post cache, so that changes made * by another request after this one loaded the order are visible. * * @param WC_Order $order The order to read. * * @return WC_Order A copy of the order with the stored properties. */ private function get_stored_order( WC_Order $order ): WC_Order { wp_cache_delete( $order->get_id(), 'posts' ); $stored_order = clone $order; $stored_order->get_data_store()->read( $stored_order ); return $stored_order; } /** * Completes order processing by updating the intent meta, unlocking the order, and saving the order. * * @param WC_Order $order Order object. * @param string|null $intent_status The status of the intent related to this order. * * @return void */ private function complete_order_processing( $order, $intent_status = null ) { if ( ! empty( $intent_status ) ) { $this->set_intention_status_for_order( $order, $intent_status ); } $this->unlock_order_payment( $order ); $order->save(); } /** * Gets the total for the order in explicit format. * * @param WC_Order $order Order object. * * @return string The formatted order total. */ private function get_order_amount( $order ) { $multi_currency_instance = WC_Payments_Multi_Currency(); $order_price = $order->get_total(); $formatted_price = $multi_currency_instance->get_backend_formatted_wc_price( $order_price, [ 'currency' => $order->get_currency() ] ); return WC_Payments_Explicit_Price_Formatter::get_explicit_price( $formatted_price, $order ); } /** * Updates the order status and catches any exceptions so that processing can continue. * * @param WC_Order $order Order object. * @param string $order_status The status to change the order to. * @param null|string $intent_id The ID of the intent associated with this order. * * @throws Exception Throws exception if intent id is not included if order needs to be marked as paid. * * @return void */ private function update_order_status( $order, $order_status, $intent_id = '' ) { try { /** * In this instance payment_complete is not an order status, but a flag to mark the order as paid. In a default WooCommerce store, the order * may move to Processing or Completed status depending on the contents of the cart, so we let WooCommerce core decide what to do. */ if ( 'payment_complete' === $order_status ) { if ( empty( $intent_id ) ) { throw new Exception( __( 'Intent id was not included for payment complete status change.', 'woocommerce-payments' ) ); } $order->payment_complete( $intent_id ); } else { $order->update_status( $order_status ); } } catch ( Exception $e ) { // Continue further, something unexpected happened, but we can't really do anything with that. Logger::log( 'Error when updating status for order ' . $order->get_id() . ': ' . $e->getMessage() ); } } /** * Takes an intent object or array and returns our needed data as an array. * This is needed due to intents can either be objects or arrays. * * @param WC_Payments_API_Abstract_Intention $intent Setup or payment intent to pull the data from. * * @return array The data we need to continue processing. */ private function get_intent_data( WC_Payments_API_Abstract_Intention $intent ): array { $intent_data = [ 'intent_id' => $intent->get_id(), 'intent_status' => $intent->get_status(), 'charge_id' => '', 'fraud_outcome' => $intent->get_metadata()['fraud_outcome'] ?? '', // The server stores the fired risk filters in the intent metadata as a JSON string, alongside `fraud_outcome`. 'fraud_ruleset_results' => $this->decode_ruleset_results( (string) ( $intent->get_metadata()['fraud_ruleset_results'] ?? '' ) ), 'payment_method_type' => $intent->get_payment_method_type(), ]; if ( $intent instanceof WC_Payments_API_Payment_Intention ) { $charge = $intent->get_charge(); $intent_data['charge_id'] = $charge ? $charge->get_id() : null; $intent_data['error'] = $intent->get_last_payment_error(); } return $intent_data; } /** * Decodes a JSON-encoded map of rule key => outcome, e.g. from order or intent metadata. * * @param string $json The JSON-encoded ruleset results, or an empty string when none are stored. * * @return array The decoded ruleset results. Empty when the input isn't a valid JSON array. */ private function decode_ruleset_results( string $json ): array { $results = json_decode( $json, true ); return is_array( $results ) ? $results : []; } /** * Schedules an action to add the fee breakdown to order notes. * * @param WC_Order $order The order to add the note to. * @param string $intent_id The intent ID for the order. * * @return void */ private function enqueue_add_fee_breakdown_to_order_notes( WC_Order $order, string $intent_id ) { WC_Payments::get_action_scheduler_service()->schedule_job( time(), self::ADD_FEE_BREAKDOWN_TO_ORDER_NOTES, [ 'order_id' => $order->get_id(), 'intent_id' => $intent_id, 'is_test_mode' => WC_Payments::mode()->is_test(), ] ); } /** * If an order object is passed in, return that, else try to get the order. * This is needed due to mocked orders cannot be retrieved from the database in tests. * * @param mixed $order The order to be returned. * * @return WC_Order|WC_Order_Refund * * @throws Order_Not_Found_Exception */ private function get_order( $order ) { $order = $this->is_order_type_object( $order ) ? $order : wc_get_order( $order ); if ( ! $this->is_order_type_object( $order ) ) { throw new Order_Not_Found_Exception( esc_html__( 'The requested order was not found.', 'woocommerce-payments' ), 'order_not_found' ); } return $order; } /** * Checks to see if the given argument is an order type object. * * @param mixed $order The order to be checked. * * @return bool */ private function is_order_type_object( $order ): bool { if ( is_a( $order, 'WC_Order' ) || is_a( $order, 'WC_Order_Refund' ) ) { return true; } return false; } /** * Checks to see if the intent data has just card set as the payment method type. * * @param array $intent_data The intent data obtained from get_intent_data. * * @return bool */ private function intent_has_card_payment_type( $intent_data ): bool { return isset( $intent_data['payment_method_type'] ) && 'card' === $intent_data['payment_method_type']; } /** * Countries where FROD balance is not supported. * * @var array */ const FROD_UNSUPPORTED_COUNTRIES = [ 'HK', 'SG', 'AE' ]; /** * Handle insufficient balance for refund. * * @param WC_Order $order The order being refunded. * @param int $stripe_amount The refund amount. */ public function handle_insufficient_balance_for_refund( WC_Order $order, int $stripe_amount ) { $account_country = WC_Payments::get_account_service()->get_account_country(); $formatted_amount = wc_price( WC_Payments_Utils::interpret_stripe_amount( $stripe_amount, $order->get_currency() ), [ 'currency' => $order->get_currency() ] ); if ( $this->is_frod_supported( $account_country ) ) { $order->add_order_note( $this->get_frod_support_note( $formatted_amount ) ); } else { $order->add_order_note( $this->get_insufficient_balance_note( $formatted_amount ) ); } } /** * Attach Multibanco information to the order. * * @param WC_Order $order The order being paid. * @param string $reference The Multibanco reference. * @param string $entity The Multibanco entity. * @param string $url The Multibanco URL. * @param int $expiry The Multibanco expiry. */ public function attach_multibanco_info_to_order( WC_Order $order, string $reference, string $entity, string $url, int $expiry ): void { $order->update_meta_data( self::WCPAY_MULTIBANCO_REFERENCE_META_KEY, $reference ); $order->update_meta_data( self::WCPAY_MULTIBANCO_ENTITY_META_KEY, $entity ); $order->update_meta_data( self::WCPAY_MULTIBANCO_URL_META_KEY, $url ); $order->update_meta_data( self::WCPAY_MULTIBANCO_EXPIRY_META_KEY, $expiry ); } /** * Get Multibanco information from the order. * * @param WC_Order $order The order. * @return array */ public function get_multibanco_info_from_order( WC_Order $order ): array { return [ 'reference' => $order->get_meta( self::WCPAY_MULTIBANCO_REFERENCE_META_KEY ), 'entity' => $order->get_meta( self::WCPAY_MULTIBANCO_ENTITY_META_KEY ), 'url' => $order->get_meta( self::WCPAY_MULTIBANCO_URL_META_KEY ), 'expiry' => $order->get_meta( self::WCPAY_MULTIBANCO_EXPIRY_META_KEY ), ]; } /** * Store payment method details in the order meta. * * @param WC_Order $order The order. * @param array $payment_method_details The payment method details. * @return void */ public function store_payment_method_details( WC_Order $order, array $payment_method_details ): void { $order->update_meta_data( self::PAYMENT_METHOD_DETAILS_META_KEY, wp_json_encode( $payment_method_details ) ); $order->save_meta_data(); } /** * Get cached payment method details from the order meta. * * @param WC_Order $order The order. * @return array The payment method details. */ public function get_payment_method_details( WC_Order $order ): ?array { $json = $order->get_meta( self::PAYMENT_METHOD_DETAILS_META_KEY ); if ( '' === $json ) { return null; } return json_decode( $json, true ); } /** * Check if FROD is supported for the given country. * * @param string $country_code Two-letter country code. * @return bool */ private function is_frod_supported( $country_code ) { return ! in_array( $country_code, self::FROD_UNSUPPORTED_COUNTRIES, true ); } /** * Get the order note for FROD supported countries. * * @param string $formatted_amount The formatted refund amount. * @return string */ private function get_frod_support_note( $formatted_amount ) { $learn_more_url = 'https://woocommerce.com/document/woopayments/fees/preventing-negative-balances/#adding-funds'; return sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %s: Formatted refund amount */ __( 'Refund of %s <strong>failed</strong> due to insufficient funds in your WooPayments balance. To prevent delays in refunding customers, please consider adding funds to your Future Refunds or Disputes (FROD) balance. <a>Learn more</a>.', 'woocommerce-payments' ), [ 'strong' => '<strong>', 'a' => '<a href="' . $learn_more_url . '" target="_blank" rel="noopener noreferrer">', ] ), $formatted_amount ); } /** * Get the order note for countries without FROD support. * * @param string $formatted_amount The formatted refund amount. * @return string */ private function get_insufficient_balance_note( $formatted_amount ) { return sprintf( WC_Payments_Utils::esc_interpolated_html( /* translators: %1$s: Formatted refund amount */ __( 'Refund of %1$s <strong>failed</strong> due to insufficient funds in your WooPayments balance.', 'woocommerce-payments' ), [ 'strong' => '<strong>', ] ), $formatted_amount ); } }
Save File
Cancel