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