get_transaction_manager(); /** @var WC_Order $order */ $order = wc_get_order( $order_id ); // Get meta multisafepay_transaction_id $multisafepay_transaction_id = $order->get_meta( 'multisafepay_transaction_id', true ); /** @var TransactionResponse $multisafepay_transaction */ $multisafepay_transaction = $transaction_manager->get( ! empty( $multisafepay_transaction_id ) ? $multisafepay_transaction_id : $order->get_order_number() ); if ( $multisafepay_transaction->requiresShoppingCart() ) { /** @var RefundRequest $refund_request */ $refund_request = $transaction_manager->createRefundRequest( $multisafepay_transaction ); $refunds = $order->get_refunds(); $refund_merchant_item_id = reset( $refunds )->id; $cart_item = new CartItem(); $cart_item->addName( __( 'Refund', 'multisafepay' ) ) ->addQuantity( 1 ) ->addUnitPrice( MoneyUtil::create_money( (float) $amount, $order->get_currency() )->negative() ) ->addMerchantItemId( 'refund_id_' . $refund_merchant_item_id ) ->addTaxRate( 0 ); $refund_request->getCheckoutData()->addItem( $cart_item ); } if ( ! $multisafepay_transaction->requiresShoppingCart() ) { $refund_request = new RefundRequest(); $refund_request->addDescriptionText( $reason ); $refund_request->addMoney( MoneyUtil::create_money( (float) $amount, $order->get_currency() ) ); } try { $error = null; $transaction_manager->refund( $multisafepay_transaction, $refund_request ); } catch ( Exception | ClientExceptionInterface | ApiException $exception ) { $error = __( 'Error:', 'multisafepay' ) . htmlspecialchars( $exception->getMessage() ); $this->logger->log_error( 'Error during refund: ' . $error . ' Refund request : ' . wp_json_encode( $refund_request->getData() ) ); } if ( ! $error ) { /* translators: %1$: The currency code. %2$ The transaction amount */ $note = sprintf( __( 'Refund of %1$s%2$s has been processed successfully.', 'multisafepay' ), get_woocommerce_currency_symbol( $order->get_currency() ), $amount ); $this->logger->log_info( $note ); $order->add_order_note( $note ); return true; } if ( get_option( 'multisafepay_debugmode', false ) ) { /* translators: %1$: The order ID. %2$ The PSP transaction ID */ $message = sprintf( __( 'Refund for Order ID: %1$s with transactionId: %2$s gives message: %3$s.', 'multisafepay' ), $order_id, $multisafepay_transaction->getTransactionId(), $error ); $this->logger->log_warning( $message ); } return false; } }