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2.0-rc.1 3.0.9 6.2.0-rc.2 3.1.0 6.2.1 3.1.1 6.2.2 3.1.2 6.2.3 3.2.0 6.3.0 3.2.1 6.3.0-beta.1 3.2.2 6.3.0-rc.1 3.2.3 6.3.0-rc.2 3.2.4 6.3.1 3.2.5 6.3.2 3.2.6 6.4.0 3.3.0 6.4.0-beta.1 3.3.1 6.4.0-rc.1 3.3.2 6.4.1 3.3.2-rc.1 6.4.2 3.3.3 6.5.0 3.3.4 6.5.0-beta.1 3.3.5 6.5.0-rc.1 3.3.6 6.5.0-rc.2 3.4.0 6.5.1 3.4.0-beta.1 6.5.2 3.4.0-rc.2 6.6.0 3.4.1 6.6.0-beta.1 3.4.2 6.6.0-rc.1 3.4.3 6.6.0-rc.2 3.4.4 6.6.1 3.4.5 6.6.2 3.4.6 6.7.0 3.4.7 6.7.0-beta.1 3.4.8 6.7.0-beta.2 3.5.0 6.7.0-rc.1 3.5.0-beta.1 6.7.1 3.5.0-rc.1 6.8.0 3.5.0-rc.2 6.8.0-beta.1 3.5.1 6.8.0-beta.2 3.5.10 6.8.0-rc.1 3.5.2 6.8.1 3.5.3 6.8.2 3.5.4 6.8.3 3.5.5 6.9.0 3.5.6 6.9.0-beta.1 3.5.7 6.9.0-beta.2 3.5.8 6.9.0-rc.1 3.5.9 6.9.1 3.6.0 6.9.2 3.6.0-beta.1 6.9.3 3.6.0-rc.1 6.9.4 3.6.0-rc.2 6.9.5 3.6.0-rc.3 7.0.0 3.6.1 7.0.0-beta.1 3.6.2 7.0.0-beta.2 3.6.3 7.0.0-beta.3 3.6.4 7.0.0-rc.1 3.6.5 7.0.0-rc.2 3.6.6 7.0.1 3.6.7 7.0.2 3.7.0 7.1.0 3.7.0-beta.1 7.1.0-beta.1 3.7.0-rc.1 7.1.0-beta.2 3.7.0-rc.2 7.1.0-rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / src / StoreApi / Utilities / OrderController.php
woocommerce / src / StoreApi / Utilities Last commit date
AgenticCheckoutUtils.php 5 days ago ArrayUtils.php 2 years ago CartController.php 1 month ago CartTokenUtils.php 1 year ago CheckoutTrait.php 1 month ago DraftOrderTrait.php 1 year ago JsonWebToken.php 11 months ago LocalPickupUtils.php 6 months ago NoticeHandler.php 1 year ago OrderAuthorizationTrait.php 5 days ago OrderController.php 5 days ago Pagination.php 2 years ago PaymentUtils.php 1 year ago ProductItemTrait.php 1 month ago ProductLinksTrait.php 3 months ago ProductQuery.php 5 days ago ProductQueryFilters.php 5 days ago QuantityLimits.php 11 months ago RateLimits.php 1 year ago SanitizationUtils.php 2 years ago ValidationUtils.php 2 years ago
OrderController.php
859 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 foreach ( $coupons as $coupon ) {
245 try {
246 array_walk(
247 $validators,
248 function ( $validator, $index, $params ) {
249 call_user_func_array( array( $this, $validator ), $params );
250 },
251 array( $coupon, $order )
252 );
253 } catch ( Exception $error ) {
254 $coupon_errors[ $coupon->get_code() ] = $error->getMessage();
255 }
256 }
257
258 if ( $coupon_errors ) {
259 // Remove all coupons that were not valid.
260 if ( $use_order_data ) {
261 $error_code = 'woocommerce_rest_order_coupon_errors';
262
263 foreach ( $coupon_errors as $coupon_code => $message ) {
264 $order->remove_coupon( $coupon_code );
265 }
266
267 // Recalculate totals.
268 $order->calculate_totals();
269 } else {
270 $error_code = 'woocommerce_rest_cart_coupon_errors';
271
272 foreach ( $coupon_errors as $coupon_code => $message ) {
273 wc()->cart->remove_coupon( $coupon_code );
274 }
275
276 // Recalculate totals.
277 wc()->cart->calculate_totals();
278
279 // Re-sync order with cart.
280 $this->update_order_from_cart( $order );
281 }
282
283 // Return exception so customer can review before payment.
284 if ( 1 === count( $coupon_errors ) && $use_order_data ) {
285 $error_message = sprintf(
286 /* translators: %1$s Coupon codes, %2$s Reason */
287 __( '"%1$s" was removed from the order. %2$s', 'woocommerce' ),
288 array_keys( $coupon_errors )[0],
289 array_values( $coupon_errors )[0],
290 );
291 } elseif ( 1 === count( $coupon_errors ) ) {
292 $error_message = sprintf(
293 /* translators: %1$s Coupon codes, %2$s Reason */
294 __( '"%1$s" was removed from the cart. %2$s', 'woocommerce' ),
295 array_keys( $coupon_errors )[0],
296 array_values( $coupon_errors )[0],
297 );
298 } elseif ( $use_order_data ) {
299 $error_message = sprintf(
300 /* translators: %s Coupon codes. */
301 __( 'Invalid coupons were removed from the order: "%s"', 'woocommerce' ),
302 implode( '", "', array_keys( $coupon_errors ) )
303 );
304 } else {
305 $error_message = sprintf(
306 /* translators: %s Coupon codes. */
307 __( 'Invalid coupons were removed from the cart: "%s"', 'woocommerce' ),
308 implode( '", "', array_keys( $coupon_errors ) )
309 );
310 }
311
312 throw new RouteException( $error_code, $error_message, 409, array( 'removed_coupons' => $coupon_errors ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
313 }
314 }
315
316 /**
317 * Validates the customer email. This is a required field.
318 *
319 * @throws RouteException Exception if invalid data is detected.
320 * @param \WC_Order $order Order object.
321 */
322 protected function validate_email( \WC_Order $order ) {
323 $email = $order->get_billing_email();
324
325 if ( empty( $email ) ) {
326 throw new RouteException(
327 'woocommerce_rest_missing_email_address',
328 __( 'A valid email address is required', 'woocommerce' ),
329 400
330 );
331 }
332
333 if ( ! is_email( $email ) ) {
334 throw new RouteException(
335 'woocommerce_rest_invalid_email_address',
336 sprintf(
337 /* translators: %s provided email. */
338 __( 'The provided email address (%s) is not valid—please provide a valid email address', 'woocommerce' ),
339 esc_html( $email )
340 ),
341 400
342 );
343 }
344 }
345
346 /**
347 * Validates customer address data based on the locale to ensure required fields are set.
348 *
349 * @throws RouteException Exception if invalid data is detected.
350 * @param \WC_Order $order Order object.
351 * @param bool $needs_shipping Whether the order needs shipping.
352 */
353 protected function validate_addresses( \WC_Order $order, bool $needs_shipping ) {
354 $errors = new \WP_Error();
355 $billing_country = $order->get_billing_country();
356 $shipping_country = $order->get_shipping_country();
357
358 if ( $needs_shipping ) {
359 $local_pickup_method_ids = LocalPickupUtils::get_local_pickup_method_ids();
360 $selected_shipping_rates = ShippingUtil::get_selected_shipping_rates_from_packages( WC()->shipping()->get_packages() );
361 $selected_shipping_rates_are_all_local_pickup = ArrayUtil::array_all(
362 $selected_shipping_rates,
363 function ( $rate ) use ( $local_pickup_method_ids ) {
364 return in_array( $rate->get_method_id(), $local_pickup_method_ids, true );
365 }
366 );
367
368 // If only local pickup is selected, we don't need to validate the shipping country.
369 if ( ! $selected_shipping_rates_are_all_local_pickup && ! $this->validate_allowed_country( $shipping_country, (array) wc()->countries->get_shipping_countries() ) ) {
370 $countries = WC()->countries->get_countries();
371 $shipping_country_name = $countries[ $shipping_country ] ?? $shipping_country;
372 throw new RouteException(
373 'woocommerce_rest_invalid_address_country',
374 sprintf(
375 /* translators: %s country name. */
376 esc_html__( 'Sorry, we do not ship orders to the provided country (%s)', 'woocommerce' ),
377 esc_html( $shipping_country_name )
378 ),
379 400,
380 array(
381 'allowed_countries' => array_map( 'esc_html', array_keys( wc()->countries->get_shipping_countries() ) ),
382 )
383 );
384 }
385 }
386
387 if ( ! $this->validate_allowed_country( $billing_country, (array) wc()->countries->get_allowed_countries() ) ) {
388 $countries = WC()->countries->get_countries();
389 $billing_country_name = $countries[ $billing_country ] ?? $billing_country;
390 throw new RouteException(
391 'woocommerce_rest_invalid_address_country',
392 sprintf(
393 /* translators: %s country name. */
394 esc_html__( 'Sorry, we do not allow orders from the provided country (%s)', 'woocommerce' ),
395 esc_html( $billing_country_name )
396 ),
397 400,
398 array(
399 'allowed_countries' => array_map( 'esc_html', array_keys( wc()->countries->get_allowed_countries() ) ),
400 )
401 );
402 }
403
404 if ( $needs_shipping ) {
405 $this->validate_address_fields( $order, 'shipping', $errors );
406 }
407 $this->validate_address_fields( $order, 'billing', $errors );
408
409 if ( ! $errors->has_errors() ) {
410 return;
411 }
412
413 $errors_by_code = array();
414 $error_codes = $errors->get_error_codes();
415
416 foreach ( $error_codes as $code ) {
417 $errors_by_code[ $code ] = $errors->get_error_messages( $code );
418 }
419
420 // Surface errors from first code.
421 foreach ( $errors_by_code as $code => $error_messages ) {
422 throw new RouteException(
423 'woocommerce_rest_invalid_address',
424 sprintf(
425 /* translators: %s Address type. */
426 esc_html__( 'There was a problem with the provided %s:', 'woocommerce' ) . ' ' . esc_html( implode( ', ', $error_messages ) ),
427 'shipping' === $code ? esc_html__( 'shipping address', 'woocommerce' ) : esc_html__( 'billing address', 'woocommerce' )
428 ),
429 400,
430 array(
431 'errors' => $errors_by_code, // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
432 )
433 );
434 }
435 }
436
437 /**
438 * Check all required address fields are set and return errors if not.
439 *
440 * @param string $country Country code.
441 * @param array $allowed_countries List of valid country codes.
442 * @return boolean True if valid.
443 */
444 protected function validate_allowed_country( $country, array $allowed_countries ) {
445 return array_key_exists( $country, $allowed_countries );
446 }
447
448 /**
449 * Check all required address fields are set and return errors if not.
450 *
451 * @param \WC_Order $order Order object.
452 * @param string $address_type billing or shipping address, used in error messages.
453 * @param \WP_Error $errors Error object.
454 */
455 protected function validate_address_fields( \WC_Order $order, $address_type, \WP_Error $errors ) {
456 $all_locales = wc()->countries->get_country_locale();
457 $address = $order->get_address( $address_type );
458 $current_locale = $all_locales[ $address['country'] ] ?? [];
459
460 foreach ( $all_locales['default'] as $key => $value ) {
461 // If $current_locale[ $key ] is not empty, merge it with locale default, otherwise just use default locale.
462 $current_locale[ $key ] = ! empty( $current_locale[ $key ] )
463 ? wp_parse_args( $current_locale[ $key ], $value )
464 : $value;
465 }
466
467 $additional_fields = $this->additional_fields_controller->get_all_fields_from_object( $order, $address_type );
468
469 $address = array_merge( $address, $additional_fields );
470
471 foreach ( $current_locale as $address_field_key => $address_field ) {
472 // Skip validation if field is not required or if it is hidden.
473 if (
474 true !== wc_string_to_bool( $address_field['required'] ?? false ) ||
475 true === wc_string_to_bool( $address_field['hidden'] ?? false )
476 ) {
477 continue;
478 }
479
480 // Check if field is not set, is an empty string, or is an empty array.
481 $is_empty = ! isset( $address[ $address_field_key ] ) ||
482 ( is_string( $address[ $address_field_key ] ) && '' === trim( $address[ $address_field_key ] ) ) ||
483 ( is_array( $address[ $address_field_key ] ) && 0 === count( $address[ $address_field_key ] ) );
484
485 if ( $is_empty ) {
486 /* translators: %s Field label. */
487 $errors->add( $address_type, sprintf( __( '%s is required', 'woocommerce' ), $address_field['label'] ), $address_field_key );
488 }
489 }
490
491 // Validate additional fields.
492 $result = $this->additional_fields_controller->validate_fields_for_location( $address, 'address', $address_type );
493
494 if ( $result->has_errors() ) {
495 // Add errors to main error object but ensure they maintain the billing/shipping error code.
496 foreach ( $result->get_error_codes() as $code ) {
497 $errors->add( $address_type, $result->get_error_message( $code ), $code );
498 }
499 }
500 }
501
502 /**
503 * Check email restrictions of a coupon against the order.
504 *
505 * @throws Exception Exception if invalid data is detected.
506 * @param \WC_Coupon $coupon Coupon object applied to the cart.
507 * @param \WC_Order $order Order object.
508 */
509 protected function validate_coupon_email_restriction( \WC_Coupon $coupon, \WC_Order $order ) {
510 $restrictions = $coupon->get_email_restrictions();
511
512 if ( empty( $restrictions ) ) {
513 return;
514 }
515
516 $check_emails = array();
517
518 // Check the logged-in user's email.
519 $current_user = wp_get_current_user();
520 if ( $current_user->exists() ) {
521 $user_email = trim( sanitize_email( $current_user->user_email ) );
522 if ( ! empty( $user_email ) ) {
523 $check_emails[] = strtolower( $user_email );
524 }
525 }
526
527 // Also check the billing email from the order.
528 $billing_email = $order->get_billing_email();
529 if ( ! empty( $billing_email ) ) {
530 $billing_email = trim( sanitize_email( $billing_email ) );
531 if ( ! empty( $billing_email ) ) {
532 $check_emails[] = strtolower( $billing_email );
533 }
534 }
535
536 // Remove duplicates and empty values.
537 $check_emails = array_unique( array_filter( $check_emails ) );
538
539 if ( ! empty( $check_emails ) && ! DiscountsUtil::is_coupon_emails_allowed( $check_emails, $restrictions ) ) {
540 // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
541 throw new Exception( $coupon->get_coupon_error( \WC_Coupon::E_WC_COUPON_NOT_YOURS_REMOVED ) );
542 }
543 }
544
545 /**
546 * Check usage restrictions of a coupon against the order.
547 *
548 * @throws Exception Exception if invalid data is detected.
549 * @param \WC_Coupon $coupon Coupon object applied to the cart.
550 * @param \WC_Order $order Order object.
551 */
552 protected function validate_coupon_usage_limit( \WC_Coupon $coupon, \WC_Order $order ) {
553 $coupon_usage_limit = $coupon->get_usage_limit_per_user();
554
555 if ( 0 === $coupon_usage_limit ) {
556 return;
557 }
558
559 // First, we check a logged in customer usage count, which happens against their user id, billing email, and account email.
560 if ( $order->get_customer_id() ) {
561 // We get usage per user id and associated emails.
562 $usage_count = $this->get_usage_per_aliases(
563 $coupon,
564 array(
565 $order->get_billing_email(),
566 $order->get_customer_id(),
567 $this->get_email_from_user_id( $order->get_customer_id() ),
568 )
569 );
570 } else {
571 // Otherwise we check if the email doesn't belong to an existing user.
572 // This will get us any user ids for the given billing email.
573 $user_ids = wc_get_container()->get( CustomerSearchService::class )->find_user_ids_by_billing_email_for_coupons_usage_lookup( array( $order->get_billing_email() ) );
574
575 // Convert all found user ids to a list of email addresses.
576 $user_emails = array_map( array( $this, 'get_email_from_user_id' ), $user_ids );
577
578 // This matches a user against the given billing email and gets their ID/email/billing email.
579 $found_user = get_user_by( 'email', $order->get_billing_email() );
580 if ( $found_user ) {
581 $user_ids[] = $found_user->ID;
582 $user_emails[] = $found_user->user_email;
583 $user_emails[] = get_user_meta( $found_user->ID, 'billing_email', true );
584 }
585
586 // Finally, grab usage count for all found IDs and emails.
587 $usage_count = $this->get_usage_per_aliases(
588 $coupon,
589 array_merge(
590 $user_emails,
591 $user_ids,
592 array( $order->get_billing_email() )
593 )
594 );
595 }
596
597 if ( $usage_count >= $coupon_usage_limit ) {
598 throw new Exception( $coupon->get_coupon_error( \WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED ) );
599 }
600 }
601
602 /**
603 * Get user email from user id.
604 *
605 * @param integer $user_id User ID.
606 * @return string Email or empty string.
607 */
608 private function get_email_from_user_id( $user_id ) {
609 $user_data = get_userdata( $user_id );
610 return $user_data ? $user_data->user_email : '';
611 }
612
613 /**
614 * Get the usage count for a coupon based on a list of aliases (ids, emails).
615 *
616 * @param \WC_Coupon $coupon Coupon object applied to the cart.
617 * @param array $aliases List of aliases to check.
618 *
619 * @return integer
620 */
621 private function get_usage_per_aliases( $coupon, $aliases ) {
622 global $wpdb;
623 $aliases = array_unique( array_filter( $aliases ) );
624 $aliases_string = "('" . implode( "','", array_map( 'esc_sql', $aliases ) ) . "')";
625 $usage_count = $wpdb->get_var(
626 $wpdb->prepare(
627 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
628 "SELECT COUNT( meta_id ) FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_used_by' AND meta_value IN {$aliases_string};",
629 $coupon->get_id(),
630 )
631 );
632
633 $data_store = $coupon->get_data_store();
634 // 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).
635 $tentative_usage_count = $data_store->get_tentative_usages_for_user( $coupon->get_id(), $aliases );
636 return $tentative_usage_count + $usage_count;
637 }
638
639 /**
640 * Check there is a shipping method if it requires shipping.
641 *
642 * @throws RouteException Exception if invalid data is detected.
643 * @param boolean $needs_shipping Current order needs shipping.
644 * @param array $chosen_shipping_methods Array of shipping methods.
645 */
646 public function validate_selected_shipping_methods( $needs_shipping, $chosen_shipping_methods = array() ) {
647 if ( ! $needs_shipping ) {
648 return;
649 }
650
651 $exception = new RouteException(
652 'woocommerce_rest_invalid_shipping_option',
653 __( 'Sorry, this order requires a shipping option.', 'woocommerce' ),
654 400,
655 array()
656 );
657
658 if ( ! is_array( $chosen_shipping_methods ) || empty( $chosen_shipping_methods ) ) {
659 throw $exception;
660 }
661
662 // Validate that the chosen shipping methods are valid according to the returned package rates.
663 $packages = WC()->shipping()->get_packages();
664 foreach ( $packages as $package_id => $package ) {
665 $chosen_rate_for_package = $chosen_shipping_methods[ $package_id ];
666 $valid_rate_ids_for_package = wp_list_pluck( $package['rates'], 'id' );
667
668 if ( ! is_string( $chosen_rate_for_package ) || ! ArrayUtils::string_contains_array( $chosen_rate_for_package, $valid_rate_ids_for_package ) ) {
669 throw $exception;
670 }
671 }
672 }
673
674 /**
675 * Validate a given order key against an existing order.
676 *
677 * @throws RouteException Exception if invalid data is detected.
678 * @param integer $order_id Order ID.
679 * @param string $order_key Order key.
680 */
681 public function validate_order_key( $order_id, $order_key ) {
682 $order = wc_get_order( $order_id );
683
684 if ( ! $order || ! $order_key || $order->get_id() !== $order_id || ! hash_equals( $order->get_order_key(), $order_key ) ) {
685 throw new RouteException( 'woocommerce_rest_invalid_order', __( 'Invalid order ID or key provided.', 'woocommerce' ), 401 );
686 }
687 }
688
689 /**
690 * Get errors for order stock on failed orders.
691 *
692 * @throws RouteException Exception if invalid data is detected.
693 * @param integer $order_id Order ID.
694 */
695 public function get_failed_order_stock_error( $order_id ) {
696 $order = wc_get_order( $order_id );
697
698 // Ensure order items are still stocked if paying for a failed order. Pending orders do not need this check because stock is held.
699 if ( ! $order->has_status( wc_get_is_pending_statuses() ) ) {
700 $quantities = array();
701
702 foreach ( $order->get_items() as $item_key => $item ) {
703 if ( $item && is_callable( array( $item, 'get_product' ) ) ) {
704 $product = $item->get_product();
705
706 if ( ! $product ) {
707 continue;
708 }
709
710 $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();
711 }
712 }
713
714 // Stock levels may already have been adjusted for this order (in which case we don't need to worry about checking for low stock).
715 if ( ! $order->get_data_store()->get_stock_reduced( $order->get_id() ) ) {
716 foreach ( $order->get_items() as $item_key => $item ) {
717 if ( $item && is_callable( array( $item, 'get_product' ) ) ) {
718 $product = $item->get_product();
719
720 if ( ! $product ) {
721 continue;
722 }
723
724 /**
725 * Filters whether or not the product is in stock for this pay for order.
726 *
727 * @param boolean True if in stock.
728 * @param \WC_Product $product Product.
729 * @param \WC_Order $order Order.
730 *
731 * @since 9.8.0-dev
732 */
733 if ( ! apply_filters( 'woocommerce_pay_order_product_in_stock', $product->is_in_stock(), $product, $order ) ) {
734 return array(
735 'code' => 'woocommerce_rest_out_of_stock',
736 /* translators: %s: product name */
737 '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() ),
738 );
739 }
740
741 // We only need to check products managing stock, with a limited stock qty.
742 if ( ! $product->managing_stock() || $product->backorders_allowed() ) {
743 continue;
744 }
745
746 // Check stock based on all items in the cart and consider any held stock within pending orders.
747 $held_stock = wc_get_held_stock_quantity( $product, $order->get_id() );
748 $required_stock = $quantities[ $product->get_stock_managed_by_id() ];
749
750 /**
751 * Filters whether or not the product has enough stock.
752 *
753 * @param boolean True if has enough stock.
754 * @param \WC_Product $product Product.
755 * @param \WC_Order $order Order.
756 *
757 * @since 9.8.0-dev
758 */
759 if ( ! apply_filters( 'woocommerce_pay_order_product_has_enough_stock', ( $product->get_stock_quantity() >= ( $held_stock + $required_stock ) ), $product, $order ) ) {
760 /* translators: 1: product name 2: quantity in stock */
761 return array(
762 'code' => 'woocommerce_rest_out_of_stock',
763 /* translators: %s: product name */
764 '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 ) ),
765 );
766 }
767 }
768 }
769 }
770 }
771
772 return null;
773 }
774
775 /**
776 * Changes default order status to draft for orders created via this API.
777 *
778 * @return string
779 */
780 public function default_order_status() {
781 return 'checkout-draft';
782 }
783
784 /**
785 * Create order line items.
786 *
787 * @param \WC_Order $order The order object to update.
788 */
789 protected function update_line_items_from_cart( \WC_Order $order ) {
790 $cart_controller = new CartController();
791 $cart = $cart_controller->get_cart_instance();
792 $cart_hashes = $cart_controller->get_cart_hashes();
793
794 if ( $order->get_cart_hash() !== $cart_hashes['line_items'] ) {
795 $order->set_cart_hash( $cart_hashes['line_items'] );
796 $order->remove_order_items( OrderItemType::LINE_ITEM );
797 wc()->checkout->create_order_line_items( $order, $cart );
798 }
799
800 if ( $order->get_meta( '_shipping_hash' ) !== $cart_hashes['shipping'] ) {
801 $order->update_meta_data( '_shipping_hash', $cart_hashes['shipping'] );
802 $order->remove_order_items( OrderItemType::SHIPPING );
803 wc()->checkout->create_order_shipping_lines( $order, wc()->session->get( 'chosen_shipping_methods' ), wc()->shipping()->get_packages() );
804 }
805
806 if ( $order->get_meta( '_coupons_hash' ) !== $cart_hashes['coupons'] ) {
807 $order->remove_order_items( OrderItemType::COUPON );
808 $order->update_meta_data( '_coupons_hash', $cart_hashes['coupons'] );
809 wc()->checkout->create_order_coupon_lines( $order, $cart );
810 }
811
812 if ( $order->get_meta( '_fees_hash' ) !== $cart_hashes['fees'] ) {
813 $order->update_meta_data( '_fees_hash', $cart_hashes['fees'] );
814 $order->remove_order_items( OrderItemType::FEE );
815 wc()->checkout->create_order_fee_lines( $order, $cart );
816 }
817
818 if ( $order->get_meta( '_taxes_hash' ) !== $cart_hashes['taxes'] ) {
819 $order->update_meta_data( '_taxes_hash', $cart_hashes['taxes'] );
820 $order->remove_order_items( OrderItemType::TAX );
821 wc()->checkout->create_order_tax_lines( $order, $cart );
822 }
823 }
824
825 /**
826 * Update address data from cart and/or customer session data.
827 *
828 * @param \WC_Order $order The order object to update.
829 */
830 protected function update_addresses_from_cart( \WC_Order $order ) {
831 $order->set_props(
832 array(
833 'billing_first_name' => wc()->customer->get_billing_first_name(),
834 'billing_last_name' => wc()->customer->get_billing_last_name(),
835 'billing_company' => wc()->customer->get_billing_company(),
836 'billing_address_1' => wc()->customer->get_billing_address_1(),
837 'billing_address_2' => wc()->customer->get_billing_address_2(),
838 'billing_city' => wc()->customer->get_billing_city(),
839 'billing_state' => wc()->customer->get_billing_state(),
840 'billing_postcode' => wc()->customer->get_billing_postcode(),
841 'billing_country' => wc()->customer->get_billing_country(),
842 'billing_email' => wc()->customer->get_billing_email(),
843 'billing_phone' => wc()->customer->get_billing_phone(),
844 'shipping_first_name' => wc()->customer->get_shipping_first_name(),
845 'shipping_last_name' => wc()->customer->get_shipping_last_name(),
846 'shipping_company' => wc()->customer->get_shipping_company(),
847 'shipping_address_1' => wc()->customer->get_shipping_address_1(),
848 'shipping_address_2' => wc()->customer->get_shipping_address_2(),
849 'shipping_city' => wc()->customer->get_shipping_city(),
850 'shipping_state' => wc()->customer->get_shipping_state(),
851 'shipping_postcode' => wc()->customer->get_shipping_postcode(),
852 'shipping_country' => wc()->customer->get_shipping_country(),
853 'shipping_phone' => wc()->customer->get_shipping_phone(),
854 )
855 );
856 $this->additional_fields_controller->sync_order_additional_fields_with_customer( $order, wc()->customer );
857 }
858 }
859