declare( strict_types = 1 );
namespace Automattic\WooCommerce\StoreApi\Utilities;
use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFields;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Utilities\DiscountsUtil;
use Automattic\WooCommerce\Utilities\ShippingUtil;
use Automattic\WooCommerce\StoreApi\Utilities\LocalPickupUtils;
use Automattic\WooCommerce\StoreApi\Utilities\PaymentUtils;
use Automattic\WooCommerce\StoreApi\Utilities\ArrayUtils;
use Automattic\WooCommerce\Utilities\ArrayUtil;
* Helper class which creates and syncs orders with the cart.
* Checkout fields controller.
private CheckoutFields $additional_fields_controller;
public function __construct() {
$this->additional_fields_controller = Package::container()->get( CheckoutFields::class );
* Create order and set props based on global settings.
* @throws RouteException Exception if invalid data is detected.
* @return \WC_Order A new order object.
public function create_order_from_cart() {
if ( wc()->cart->is_empty() ) {
throw new RouteException(
'woocommerce_rest_cart_empty',
__( 'Cannot create order from empty cart.', 'woocommerce' ),
add_filter( 'woocommerce_default_order_status', array( $this, 'default_order_status' ) );
$order = new \WC_Order();
$order->set_status( 'checkout-draft' );
$order->set_created_via( 'store-api' );
$this->update_order_from_cart( $order );
remove_filter( 'woocommerce_default_order_status', array( $this, 'default_order_status' ) );
* Update an order using data from the current cart.
* @param \WC_Order $order The order object to update.
* @param boolean $update_totals Whether to update totals or not.
public function update_order_from_cart( \WC_Order $order, $update_totals = true ) {
* This filter ensures that local pickup locations are still used for order taxes by forcing the address used to
* calculate tax for an order to match the current address of the customer.
* - The method `$customer->get_taxable_address()` runs the filter `woocommerce_customer_taxable_address`.
* - While we have a session, our `ShippingController::filter_taxable_address` function uses this hook to set
* the customer address to the pickup location address if local pickup is the chosen method.
* Without this code in place, `$customer->get_taxable_address()` is not used when order taxes are calculated,
* resulting in the wrong taxes being applied with local pickup.
* The alternative would be to instead use `woocommerce_order_get_tax_location` to return the pickup location
* address directly, however since we have the customer filter in place we don't need to duplicate effort.
* @see \WC_Abstract_Order::get_tax_location()
'woocommerce_order_get_tax_location',
if ( ! is_null( wc()->customer ) ) {
$taxable_address = wc()->customer->get_taxable_address();
'country' => $taxable_address[0],
'state' => $taxable_address[1],
'postcode' => $taxable_address[2],
'city' => $taxable_address[3],
// Ensure cart is current.
wc()->cart->calculate_totals();
// Update the current order to match the current cart.
$this->update_line_items_from_cart( $order );
$this->update_addresses_from_cart( $order );
$order->set_currency( get_woocommerce_currency() );
$order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) );
$order->set_customer_id( get_current_user_id() );
$order->set_customer_ip_address( \WC_Geolocation::get_ip_address() );
$order->set_customer_user_agent( wc_get_user_agent() );
$order->set_payment_method( PaymentUtils::get_default_payment_method() );
$order->update_meta_data( 'is_vat_exempt', wc_bool_to_string( wc()->cart->get_customer()->get_is_vat_exempt() ) );
$order->calculate_totals();
* Copies order data to customer object (not the session), so values persist for future checkouts.
* @param \WC_Order $order Order object.
public function sync_customer_data_with_order( \WC_Order $order ) {
if ( $order->get_customer_id() ) {
$customer = new \WC_Customer( $order->get_customer_id() );
'billing_first_name' => $order->get_billing_first_name(),
'billing_last_name' => $order->get_billing_last_name(),
'billing_company' => $order->get_billing_company(),
'billing_address_1' => $order->get_billing_address_1(),
'billing_address_2' => $order->get_billing_address_2(),
'billing_city' => $order->get_billing_city(),
'billing_state' => $order->get_billing_state(),
'billing_postcode' => $order->get_billing_postcode(),
'billing_country' => $order->get_billing_country(),
'billing_email' => $order->get_billing_email(),
'billing_phone' => $order->get_billing_phone(),
'shipping_first_name' => $order->get_shipping_first_name(),
'shipping_last_name' => $order->get_shipping_last_name(),
'shipping_company' => $order->get_shipping_company(),
'shipping_address_1' => $order->get_shipping_address_1(),
'shipping_address_2' => $order->get_shipping_address_2(),
'shipping_city' => $order->get_shipping_city(),
'shipping_state' => $order->get_shipping_state(),
'shipping_postcode' => $order->get_shipping_postcode(),
'shipping_country' => $order->get_shipping_country(),
'shipping_phone' => $order->get_shipping_phone(),
$this->additional_fields_controller->sync_customer_additional_fields_with_order( $order, $customer );
* Final validation ran before payment is taken.
* By this point we have an order populated with customer data and items.
* @throws RouteException Exception if invalid data is detected.
* @param \WC_Order $order Order object.
public function validate_order_before_payment( \WC_Order $order ) {
$needs_shipping = wc()->cart->needs_shipping();
$chosen_shipping_methods = wc()->session->get( 'chosen_shipping_methods', [] );
$this->validate_coupons( $order );
$this->validate_email( $order );
$this->validate_selected_shipping_methods( $needs_shipping, $chosen_shipping_methods );
$this->validate_addresses( $order, $needs_shipping );
// Perform custom validations.
$this->perform_custom_order_validation( $order );
* Final validation for existing orders, ran before payment is taken.
* By this point we have an order populated with customer data and items.
* Since the cart is not involved, we don't validate shipping methods and assume the order already
* contains the correct shipping items.
* @throws RouteException Exception if invalid data is detected.
* @param \WC_Order $order Order object.
public function validate_existing_order_before_payment( \WC_Order $order ) {
$needs_shipping = $order->needs_shipping();
$this->validate_coupons( $order, true );
$this->validate_email( $order );
$this->validate_addresses( $order, $needs_shipping );
// Perform custom validations.
$this->perform_custom_order_validation( $order );
* Perform custom order validation via WooCommerce hooks.
* Allows plugins to perform custom validation before payment.
* @param \WC_Order $order Order object.
* @throws RouteException Exception if validation fails.
protected function perform_custom_order_validation( \WC_Order $order ) {
$validation_errors = new \WP_Error();
* Allow plugins to perform custom validation before payment.
* Plugins can add errors to the $validation_errors object.
* @param \WC_Order $order The order object.
* @param \WP_Error $validation_errors WP_Error object to add custom errors to.
do_action( 'woocommerce_checkout_validate_order_before_payment', $order, $validation_errors );
// Check if there are any errors after custom validation.
if ( $validation_errors->has_errors() ) {
throw new RouteException(
'woocommerce_rest_checkout_custom_validation_error',
esc_html( implode( ' ', $validation_errors->get_error_messages() ) ),
* Convert a coupon code to a coupon object.
* @param string $coupon_code Coupon code.
* @return \WC_Coupon Coupon object.
protected function get_coupon( $coupon_code ) {
return new \WC_Coupon( $coupon_code );
* Validate coupons applied to the order and remove those that are not valid.
* @throws RouteException Exception if invalid data is detected.
* @param \WC_Order $order Order object.
* @param bool $use_order_data Whether to use order data or cart data.
protected function validate_coupons( \WC_Order $order, bool $use_order_data = false ) {
$coupon_codes = $order->get_coupon_codes();
$coupons = array_filter( array_map( array( $this, 'get_coupon' ), $coupon_codes ) );
$validators = array( 'validate_coupon_email_restriction', 'validate_coupon_usage_limit' );
$coupon_errors = array();
foreach ( $coupons as $coupon ) {
function ( $validator, $index, $params ) {
call_user_func_array( array( $this, $validator ), $params );
} catch ( Exception $error ) {
$coupon_errors[ $coupon->get_code() ] = $error->getMessage();
// Remove all coupons that were not valid.
$error_code = 'woocommerce_rest_order_coupon_errors';
foreach ( $coupon_errors as $coupon_code => $message ) {
$order->remove_coupon( $coupon_code );
$order->calculate_totals();
$error_code = 'woocommerce_rest_cart_coupon_errors';
foreach ( $coupon_errors as $coupon_code => $message ) {
wc()->cart->remove_coupon( $coupon_code );
wc()->cart->calculate_totals();
// Re-sync order with cart.
$this->update_order_from_cart( $order );
// Return exception so customer can review before payment.
if ( 1 === count( $coupon_errors ) && $use_order_data ) {
$error_message = sprintf(
/* translators: %1$s Coupon codes, %2$s Reason */
__( '"%1$s" was removed from the order. %2$s', 'woocommerce' ),
array_keys( $coupon_errors )[0],
array_values( $coupon_errors )[0],
} elseif ( 1 === count( $coupon_errors ) ) {
$error_message = sprintf(
/* translators: %1$s Coupon codes, %2$s Reason */
__( '"%1$s" was removed from the cart. %2$s', 'woocommerce' ),
array_keys( $coupon_errors )[0],
array_values( $coupon_errors )[0],
} elseif ( $use_order_data ) {
$error_message = sprintf(
/* translators: %s Coupon codes. */
__( 'Invalid coupons were removed from the order: "%s"', 'woocommerce' ),
implode( '", "', array_keys( $coupon_errors ) )
$error_message = sprintf(
/* translators: %s Coupon codes. */
__( 'Invalid coupons were removed from the cart: "%s"', 'woocommerce' ),
implode( '", "', array_keys( $coupon_errors ) )
throw new RouteException( $error_code, $error_message, 409, array( 'removed_coupons' => $coupon_errors ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
* Validates the customer email. This is a required field.
* @throws RouteException Exception if invalid data is detected.
* @param \WC_Order $order Order object.
protected function validate_email( \WC_Order $order ) {
$email = $order->get_billing_email();
throw new RouteException(
'woocommerce_rest_missing_email_address',
__( 'A valid email address is required', 'woocommerce' ),
if ( ! is_email( $email ) ) {
throw new RouteException(
'woocommerce_rest_invalid_email_address',
/* translators: %s provided email. */
__( 'The provided email address (%s) is not valid—please provide a valid email address', 'woocommerce' ),
* Validates customer address data based on the locale to ensure required fields are set.
* @throws RouteException Exception if invalid data is detected.
* @param \WC_Order $order Order object.
* @param bool $needs_shipping Whether the order needs shipping.
protected function validate_addresses( \WC_Order $order, bool $needs_shipping ) {
$errors = new \WP_Error();
$billing_country = $order->get_billing_country();
$shipping_country = $order->get_shipping_country();
$local_pickup_method_ids = LocalPickupUtils::get_local_pickup_method_ids();
$selected_shipping_rates = ShippingUtil::get_selected_shipping_rates_from_packages( WC()->shipping()->get_packages() );
$selected_shipping_rates_are_all_local_pickup = ArrayUtil::array_all(
$selected_shipping_rates,
function ( $rate ) use ( $local_pickup_method_ids ) {
return in_array( $rate->get_method_id(), $local_pickup_method_ids, true );
// If only local pickup is selected, we don't need to validate the shipping country.
if ( ! $selected_shipping_rates_are_all_local_pickup && ! $this->validate_allowed_country( $shipping_country, (array) wc()->countries->get_shipping_countries() ) ) {
throw new RouteException(
'woocommerce_rest_invalid_address_country',
/* translators: %s country code. */
esc_html__( 'Sorry, we do not ship orders to the provided country (%s)', 'woocommerce' ),
esc_html( $shipping_country )
'allowed_countries' => array_map( 'esc_html', array_keys( wc()->countries->get_shipping_countries() ) ),
if ( ! $this->validate_allowed_country( $billing_country, (array) wc()->countries->get_allowed_countries() ) ) {
throw new RouteException(
'woocommerce_rest_invalid_address_country',
/* translators: %s country code. */
esc_html__( 'Sorry, we do not allow orders from the provided country (%s)', 'woocommerce' ),
esc_html( $billing_country )
'allowed_countries' => array_map( 'esc_html', array_keys( wc()->countries->get_allowed_countries() ) ),
$this->validate_address_fields( $order, 'shipping', $errors );
$this->validate_address_fields( $order, 'billing', $errors );
if ( ! $errors->has_errors() ) {
$errors_by_code = array();
$error_codes = $errors->get_error_codes();
foreach ( $error_codes as $code ) {
$errors_by_code[ $code ] = $errors->get_error_messages( $code );
// Surface errors from first code.
foreach ( $errors_by_code as $code => $error_messages ) {
throw new RouteException(
'woocommerce_rest_invalid_address',
/* translators: %s Address type. */
esc_html__( 'There was a problem with the provided %s:', 'woocommerce' ) . ' ' . esc_html( implode( ', ', $error_messages ) ),
'shipping' === $code ? esc_html__( 'shipping address', 'woocommerce' ) : esc_html__( 'billing address', 'woocommerce' )
'errors' => $errors_by_code, // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
* Check all required address fields are set and return errors if not.
* @param string $country Country code.
* @param array $allowed_countries List of valid country codes.
* @return boolean True if valid.
protected function validate_allowed_country( $country, array $allowed_countries ) {
return array_key_exists( $country, $allowed_countries );
* Check all required address fields are set and return errors if not.
* @param \WC_Order $order Order object.
* @param string $address_type billing or shipping address, used in error messages.
* @param \WP_Error $errors Error object.
protected function validate_address_fields( \WC_Order $order, $address_type, \WP_Error $errors ) {
$all_locales = wc()->countries->get_country_locale();
$address = $order->get_address( $address_type );
$current_locale = $all_locales[ $address['country'] ] ?? [];
foreach ( $all_locales['default'] as $key => $value ) {
// If $current_locale[ $key ] is not empty, merge it with locale default, otherwise just use default locale.
$current_locale[ $key ] = ! empty( $current_locale[ $key ] )
? wp_parse_args( $current_locale[ $key ], $value )
$additional_fields = $this->additional_fields_controller->get_all_fields_from_object( $order, $address_type );
$address = array_merge( $address, $additional_fields );
foreach ( $current_locale as $address_field_key => $address_field ) {
// Skip validation if field is not required or if it is hidden.
true !== wc_string_to_bool( $address_field['required'] ?? false ) ||
true === wc_string_to_bool( $address_field['hidden'] ?? false )
// Check if field is not set, is an empty string, or is an empty array.
$is_empty = ! isset( $address[ $address_field_key ] ) ||
( is_string( $address[ $address_field_key ] ) && '' === trim( $address[ $address_field_key ] ) ) ||
( is_array( $address[ $address_field_key ] ) && 0 === count( $address[ $address_field_key ] ) );