AgenticCheckoutUtils.php
1 month ago
ArrayUtils.php
2 years ago
CartController.php
2 months ago
CartTokenUtils.php
3 weeks ago
CheckoutTrait.php
2 months ago
DraftOrderTrait.php
1 year ago
JsonWebToken.php
1 year ago
LocalPickupUtils.php
7 months ago
NoticeHandler.php
1 year ago
OrderAuthorizationTrait.php
1 month ago
OrderController.php
3 weeks ago
Pagination.php
2 years ago
PaymentUtils.php
1 year ago
ProductItemTrait.php
2 months ago
ProductLinksTrait.php
5 months ago
ProductQuery.php
1 month ago
ProductQueryFilters.php
1 month ago
QuantityLimits.php
1 year ago
RateLimits.php
1 year ago
SanitizationUtils.php
2 years ago
ValidationUtils.php
2 years ago
OrderController.php
901 lines
| 1 | <?php |
| 2 | declare( strict_types = 1 ); |
| 3 | namespace Automattic\WooCommerce\StoreApi\Utilities; |
| 4 | |
| 5 | use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFields; |
| 6 | use Automattic\WooCommerce\Blocks\Package; |
| 7 | use Automattic\WooCommerce\Internal\Customers\SearchService as CustomerSearchService; |
| 8 | use Automattic\WooCommerce\StoreApi\Exceptions\RouteException; |
| 9 | use Automattic\WooCommerce\Utilities\ArrayUtil; |
| 10 | use Automattic\WooCommerce\Enums\OrderItemType; |
| 11 | use Automattic\WooCommerce\Utilities\DiscountsUtil; |
| 12 | use Automattic\WooCommerce\Utilities\ShippingUtil; |
| 13 | use Exception; |
| 14 | |
| 15 | /** |
| 16 | * OrderController class. |
| 17 | * Helper class which creates and syncs orders with the cart. |
| 18 | */ |
| 19 | class OrderController { |
| 20 | |
| 21 | /** |
| 22 | * Checkout fields controller. |
| 23 | * |
| 24 | * @var CheckoutFields |
| 25 | */ |
| 26 | private CheckoutFields $additional_fields_controller; |
| 27 | |
| 28 | /** |
| 29 | * Constructor. |
| 30 | */ |
| 31 | public function __construct() { |
| 32 | $this->additional_fields_controller = Package::container()->get( CheckoutFields::class ); |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Create order and set props based on global settings. |
| 37 | * |
| 38 | * @throws RouteException Exception if invalid data is detected. |
| 39 | * |
| 40 | * @return \WC_Order A new order object. |
| 41 | */ |
| 42 | public function create_order_from_cart() { |
| 43 | if ( wc()->cart->is_empty() ) { |
| 44 | throw new RouteException( |
| 45 | 'woocommerce_rest_cart_empty', |
| 46 | __( 'Cannot create order from empty cart.', 'woocommerce' ), |
| 47 | 400 |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | add_filter( 'woocommerce_default_order_status', array( $this, 'default_order_status' ) ); |
| 52 | |
| 53 | try { |
| 54 | $order = new \WC_Order(); |
| 55 | $order->set_status( 'checkout-draft' ); |
| 56 | $order->set_created_via( 'store-api' ); |
| 57 | $this->update_order_from_cart( $order ); |
| 58 | } finally { |
| 59 | remove_filter( 'woocommerce_default_order_status', array( $this, 'default_order_status' ) ); |
| 60 | } |
| 61 | |
| 62 | return $order; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Update an order using data from the current cart. |
| 67 | * |
| 68 | * @param \WC_Order $order The order object to update. |
| 69 | * @param boolean $update_totals Whether to update totals or not. |
| 70 | */ |
| 71 | public function update_order_from_cart( \WC_Order $order, $update_totals = true ) { |
| 72 | // Tax location for local pickup orders is handled by ShippingController::filter_order_tax_location(), which |
| 73 | // hooks woocommerce_order_get_tax_location once and derives the pickup location address from the order's own |
| 74 | // shipping line item. This avoids registering a per-call (and unremovable) closure on every sync. |
| 75 | // See \WC_Abstract_Order::get_tax_location(). |
| 76 | |
| 77 | // Ensure cart is current. |
| 78 | if ( $update_totals ) { |
| 79 | wc()->cart->calculate_totals(); |
| 80 | } |
| 81 | |
| 82 | // Update the current order to match the current cart. |
| 83 | $this->update_line_items_from_cart( $order ); |
| 84 | $this->update_addresses_from_cart( $order ); |
| 85 | $order->set_currency( get_woocommerce_currency() ); |
| 86 | $order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) ); |
| 87 | $order->set_customer_id( get_current_user_id() ); |
| 88 | $order->set_customer_ip_address( \WC_Geolocation::get_ip_address() ); |
| 89 | $order->set_customer_user_agent( wc_get_user_agent() ); |
| 90 | $order->set_payment_method( PaymentUtils::get_default_payment_method() ); |
| 91 | $order->update_meta_data( 'is_vat_exempt', wc_bool_to_string( wc()->cart->get_customer()->get_is_vat_exempt() ) ); |
| 92 | $order->calculate_totals(); |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * Copies order data to customer object (not the session), so values persist for future checkouts. |
| 97 | * |
| 98 | * @param \WC_Order $order Order object. |
| 99 | */ |
| 100 | public function sync_customer_data_with_order( \WC_Order $order ) { |
| 101 | $customer_id = $order->get_customer_id(); |
| 102 | if ( $customer_id ) { |
| 103 | $customer = new \WC_Customer( $customer_id ); |
| 104 | $customer->set_props( |
| 105 | array( |
| 106 | 'billing_first_name' => $order->get_billing_first_name(), |
| 107 | 'billing_last_name' => $order->get_billing_last_name(), |
| 108 | 'billing_company' => $order->get_billing_company(), |
| 109 | 'billing_address_1' => $order->get_billing_address_1(), |
| 110 | 'billing_address_2' => $order->get_billing_address_2(), |
| 111 | 'billing_city' => $order->get_billing_city(), |
| 112 | 'billing_state' => $order->get_billing_state(), |
| 113 | 'billing_postcode' => $order->get_billing_postcode(), |
| 114 | 'billing_country' => $order->get_billing_country(), |
| 115 | 'billing_email' => $order->get_billing_email(), |
| 116 | 'billing_phone' => $order->get_billing_phone(), |
| 117 | 'shipping_first_name' => $order->get_shipping_first_name(), |
| 118 | 'shipping_last_name' => $order->get_shipping_last_name(), |
| 119 | 'shipping_company' => $order->get_shipping_company(), |
| 120 | 'shipping_address_1' => $order->get_shipping_address_1(), |
| 121 | 'shipping_address_2' => $order->get_shipping_address_2(), |
| 122 | 'shipping_city' => $order->get_shipping_city(), |
| 123 | 'shipping_state' => $order->get_shipping_state(), |
| 124 | 'shipping_postcode' => $order->get_shipping_postcode(), |
| 125 | 'shipping_country' => $order->get_shipping_country(), |
| 126 | 'shipping_phone' => $order->get_shipping_phone(), |
| 127 | ) |
| 128 | ); |
| 129 | $this->additional_fields_controller->sync_customer_additional_fields_with_order( $order, $customer ); |
| 130 | $customer->save(); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | /** |
| 135 | * Final validation ran before payment is taken. |
| 136 | * |
| 137 | * By this point we have an order populated with customer data and items. |
| 138 | * |
| 139 | * @throws RouteException Exception if invalid data is detected. |
| 140 | * @param \WC_Order $order Order object. |
| 141 | */ |
| 142 | public function validate_order_before_payment( \WC_Order $order ) { |
| 143 | $needs_shipping = wc()->cart->needs_shipping(); |
| 144 | $chosen_shipping_methods = wc()->session->get( 'chosen_shipping_methods', [] ); |
| 145 | |
| 146 | $this->validate_coupons( $order ); |
| 147 | $this->validate_email( $order ); |
| 148 | $this->validate_selected_shipping_methods( $needs_shipping, $chosen_shipping_methods ); |
| 149 | $this->validate_addresses( $order, $needs_shipping ); |
| 150 | |
| 151 | // Perform custom validations. |
| 152 | $this->perform_custom_order_validation( $order ); |
| 153 | } |
| 154 | |
| 155 | /** |
| 156 | * Final validation for existing orders, ran before payment is taken. |
| 157 | * |
| 158 | * By this point we have an order populated with customer data and items. |
| 159 | * |
| 160 | * Since the cart is not involved, we don't validate shipping methods and assume the order already |
| 161 | * contains the correct shipping items. |
| 162 | * |
| 163 | * @throws RouteException Exception if invalid data is detected. |
| 164 | * @param \WC_Order $order Order object. |
| 165 | */ |
| 166 | public function validate_existing_order_before_payment( \WC_Order $order ) { |
| 167 | $needs_shipping = $order->needs_shipping(); |
| 168 | |
| 169 | $this->validate_coupons( $order, true ); |
| 170 | $this->validate_email( $order ); |
| 171 | $this->validate_addresses( $order, $needs_shipping ); |
| 172 | |
| 173 | // Perform custom validations. |
| 174 | $this->perform_custom_order_validation( $order ); |
| 175 | } |
| 176 | |
| 177 | /** |
| 178 | * Validate an existing order's address data before the order is updated from the request. |
| 179 | * |
| 180 | * Runs before any request data is persisted so a rejected address cannot mutate the order. |
| 181 | * |
| 182 | * @throws RouteException Exception if invalid data is detected. |
| 183 | * @param \WC_Order $order Order object. |
| 184 | */ |
| 185 | public function validate_existing_order_before_update( \WC_Order $order ): void { |
| 186 | $this->validate_addresses( $order, $order->needs_shipping() ); |
| 187 | } |
| 188 | |
| 189 | /** |
| 190 | * Perform custom order validation via WooCommerce hooks. |
| 191 | * |
| 192 | * Allows plugins to perform custom validation before payment. |
| 193 | * |
| 194 | * @param \WC_Order $order Order object. |
| 195 | * @throws RouteException Exception if validation fails. |
| 196 | */ |
| 197 | protected function perform_custom_order_validation( \WC_Order $order ) { |
| 198 | $validation_errors = new \WP_Error(); |
| 199 | |
| 200 | /** |
| 201 | * Allow plugins to perform custom validation before payment. |
| 202 | * |
| 203 | * Plugins can add errors to the $validation_errors object. |
| 204 | * |
| 205 | * @param \WC_Order $order The order object. |
| 206 | * @param \WP_Error $validation_errors WP_Error object to add custom errors to. |
| 207 | * @since 9.9.0 |
| 208 | */ |
| 209 | do_action( 'woocommerce_checkout_validate_order_before_payment', $order, $validation_errors ); |
| 210 | |
| 211 | // Check if there are any errors after custom validation. |
| 212 | if ( $validation_errors->has_errors() ) { |
| 213 | throw new RouteException( |
| 214 | 'woocommerce_rest_checkout_custom_validation_error', |
| 215 | esc_html( implode( ' ', $validation_errors->get_error_messages() ) ), |
| 216 | 400 |
| 217 | ); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * Convert a coupon code to a coupon object. |
| 223 | * |
| 224 | * @param string $coupon_code Coupon code. |
| 225 | * @return \WC_Coupon Coupon object. |
| 226 | */ |
| 227 | protected function get_coupon( $coupon_code ) { |
| 228 | return new \WC_Coupon( $coupon_code ); |
| 229 | } |
| 230 | |
| 231 | /** |
| 232 | * Validate coupons applied to the order and remove those that are not valid. |
| 233 | * |
| 234 | * @throws RouteException Exception if invalid data is detected. |
| 235 | * @param \WC_Order $order Order object. |
| 236 | * @param bool $use_order_data Whether to use order data or cart data. |
| 237 | */ |
| 238 | protected function validate_coupons( \WC_Order $order, bool $use_order_data = false ) { |
| 239 | $coupon_codes = $order->get_coupon_codes(); |
| 240 | $coupons = array_filter( array_map( array( $this, 'get_coupon' ), $coupon_codes ) ); |
| 241 | $validators = array( 'validate_coupon_email_restriction', 'validate_coupon_usage_limit' ); |
| 242 | $coupon_errors = array(); |
| 243 | |
| 244 | if ( $use_order_data ) { |
| 245 | $validators[] = 'validate_coupon_global_usage_limit'; |
| 246 | } |
| 247 | |
| 248 | foreach ( $coupons as $coupon ) { |
| 249 | try { |
| 250 | array_walk( |
| 251 | $validators, |
| 252 | function ( $validator, $index, $params ) { |
| 253 | call_user_func_array( array( $this, $validator ), $params ); |
| 254 | }, |
| 255 | array( $coupon, $order ) |
| 256 | ); |
| 257 | } catch ( Exception $error ) { |
| 258 | $coupon_errors[ $coupon->get_code() ] = $error->getMessage(); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | if ( $coupon_errors ) { |
| 263 | // Remove all coupons that were not valid. |
| 264 | if ( $use_order_data ) { |
| 265 | $error_code = 'woocommerce_rest_order_coupon_errors'; |
| 266 | |
| 267 | if ( $order->get_recorded_coupon_usage_counts() ) { |
| 268 | foreach ( $coupon_errors as $coupon_code => $message ) { |
| 269 | $order->remove_coupon( $coupon_code ); |
| 270 | } |
| 271 | } else { |
| 272 | // Remove directly. `remove_coupon()` would decrement `usage_count` this order never recorded. |
| 273 | foreach ( $order->get_items( 'coupon' ) as $item_id => $coupon_item ) { |
| 274 | if ( $coupon_item instanceof \WC_Order_Item_Coupon && isset( $coupon_errors[ $coupon_item->get_code() ] ) ) { |
| 275 | $order->remove_item( $item_id ); |
| 276 | } |
| 277 | } |
| 278 | $order->recalculate_coupons(); |
| 279 | } |
| 280 | |
| 281 | // Recalculate totals. |
| 282 | $order->calculate_totals(); |
| 283 | } else { |
| 284 | $error_code = 'woocommerce_rest_cart_coupon_errors'; |
| 285 | |
| 286 | foreach ( $coupon_errors as $coupon_code => $message ) { |
| 287 | wc()->cart->remove_coupon( $coupon_code ); |
| 288 | } |
| 289 | |
| 290 | // Recalculate totals. |
| 291 | wc()->cart->calculate_totals(); |
| 292 | |
| 293 | // Re-sync order with cart. |
| 294 | $this->update_order_from_cart( $order ); |
| 295 | } |
| 296 | |
| 297 | // Return exception so customer can review before payment. |
| 298 | if ( 1 === count( $coupon_errors ) && $use_order_data ) { |
| 299 | $error_message = sprintf( |
| 300 | /* translators: %1$s Coupon codes, %2$s Reason */ |
| 301 | __( '"%1$s" was removed from the order. %2$s', 'woocommerce' ), |
| 302 | array_keys( $coupon_errors )[0], |
| 303 | array_values( $coupon_errors )[0], |
| 304 | ); |
| 305 | } elseif ( 1 === count( $coupon_errors ) ) { |
| 306 | $error_message = sprintf( |
| 307 | /* translators: %1$s Coupon codes, %2$s Reason */ |
| 308 | __( '"%1$s" was removed from the cart. %2$s', 'woocommerce' ), |
| 309 | array_keys( $coupon_errors )[0], |
| 310 | array_values( $coupon_errors )[0], |
| 311 | ); |
| 312 | } elseif ( $use_order_data ) { |
| 313 | $error_message = sprintf( |
| 314 | /* translators: %s Coupon codes. */ |
| 315 | __( 'Invalid coupons were removed from the order: "%s"', 'woocommerce' ), |
| 316 | implode( '", "', array_keys( $coupon_errors ) ) |
| 317 | ); |
| 318 | } else { |
| 319 | $error_message = sprintf( |
| 320 | /* translators: %s Coupon codes. */ |
| 321 | __( 'Invalid coupons were removed from the cart: "%s"', 'woocommerce' ), |
| 322 | implode( '", "', array_keys( $coupon_errors ) ) |
| 323 | ); |
| 324 | } |
| 325 | |
| 326 | throw new RouteException( $error_code, $error_message, 409, array( 'removed_coupons' => $coupon_errors ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | /** |
| 331 | * Validates the customer email. This is a required field. |
| 332 | * |
| 333 | * @throws RouteException Exception if invalid data is detected. |
| 334 | * @param \WC_Order $order Order object. |
| 335 | */ |
| 336 | protected function validate_email( \WC_Order $order ) { |
| 337 | $email = $order->get_billing_email(); |
| 338 | |
| 339 | if ( empty( $email ) ) { |
| 340 | throw new RouteException( |
| 341 | 'woocommerce_rest_missing_email_address', |
| 342 | __( 'A valid email address is required', 'woocommerce' ), |
| 343 | 400 |
| 344 | ); |
| 345 | } |
| 346 | |
| 347 | if ( ! is_email( $email ) ) { |
| 348 | throw new RouteException( |
| 349 | 'woocommerce_rest_invalid_email_address', |
| 350 | sprintf( |
| 351 | /* translators: %s provided email. */ |
| 352 | __( 'The provided email address (%s) is not valid—please provide a valid email address', 'woocommerce' ), |
| 353 | esc_html( $email ) |
| 354 | ), |
| 355 | 400 |
| 356 | ); |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | /** |
| 361 | * Validates customer address data based on the locale to ensure required fields are set. |
| 362 | * |
| 363 | * @throws RouteException Exception if invalid data is detected. |
| 364 | * @param \WC_Order $order Order object. |
| 365 | * @param bool $needs_shipping Whether the order needs shipping. |
| 366 | */ |
| 367 | protected function validate_addresses( \WC_Order $order, bool $needs_shipping ) { |
| 368 | $errors = new \WP_Error(); |
| 369 | $billing_country = $order->get_billing_country(); |
| 370 | $shipping_country = $order->get_shipping_country(); |
| 371 | |
| 372 | if ( $needs_shipping ) { |
| 373 | $local_pickup_method_ids = LocalPickupUtils::get_local_pickup_method_ids(); |
| 374 | $selected_shipping_rates = ShippingUtil::get_selected_shipping_rates_from_packages( WC()->shipping()->get_packages() ); |
| 375 | $selected_shipping_rates_are_all_local_pickup = ArrayUtil::array_all( |
| 376 | $selected_shipping_rates, |
| 377 | function ( $rate ) use ( $local_pickup_method_ids ) { |
| 378 | return in_array( $rate->get_method_id(), $local_pickup_method_ids, true ); |
| 379 | } |
| 380 | ); |
| 381 | |
| 382 | // If only local pickup is selected, we don't need to validate the shipping country. |
| 383 | if ( ! $selected_shipping_rates_are_all_local_pickup && ! $this->validate_allowed_country( $shipping_country, (array) wc()->countries->get_shipping_countries() ) ) { |
| 384 | $countries = WC()->countries->get_countries(); |
| 385 | $shipping_country_name = $countries[ $shipping_country ] ?? $shipping_country; |
| 386 | throw new RouteException( |
| 387 | 'woocommerce_rest_invalid_address_country', |
| 388 | sprintf( |
| 389 | /* translators: %s country name. */ |
| 390 | esc_html__( 'Sorry, we do not ship orders to the provided country (%s)', 'woocommerce' ), |
| 391 | esc_html( $shipping_country_name ) |
| 392 | ), |
| 393 | 400, |
| 394 | array( |
| 395 | 'allowed_countries' => array_map( 'esc_html', array_keys( wc()->countries->get_shipping_countries() ) ), |
| 396 | ) |
| 397 | ); |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | if ( ! $this->validate_allowed_country( $billing_country, (array) wc()->countries->get_allowed_countries() ) ) { |
| 402 | $countries = WC()->countries->get_countries(); |
| 403 | $billing_country_name = $countries[ $billing_country ] ?? $billing_country; |
| 404 | throw new RouteException( |
| 405 | 'woocommerce_rest_invalid_address_country', |
| 406 | sprintf( |
| 407 | /* translators: %s country name. */ |
| 408 | esc_html__( 'Sorry, we do not allow orders from the provided country (%s)', 'woocommerce' ), |
| 409 | esc_html( $billing_country_name ) |
| 410 | ), |
| 411 | 400, |
| 412 | array( |
| 413 | 'allowed_countries' => array_map( 'esc_html', array_keys( wc()->countries->get_allowed_countries() ) ), |
| 414 | ) |
| 415 | ); |
| 416 | } |
| 417 | |
| 418 | if ( $needs_shipping ) { |
| 419 | $this->validate_address_fields( $order, 'shipping', $errors ); |
| 420 | } |
| 421 | $this->validate_address_fields( $order, 'billing', $errors ); |
| 422 | |
| 423 | if ( ! $errors->has_errors() ) { |
| 424 | return; |
| 425 | } |
| 426 | |
| 427 | $errors_by_code = array(); |
| 428 | $error_codes = $errors->get_error_codes(); |
| 429 | |
| 430 | foreach ( $error_codes as $code ) { |
| 431 | $errors_by_code[ $code ] = $errors->get_error_messages( $code ); |
| 432 | } |
| 433 | |
| 434 | // Surface errors from first code. |
| 435 | foreach ( $errors_by_code as $code => $error_messages ) { |
| 436 | throw new RouteException( |
| 437 | 'woocommerce_rest_invalid_address', |
| 438 | sprintf( |
| 439 | /* translators: %s Address type. */ |
| 440 | esc_html__( 'There was a problem with the provided %s:', 'woocommerce' ) . ' ' . esc_html( implode( ', ', $error_messages ) ), |
| 441 | 'shipping' === $code ? esc_html__( 'shipping address', 'woocommerce' ) : esc_html__( 'billing address', 'woocommerce' ) |
| 442 | ), |
| 443 | 400, |
| 444 | array( |
| 445 | 'errors' => $errors_by_code, // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped |
| 446 | ) |
| 447 | ); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | /** |
| 452 | * Check all required address fields are set and return errors if not. |
| 453 | * |
| 454 | * @param string $country Country code. |
| 455 | * @param array $allowed_countries List of valid country codes. |
| 456 | * @return boolean True if valid. |
| 457 | */ |
| 458 | protected function validate_allowed_country( $country, array $allowed_countries ) { |
| 459 | return array_key_exists( $country, $allowed_countries ); |
| 460 | } |
| 461 | |
| 462 | /** |
| 463 | * Check all required address fields are set and return errors if not. |
| 464 | * |
| 465 | * @param \WC_Order $order Order object. |
| 466 | * @param string $address_type billing or shipping address, used in error messages. |
| 467 | * @param \WP_Error $errors Error object. |
| 468 | */ |
| 469 | protected function validate_address_fields( \WC_Order $order, $address_type, \WP_Error $errors ) { |
| 470 | $all_locales = wc()->countries->get_country_locale(); |
| 471 | $address = $order->get_address( $address_type ); |
| 472 | $current_locale = $all_locales[ $address['country'] ] ?? []; |
| 473 | |
| 474 | foreach ( $all_locales['default'] as $key => $value ) { |
| 475 | // If $current_locale[ $key ] is not empty, merge it with locale default, otherwise just use default locale. |
| 476 | $current_locale[ $key ] = ! empty( $current_locale[ $key ] ) |
| 477 | ? wp_parse_args( $current_locale[ $key ], $value ) |
| 478 | : $value; |
| 479 | } |
| 480 | |
| 481 | $additional_fields = $this->additional_fields_controller->get_all_fields_from_object( $order, $address_type ); |
| 482 | |
| 483 | $address = array_merge( $address, $additional_fields ); |
| 484 | |
| 485 | foreach ( $current_locale as $address_field_key => $address_field ) { |
| 486 | // Skip validation if field is not required or if it is hidden. |
| 487 | if ( |
| 488 | true !== wc_string_to_bool( $address_field['required'] ?? false ) || |
| 489 | true === wc_string_to_bool( $address_field['hidden'] ?? false ) |
| 490 | ) { |
| 491 | continue; |
| 492 | } |
| 493 | |
| 494 | // Check if field is not set, is an empty string, or is an empty array. |
| 495 | $is_empty = ! isset( $address[ $address_field_key ] ) || |
| 496 | ( is_string( $address[ $address_field_key ] ) && '' === trim( $address[ $address_field_key ] ) ) || |
| 497 | ( is_array( $address[ $address_field_key ] ) && 0 === count( $address[ $address_field_key ] ) ); |
| 498 | |
| 499 | if ( $is_empty ) { |
| 500 | /* translators: %s Field label. */ |
| 501 | $errors->add( $address_type, sprintf( __( '%s is required', 'woocommerce' ), $address_field['label'] ), $address_field_key ); |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | // Validate additional fields. |
| 506 | $result = $this->additional_fields_controller->validate_fields_for_location( $address, 'address', $address_type ); |
| 507 | |
| 508 | if ( $result->has_errors() ) { |
| 509 | // Add errors to main error object but ensure they maintain the billing/shipping error code. |
| 510 | foreach ( $result->get_error_codes() as $code ) { |
| 511 | $errors->add( $address_type, $result->get_error_message( $code ), $code ); |
| 512 | } |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | /** |
| 517 | * Check email restrictions of a coupon against the order. |
| 518 | * |
| 519 | * @throws Exception Exception if invalid data is detected. |
| 520 | * @param \WC_Coupon $coupon Coupon object applied to the cart. |
| 521 | * @param \WC_Order $order Order object. |
| 522 | */ |
| 523 | protected function validate_coupon_email_restriction( \WC_Coupon $coupon, \WC_Order $order ) { |
| 524 | $restrictions = $coupon->get_email_restrictions(); |
| 525 | |
| 526 | if ( empty( $restrictions ) ) { |
| 527 | return; |
| 528 | } |
| 529 | |
| 530 | $check_emails = array(); |
| 531 | |
| 532 | // Check the logged-in user's email. |
| 533 | $current_user = wp_get_current_user(); |
| 534 | if ( $current_user->exists() ) { |
| 535 | $user_email = trim( sanitize_email( $current_user->user_email ) ); |
| 536 | if ( ! empty( $user_email ) ) { |
| 537 | $check_emails[] = strtolower( $user_email ); |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | // Also check the billing email from the order. |
| 542 | $billing_email = $order->get_billing_email(); |
| 543 | if ( ! empty( $billing_email ) ) { |
| 544 | $billing_email = trim( sanitize_email( $billing_email ) ); |
| 545 | if ( ! empty( $billing_email ) ) { |
| 546 | $check_emails[] = strtolower( $billing_email ); |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | // Remove duplicates and empty values. |
| 551 | $check_emails = array_unique( array_filter( $check_emails ) ); |
| 552 | |
| 553 | if ( ! empty( $check_emails ) && ! DiscountsUtil::is_coupon_emails_allowed( $check_emails, $restrictions ) ) { |
| 554 | // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped |
| 555 | throw new Exception( $coupon->get_coupon_error( \WC_Coupon::E_WC_COUPON_NOT_YOURS_REMOVED ) ); |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | /** |
| 560 | * Check usage restrictions of a coupon against the order. |
| 561 | * |
| 562 | * @throws Exception Exception if invalid data is detected. |
| 563 | * @param \WC_Coupon $coupon Coupon object applied to the cart. |
| 564 | * @param \WC_Order $order Order object. |
| 565 | */ |
| 566 | protected function validate_coupon_usage_limit( \WC_Coupon $coupon, \WC_Order $order ) { |
| 567 | $coupon_usage_limit = $coupon->get_usage_limit_per_user(); |
| 568 | |
| 569 | if ( 0 === $coupon_usage_limit ) { |
| 570 | return; |
| 571 | } |
| 572 | |
| 573 | // First, we check a logged in customer usage count, which happens against their user id, billing email, and account email. |
| 574 | if ( $order->get_customer_id() ) { |
| 575 | // We get usage per user id and associated emails. |
| 576 | $usage_count = $this->get_usage_per_aliases( |
| 577 | $coupon, |
| 578 | array( |
| 579 | $order->get_billing_email(), |
| 580 | $order->get_customer_id(), |
| 581 | $this->get_email_from_user_id( $order->get_customer_id() ), |
| 582 | ) |
| 583 | ); |
| 584 | } else { |
| 585 | // Otherwise we check if the email doesn't belong to an existing user. |
| 586 | // This will get us any user ids for the given billing email. |
| 587 | $user_ids = wc_get_container()->get( CustomerSearchService::class )->find_user_ids_by_billing_email_for_coupons_usage_lookup( array( $order->get_billing_email() ) ); |
| 588 | |
| 589 | // Convert all found user ids to a list of email addresses. |
| 590 | $user_emails = array_map( array( $this, 'get_email_from_user_id' ), $user_ids ); |
| 591 | |
| 592 | // This matches a user against the given billing email and gets their ID/email/billing email. |
| 593 | $found_user = get_user_by( 'email', $order->get_billing_email() ); |
| 594 | if ( $found_user ) { |
| 595 | $user_ids[] = $found_user->ID; |
| 596 | $user_emails[] = $found_user->user_email; |
| 597 | $user_emails[] = get_user_meta( $found_user->ID, 'billing_email', true ); |
| 598 | } |
| 599 | |
| 600 | // Finally, grab usage count for all found IDs and emails. |
| 601 | $usage_count = $this->get_usage_per_aliases( |
| 602 | $coupon, |
| 603 | array_merge( |
| 604 | $user_emails, |
| 605 | $user_ids, |
| 606 | array( $order->get_billing_email() ) |
| 607 | ) |
| 608 | ); |
| 609 | } |
| 610 | |
| 611 | if ( $usage_count >= $coupon_usage_limit ) { |
| 612 | throw new Exception( $coupon->get_coupon_error( \WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED ) ); |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | /** |
| 617 | * Check the coupon's global usage limit against the order. |
| 618 | * |
| 619 | * Skipped once the order has recorded its own usage, so it is not counted against itself. |
| 620 | * |
| 621 | * @throws Exception Exception if the global usage limit has been reached. |
| 622 | * @param \WC_Coupon $coupon Coupon object applied to the order. |
| 623 | * @param \WC_Order $order Order object. |
| 624 | */ |
| 625 | protected function validate_coupon_global_usage_limit( \WC_Coupon $coupon, \WC_Order $order ): void { |
| 626 | $usage_limit = $coupon->get_usage_limit(); |
| 627 | |
| 628 | if ( ! $usage_limit || $order->get_recorded_coupon_usage_counts() ) { |
| 629 | return; |
| 630 | } |
| 631 | |
| 632 | // Include tentative holds, matching WC_Discounts::validate_coupon_usage_limit(). |
| 633 | $data_store = $coupon->get_data_store(); |
| 634 | $tentative_usage = is_callable( array( $data_store, 'get_tentative_usage_count' ) ) |
| 635 | ? (int) $data_store->get_tentative_usage_count( $coupon->get_id() ) |
| 636 | : 0; |
| 637 | |
| 638 | if ( $coupon->get_usage_count() + $tentative_usage >= $usage_limit ) { |
| 639 | // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped |
| 640 | throw new Exception( $coupon->get_coupon_error( \WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED ) ); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | /** |
| 645 | * Get user email from user id. |
| 646 | * |
| 647 | * @param integer $user_id User ID. |
| 648 | * @return string Email or empty string. |
| 649 | */ |
| 650 | private function get_email_from_user_id( $user_id ) { |
| 651 | $user_data = get_userdata( $user_id ); |
| 652 | return $user_data ? $user_data->user_email : ''; |
| 653 | } |
| 654 | |
| 655 | /** |
| 656 | * Get the usage count for a coupon based on a list of aliases (ids, emails). |
| 657 | * |
| 658 | * @param \WC_Coupon $coupon Coupon object applied to the cart. |
| 659 | * @param array $aliases List of aliases to check. |
| 660 | * |
| 661 | * @return integer |
| 662 | */ |
| 663 | private function get_usage_per_aliases( $coupon, $aliases ) { |
| 664 | global $wpdb; |
| 665 | $aliases = array_unique( array_filter( $aliases ) ); |
| 666 | $aliases_string = "('" . implode( "','", array_map( 'esc_sql', $aliases ) ) . "')"; |
| 667 | $usage_count = $wpdb->get_var( |
| 668 | $wpdb->prepare( |
| 669 | // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 670 | "SELECT COUNT( meta_id ) FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_used_by' AND meta_value IN {$aliases_string};", |
| 671 | $coupon->get_id(), |
| 672 | ) |
| 673 | ); |
| 674 | |
| 675 | $data_store = $coupon->get_data_store(); |
| 676 | // Coupons can be held for an x amount of time before being applied to an order, so we need to check if it's already being held in (maybe via another flow). |
| 677 | $tentative_usage_count = $data_store->get_tentative_usages_for_user( $coupon->get_id(), $aliases ); |
| 678 | return $tentative_usage_count + $usage_count; |
| 679 | } |
| 680 | |
| 681 | /** |
| 682 | * Check there is a shipping method if it requires shipping. |
| 683 | * |
| 684 | * @throws RouteException Exception if invalid data is detected. |
| 685 | * @param boolean $needs_shipping Current order needs shipping. |
| 686 | * @param array $chosen_shipping_methods Array of shipping methods. |
| 687 | */ |
| 688 | public function validate_selected_shipping_methods( $needs_shipping, $chosen_shipping_methods = array() ) { |
| 689 | if ( ! $needs_shipping ) { |
| 690 | return; |
| 691 | } |
| 692 | |
| 693 | $exception = new RouteException( |
| 694 | 'woocommerce_rest_invalid_shipping_option', |
| 695 | __( 'Sorry, this order requires a shipping option.', 'woocommerce' ), |
| 696 | 400, |
| 697 | array() |
| 698 | ); |
| 699 | |
| 700 | if ( ! is_array( $chosen_shipping_methods ) || empty( $chosen_shipping_methods ) ) { |
| 701 | throw $exception; |
| 702 | } |
| 703 | |
| 704 | // Validate that the chosen shipping methods are valid according to the returned package rates. |
| 705 | $packages = WC()->shipping()->get_packages(); |
| 706 | foreach ( $packages as $package_id => $package ) { |
| 707 | $chosen_rate_for_package = $chosen_shipping_methods[ $package_id ]; |
| 708 | $valid_rate_ids_for_package = wp_list_pluck( $package['rates'], 'id' ); |
| 709 | |
| 710 | if ( ! is_string( $chosen_rate_for_package ) || ! ArrayUtils::string_contains_array( $chosen_rate_for_package, $valid_rate_ids_for_package ) ) { |
| 711 | throw $exception; |
| 712 | } |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | /** |
| 717 | * Validate a given order key against an existing order. |
| 718 | * |
| 719 | * @throws RouteException Exception if invalid data is detected. |
| 720 | * @param integer $order_id Order ID. |
| 721 | * @param string $order_key Order key. |
| 722 | */ |
| 723 | public function validate_order_key( $order_id, $order_key ) { |
| 724 | $order = wc_get_order( $order_id ); |
| 725 | |
| 726 | if ( ! $order || ! $order_key || $order->get_id() !== $order_id || ! hash_equals( $order->get_order_key(), $order_key ) ) { |
| 727 | throw new RouteException( 'woocommerce_rest_invalid_order', __( 'Invalid order ID or key provided.', 'woocommerce' ), 401 ); |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | /** |
| 732 | * Get errors for order stock on failed orders. |
| 733 | * |
| 734 | * @throws RouteException Exception if invalid data is detected. |
| 735 | * @param integer $order_id Order ID. |
| 736 | */ |
| 737 | public function get_failed_order_stock_error( $order_id ) { |
| 738 | $order = wc_get_order( $order_id ); |
| 739 | |
| 740 | // Ensure order items are still stocked if paying for a failed order. Pending orders do not need this check because stock is held. |
| 741 | if ( ! $order->has_status( wc_get_is_pending_statuses() ) ) { |
| 742 | $quantities = array(); |
| 743 | |
| 744 | foreach ( $order->get_items() as $item_key => $item ) { |
| 745 | if ( $item && is_callable( array( $item, 'get_product' ) ) ) { |
| 746 | $product = $item->get_product(); |
| 747 | |
| 748 | if ( ! $product ) { |
| 749 | continue; |
| 750 | } |
| 751 | |
| 752 | $quantities[ $product->get_stock_managed_by_id() ] = isset( $quantities[ $product->get_stock_managed_by_id() ] ) ? $quantities[ $product->get_stock_managed_by_id() ] + $item->get_quantity() : $item->get_quantity(); |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | // Stock levels may already have been adjusted for this order (in which case we don't need to worry about checking for low stock). |
| 757 | if ( ! $order->get_data_store()->get_stock_reduced( $order->get_id() ) ) { |
| 758 | foreach ( $order->get_items() as $item_key => $item ) { |
| 759 | if ( $item && is_callable( array( $item, 'get_product' ) ) ) { |
| 760 | $product = $item->get_product(); |
| 761 | |
| 762 | if ( ! $product ) { |
| 763 | continue; |
| 764 | } |
| 765 | |
| 766 | /** |
| 767 | * Filters whether or not the product is in stock for this pay for order. |
| 768 | * |
| 769 | * @param boolean True if in stock. |
| 770 | * @param \WC_Product $product Product. |
| 771 | * @param \WC_Order $order Order. |
| 772 | * |
| 773 | * @since 9.8.0-dev |
| 774 | */ |
| 775 | if ( ! apply_filters( 'woocommerce_pay_order_product_in_stock', $product->is_in_stock(), $product, $order ) ) { |
| 776 | return array( |
| 777 | 'code' => 'woocommerce_rest_out_of_stock', |
| 778 | /* translators: %s: product name */ |
| 779 | 'message' => sprintf( __( 'Sorry, "%s" is no longer in stock so this order cannot be paid for. We apologize for any inconvenience caused.', 'woocommerce' ), $product->get_name() ), |
| 780 | ); |
| 781 | } |
| 782 | |
| 783 | // We only need to check products managing stock, with a limited stock qty. |
| 784 | if ( ! $product->managing_stock() || $product->backorders_allowed() ) { |
| 785 | continue; |
| 786 | } |
| 787 | |
| 788 | // Check stock based on all items in the cart and consider any held stock within pending orders. |
| 789 | $held_stock = wc_get_held_stock_quantity( $product, $order->get_id() ); |
| 790 | $required_stock = $quantities[ $product->get_stock_managed_by_id() ]; |
| 791 | |
| 792 | /** |
| 793 | * Filters whether or not the product has enough stock. |
| 794 | * |
| 795 | * @param boolean True if has enough stock. |
| 796 | * @param \WC_Product $product Product. |
| 797 | * @param \WC_Order $order Order. |
| 798 | * |
| 799 | * @since 9.8.0-dev |
| 800 | */ |
| 801 | if ( ! apply_filters( 'woocommerce_pay_order_product_has_enough_stock', ( $product->get_stock_quantity() >= ( $held_stock + $required_stock ) ), $product, $order ) ) { |
| 802 | /* translators: 1: product name 2: quantity in stock */ |
| 803 | return array( |
| 804 | 'code' => 'woocommerce_rest_out_of_stock', |
| 805 | /* translators: %s: product name */ |
| 806 | 'message' => sprintf( __( 'Sorry, we do not have enough "%1$s" in stock to fulfill your order (%2$s available). We apologize for any inconvenience caused.', 'woocommerce' ), $product->get_name(), wc_format_stock_quantity_for_display( $product->get_stock_quantity() - $held_stock, $product ) ), |
| 807 | ); |
| 808 | } |
| 809 | } |
| 810 | } |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | return null; |
| 815 | } |
| 816 | |
| 817 | /** |
| 818 | * Changes default order status to draft for orders created via this API. |
| 819 | * |
| 820 | * @return string |
| 821 | */ |
| 822 | public function default_order_status() { |
| 823 | return 'checkout-draft'; |
| 824 | } |
| 825 | |
| 826 | /** |
| 827 | * Create order line items. |
| 828 | * |
| 829 | * @param \WC_Order $order The order object to update. |
| 830 | */ |
| 831 | protected function update_line_items_from_cart( \WC_Order $order ) { |
| 832 | $cart_controller = new CartController(); |
| 833 | $cart = $cart_controller->get_cart_instance(); |
| 834 | $cart_hashes = $cart_controller->get_cart_hashes(); |
| 835 | |
| 836 | if ( $order->get_cart_hash() !== $cart_hashes['line_items'] ) { |
| 837 | $order->set_cart_hash( $cart_hashes['line_items'] ); |
| 838 | $order->remove_order_items( OrderItemType::LINE_ITEM ); |
| 839 | wc()->checkout->create_order_line_items( $order, $cart ); |
| 840 | } |
| 841 | |
| 842 | if ( $order->get_meta( '_shipping_hash' ) !== $cart_hashes['shipping'] ) { |
| 843 | $order->update_meta_data( '_shipping_hash', $cart_hashes['shipping'] ); |
| 844 | $order->remove_order_items( OrderItemType::SHIPPING ); |
| 845 | wc()->checkout->create_order_shipping_lines( $order, wc()->session->get( 'chosen_shipping_methods' ), wc()->shipping()->get_packages() ); |
| 846 | } |
| 847 | |
| 848 | if ( $order->get_meta( '_coupons_hash' ) !== $cart_hashes['coupons'] ) { |
| 849 | $order->remove_order_items( OrderItemType::COUPON ); |
| 850 | $order->update_meta_data( '_coupons_hash', $cart_hashes['coupons'] ); |
| 851 | wc()->checkout->create_order_coupon_lines( $order, $cart ); |
| 852 | } |
| 853 | |
| 854 | if ( $order->get_meta( '_fees_hash' ) !== $cart_hashes['fees'] ) { |
| 855 | $order->update_meta_data( '_fees_hash', $cart_hashes['fees'] ); |
| 856 | $order->remove_order_items( OrderItemType::FEE ); |
| 857 | wc()->checkout->create_order_fee_lines( $order, $cart ); |
| 858 | } |
| 859 | |
| 860 | if ( $order->get_meta( '_taxes_hash' ) !== $cart_hashes['taxes'] ) { |
| 861 | $order->update_meta_data( '_taxes_hash', $cart_hashes['taxes'] ); |
| 862 | $order->remove_order_items( OrderItemType::TAX ); |
| 863 | wc()->checkout->create_order_tax_lines( $order, $cart ); |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | /** |
| 868 | * Update address data from cart and/or customer session data. |
| 869 | * |
| 870 | * @param \WC_Order $order The order object to update. |
| 871 | */ |
| 872 | protected function update_addresses_from_cart( \WC_Order $order ) { |
| 873 | $order->set_props( |
| 874 | array( |
| 875 | 'billing_first_name' => wc()->customer->get_billing_first_name(), |
| 876 | 'billing_last_name' => wc()->customer->get_billing_last_name(), |
| 877 | 'billing_company' => wc()->customer->get_billing_company(), |
| 878 | 'billing_address_1' => wc()->customer->get_billing_address_1(), |
| 879 | 'billing_address_2' => wc()->customer->get_billing_address_2(), |
| 880 | 'billing_city' => wc()->customer->get_billing_city(), |
| 881 | 'billing_state' => wc()->customer->get_billing_state(), |
| 882 | 'billing_postcode' => wc()->customer->get_billing_postcode(), |
| 883 | 'billing_country' => wc()->customer->get_billing_country(), |
| 884 | 'billing_email' => wc()->customer->get_billing_email(), |
| 885 | 'billing_phone' => wc()->customer->get_billing_phone(), |
| 886 | 'shipping_first_name' => wc()->customer->get_shipping_first_name(), |
| 887 | 'shipping_last_name' => wc()->customer->get_shipping_last_name(), |
| 888 | 'shipping_company' => wc()->customer->get_shipping_company(), |
| 889 | 'shipping_address_1' => wc()->customer->get_shipping_address_1(), |
| 890 | 'shipping_address_2' => wc()->customer->get_shipping_address_2(), |
| 891 | 'shipping_city' => wc()->customer->get_shipping_city(), |
| 892 | 'shipping_state' => wc()->customer->get_shipping_state(), |
| 893 | 'shipping_postcode' => wc()->customer->get_shipping_postcode(), |
| 894 | 'shipping_country' => wc()->customer->get_shipping_country(), |
| 895 | 'shipping_phone' => wc()->customer->get_shipping_phone(), |
| 896 | ) |
| 897 | ); |
| 898 | $this->additional_fields_controller->sync_order_additional_fields_with_customer( $order, wc()->customer ); |
| 899 | } |
| 900 | } |
| 901 |