Skip to content

Instantly share code, notes, and snippets.

@BrianHenryIE
Last active September 6, 2021 06:56
Show Gist options
  • Save BrianHenryIE/22e2bd26972c92551ebe3033cd244261 to your computer and use it in GitHub Desktop.
Save BrianHenryIE/22e2bd26972c92551ebe3033cd244261 to your computer and use it in GitHub Desktop.
<?php
/**
* When the PayPal IPN is called, we'll replace the WC_Order class with a subclass that performs a currency conversion.
*
* NB: untested.
*
* @author BrianHenryIE
*/
/**
* @see WC_Gateway_Paypal_IPN_Handler::get_paypal_order()
*
* @hooked valid-paypal-standard-ipn-request
*
* @param array $posted `wp_unslash( $_POST )`
*/
function use_currency_conversion_order_subclass_for_paypal_ipn( $posted ): void {
if ( ! class_exists(My_PayPal_Currency_Conversion_WC_Order::class ) ) {
class My_PayPal_Currency_Conversion_WC_Order extends WC_Order
{
public function get_total( $context = 'view' )
{
$local_currency_total = parent::get_total( $context );
$exchange_rate = 1.23;
$euro_total = $local_currency_total * $exchange_rate;
return $euro_total;
}
}
}
/**
* When `wc_get_order()` is called, substitute the class.
*
* @see WC_Order_Factory::get_order();
* @see wc_get_order()
*
* @param string|false $classname
* @param bool|array $order_type Details about the order type.
* @param int|bool $order_id
*/
$substitute_class = function ( $classname, $order_type, $order_id ) {
static $returned = false;
if( ! $returned ) {
$returned = true;
return My_PayPal_Currency_Conversion_WC_Order::class;
}
return WC_Order::class;
};
add_filter( 'woocommerce_order_class', $substitute_class, 10, 3);
// If the static flag above doesn't work, this should be run as soon as possible after the change is no longer needed:
// remove_filter( 'woocommerce_order_class', $substitute_class );
}
/**
* Hook in before `::valid_response()` which calls `::get_paypal_order()` which uses `wc_get_order()`.
*
* @see WC_Gateway_Paypal_IPN_Handler
* @see WC_Gateway_Paypal_IPN_Handler::check_response()
* @see WC_Gateway_Paypal_IPN_Handler::valid_response()
* @see WC_Gateway_Paypal_IPN_Handler::get_paypal_order()
*/
add_action( 'valid-paypal-standard-ipn-request', 'use_currency_conversion_order_subclass_for_paypal_ipn', 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment