Nessuna descrizione

class-wc-checkout.php 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. <?php
  2. /**
  3. * Checkout functionality
  4. *
  5. * The WooCommerce checkout class handles the checkout process, collecting user data and processing the payment.
  6. *
  7. * @package WooCommerce\Classes
  8. * @version 3.4.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Checkout class.
  13. */
  14. class WC_Checkout {
  15. /**
  16. * The single instance of the class.
  17. *
  18. * @var WC_Checkout|null
  19. */
  20. protected static $instance = null;
  21. /**
  22. * Checkout fields are stored here.
  23. *
  24. * @var array|null
  25. */
  26. protected $fields = null;
  27. /**
  28. * Holds posted data for backwards compatibility.
  29. *
  30. * @var array
  31. */
  32. protected $legacy_posted_data = array();
  33. /**
  34. * Caches customer object. @see get_value.
  35. *
  36. * @var WC_Customer
  37. */
  38. private $logged_in_customer = null;
  39. /**
  40. * Gets the main WC_Checkout Instance.
  41. *
  42. * @since 2.1
  43. * @static
  44. * @return WC_Checkout Main instance
  45. */
  46. public static function instance() {
  47. if ( is_null( self::$instance ) ) {
  48. self::$instance = new self();
  49. // Hook in actions once.
  50. add_action( 'woocommerce_checkout_billing', array( self::$instance, 'checkout_form_billing' ) );
  51. add_action( 'woocommerce_checkout_shipping', array( self::$instance, 'checkout_form_shipping' ) );
  52. // woocommerce_checkout_init action is ran once when the class is first constructed.
  53. do_action( 'woocommerce_checkout_init', self::$instance );
  54. }
  55. return self::$instance;
  56. }
  57. /**
  58. * See if variable is set. Used to support legacy public variables which are no longer defined.
  59. *
  60. * @param string $key Key.
  61. * @return bool
  62. */
  63. public function __isset( $key ) {
  64. return in_array(
  65. $key,
  66. array(
  67. 'enable_signup',
  68. 'enable_guest_checkout',
  69. 'must_create_account',
  70. 'checkout_fields',
  71. 'posted',
  72. 'shipping_method',
  73. 'payment_method',
  74. 'customer_id',
  75. 'shipping_methods',
  76. ),
  77. true
  78. );
  79. }
  80. /**
  81. * Sets the legacy public variables for backwards compatibility.
  82. *
  83. * @param string $key Key.
  84. * @param mixed $value Value.
  85. */
  86. public function __set( $key, $value ) {
  87. switch ( $key ) {
  88. case 'enable_signup':
  89. $bool_value = wc_string_to_bool( $value );
  90. if ( $bool_value !== $this->is_registration_enabled() ) {
  91. remove_filter( 'woocommerce_checkout_registration_enabled', '__return_true', 0 );
  92. remove_filter( 'woocommerce_checkout_registration_enabled', '__return_false', 0 );
  93. add_filter( 'woocommerce_checkout_registration_enabled', $bool_value ? '__return_true' : '__return_false', 0 );
  94. }
  95. break;
  96. case 'enable_guest_checkout':
  97. $bool_value = wc_string_to_bool( $value );
  98. if ( $bool_value === $this->is_registration_required() ) {
  99. remove_filter( 'woocommerce_checkout_registration_required', '__return_true', 0 );
  100. remove_filter( 'woocommerce_checkout_registration_required', '__return_false', 0 );
  101. add_filter( 'woocommerce_checkout_registration_required', $bool_value ? '__return_false' : '__return_true', 0 );
  102. }
  103. break;
  104. case 'checkout_fields':
  105. $this->fields = $value;
  106. break;
  107. case 'shipping_methods':
  108. WC()->session->set( 'chosen_shipping_methods', $value );
  109. break;
  110. case 'posted':
  111. $this->legacy_posted_data = $value;
  112. break;
  113. }
  114. }
  115. /**
  116. * Gets the legacy public variables for backwards compatibility.
  117. *
  118. * @param string $key Key.
  119. * @return array|string
  120. */
  121. public function __get( $key ) {
  122. if ( in_array( $key, array( 'posted', 'shipping_method', 'payment_method' ), true ) && empty( $this->legacy_posted_data ) ) {
  123. $this->legacy_posted_data = $this->get_posted_data();
  124. }
  125. switch ( $key ) {
  126. case 'enable_signup':
  127. return $this->is_registration_enabled();
  128. case 'enable_guest_checkout':
  129. return ! $this->is_registration_required();
  130. case 'must_create_account':
  131. return $this->is_registration_required() && ! is_user_logged_in();
  132. case 'checkout_fields':
  133. return $this->get_checkout_fields();
  134. case 'posted':
  135. wc_doing_it_wrong( 'WC_Checkout->posted', 'Use $_POST directly.', '3.0.0' );
  136. return $this->legacy_posted_data;
  137. case 'shipping_method':
  138. return $this->legacy_posted_data['shipping_method'];
  139. case 'payment_method':
  140. return $this->legacy_posted_data['payment_method'];
  141. case 'customer_id':
  142. return apply_filters( 'woocommerce_checkout_customer_id', get_current_user_id() );
  143. case 'shipping_methods':
  144. return (array) WC()->session->get( 'chosen_shipping_methods' );
  145. }
  146. }
  147. /**
  148. * Cloning is forbidden.
  149. */
  150. public function __clone() {
  151. wc_doing_it_wrong( __FUNCTION__, __( 'Cloning is forbidden.', 'woocommerce' ), '2.1' );
  152. }
  153. /**
  154. * Unserializing instances of this class is forbidden.
  155. */
  156. public function __wakeup() {
  157. wc_doing_it_wrong( __FUNCTION__, __( 'Unserializing instances of this class is forbidden.', 'woocommerce' ), '2.1' );
  158. }
  159. /**
  160. * Is registration required to checkout?
  161. *
  162. * @since 3.0.0
  163. * @return boolean
  164. */
  165. public function is_registration_required() {
  166. return apply_filters( 'woocommerce_checkout_registration_required', 'yes' !== get_option( 'woocommerce_enable_guest_checkout' ) );
  167. }
  168. /**
  169. * Is registration enabled on the checkout page?
  170. *
  171. * @since 3.0.0
  172. * @return boolean
  173. */
  174. public function is_registration_enabled() {
  175. return apply_filters( 'woocommerce_checkout_registration_enabled', 'yes' === get_option( 'woocommerce_enable_signup_and_login_from_checkout' ) );
  176. }
  177. /**
  178. * Get an array of checkout fields.
  179. *
  180. * @param string $fieldset to get.
  181. * @return array
  182. */
  183. public function get_checkout_fields( $fieldset = '' ) {
  184. if ( ! is_null( $this->fields ) ) {
  185. return $fieldset ? $this->fields[ $fieldset ] : $this->fields;
  186. }
  187. // Fields are based on billing/shipping country. Grab those values but ensure they are valid for the store before using.
  188. $billing_country = $this->get_value( 'billing_country' );
  189. $billing_country = empty( $billing_country ) ? WC()->countries->get_base_country() : $billing_country;
  190. $allowed_countries = WC()->countries->get_allowed_countries();
  191. if ( ! array_key_exists( $billing_country, $allowed_countries ) ) {
  192. $billing_country = current( array_keys( $allowed_countries ) );
  193. }
  194. $shipping_country = $this->get_value( 'shipping_country' );
  195. $shipping_country = empty( $shipping_country ) ? WC()->countries->get_base_country() : $shipping_country;
  196. $allowed_countries = WC()->countries->get_shipping_countries();
  197. if ( ! array_key_exists( $shipping_country, $allowed_countries ) ) {
  198. $shipping_country = current( array_keys( $allowed_countries ) );
  199. }
  200. $this->fields = array(
  201. 'billing' => WC()->countries->get_address_fields(
  202. $billing_country,
  203. 'billing_'
  204. ),
  205. 'shipping' => WC()->countries->get_address_fields(
  206. $shipping_country,
  207. 'shipping_'
  208. ),
  209. 'account' => array(),
  210. 'order' => array(
  211. 'order_comments' => array(
  212. 'type' => 'textarea',
  213. 'class' => array( 'notes' ),
  214. 'label' => __( 'Order notes', 'woocommerce' ),
  215. 'placeholder' => esc_attr__(
  216. 'Notes about your order, e.g. special notes for delivery.',
  217. 'woocommerce'
  218. ),
  219. ),
  220. ),
  221. );
  222. if ( 'no' === get_option( 'woocommerce_registration_generate_username' ) ) {
  223. $this->fields['account']['account_username'] = array(
  224. 'type' => 'text',
  225. 'label' => __( 'Account username', 'woocommerce' ),
  226. 'required' => true,
  227. 'placeholder' => esc_attr__( 'Username', 'woocommerce' ),
  228. );
  229. }
  230. if ( 'no' === get_option( 'woocommerce_registration_generate_password' ) ) {
  231. $this->fields['account']['account_password'] = array(
  232. 'type' => 'password',
  233. 'label' => __( 'Create account password', 'woocommerce' ),
  234. 'required' => true,
  235. 'placeholder' => esc_attr__( 'Password', 'woocommerce' ),
  236. );
  237. }
  238. $this->fields = apply_filters( 'woocommerce_checkout_fields', $this->fields );
  239. foreach ( $this->fields as $field_type => $fields ) {
  240. // Sort each of the checkout field sections based on priority.
  241. uasort( $this->fields[ $field_type ], 'wc_checkout_fields_uasort_comparison' );
  242. // Add accessibility labels to fields that have placeholders.
  243. foreach ( $fields as $single_field_type => $field ) {
  244. if ( empty( $field['label'] ) && ! empty( $field['placeholder'] ) ) {
  245. $this->fields[ $field_type ][ $single_field_type ]['label'] = $field['placeholder'];
  246. $this->fields[ $field_type ][ $single_field_type ]['label_class'] = array( 'screen-reader-text' );
  247. }
  248. }
  249. }
  250. return $fieldset ? $this->fields[ $fieldset ] : $this->fields;
  251. }
  252. /**
  253. * When we process the checkout, lets ensure cart items are rechecked to prevent checkout.
  254. */
  255. public function check_cart_items() {
  256. do_action( 'woocommerce_check_cart_items' );
  257. }
  258. /**
  259. * Output the billing form.
  260. */
  261. public function checkout_form_billing() {
  262. wc_get_template( 'checkout/form-billing.php', array( 'checkout' => $this ) );
  263. }
  264. /**
  265. * Output the shipping form.
  266. */
  267. public function checkout_form_shipping() {
  268. wc_get_template( 'checkout/form-shipping.php', array( 'checkout' => $this ) );
  269. }
  270. /**
  271. * Create an order. Error codes:
  272. * 520 - Cannot insert order into the database.
  273. * 521 - Cannot get order after creation.
  274. * 522 - Cannot update order.
  275. * 525 - Cannot create line item.
  276. * 526 - Cannot create fee item.
  277. * 527 - Cannot create shipping item.
  278. * 528 - Cannot create tax item.
  279. * 529 - Cannot create coupon item.
  280. *
  281. * @throws Exception When checkout validation fails.
  282. * @param array $data Posted data.
  283. * @return int|WP_ERROR
  284. */
  285. public function create_order( $data ) {
  286. // Give plugins the opportunity to create an order themselves.
  287. $order_id = apply_filters( 'woocommerce_create_order', null, $this );
  288. if ( $order_id ) {
  289. return $order_id;
  290. }
  291. try {
  292. $order_id = absint( WC()->session->get( 'order_awaiting_payment' ) );
  293. $cart_hash = WC()->cart->get_cart_hash();
  294. $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
  295. $order = $order_id ? wc_get_order( $order_id ) : null;
  296. /**
  297. * If there is an order pending payment, we can resume it here so
  298. * long as it has not changed. If the order has changed, i.e.
  299. * different items or cost, create a new order. We use a hash to
  300. * detect changes which is based on cart items + order total.
  301. */
  302. if ( $order && $order->has_cart_hash( $cart_hash ) && $order->has_status( array( 'pending', 'failed' ) ) ) {
  303. // Action for 3rd parties.
  304. do_action( 'woocommerce_resume_order', $order_id );
  305. // Remove all items - we will re-add them later.
  306. $order->remove_order_items();
  307. } else {
  308. $order = new WC_Order();
  309. }
  310. $fields_prefix = array(
  311. 'shipping' => true,
  312. 'billing' => true,
  313. );
  314. $shipping_fields = array(
  315. 'shipping_method' => true,
  316. 'shipping_total' => true,
  317. 'shipping_tax' => true,
  318. );
  319. foreach ( $data as $key => $value ) {
  320. if ( is_callable( array( $order, "set_{$key}" ) ) ) {
  321. $order->{"set_{$key}"}( $value );
  322. // Store custom fields prefixed with wither shipping_ or billing_. This is for backwards compatibility with 2.6.x.
  323. } elseif ( isset( $fields_prefix[ current( explode( '_', $key ) ) ] ) ) {
  324. if ( ! isset( $shipping_fields[ $key ] ) ) {
  325. $order->update_meta_data( '_' . $key, $value );
  326. }
  327. }
  328. }
  329. $order->hold_applied_coupons( $data['billing_email'] );
  330. $order->set_created_via( 'checkout' );
  331. $order->set_cart_hash( $cart_hash );
  332. $order->set_customer_id( apply_filters( 'woocommerce_checkout_customer_id', get_current_user_id() ) );
  333. $order->set_currency( get_woocommerce_currency() );
  334. $order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) );
  335. $order->set_customer_ip_address( WC_Geolocation::get_ip_address() );
  336. $order->set_customer_user_agent( wc_get_user_agent() );
  337. $order->set_customer_note( isset( $data['order_comments'] ) ? $data['order_comments'] : '' );
  338. $order->set_payment_method( isset( $available_gateways[ $data['payment_method'] ] ) ? $available_gateways[ $data['payment_method'] ] : $data['payment_method'] );
  339. $this->set_data_from_cart( $order );
  340. /**
  341. * Action hook to adjust order before save.
  342. *
  343. * @since 3.0.0
  344. */
  345. do_action( 'woocommerce_checkout_create_order', $order, $data );
  346. // Save the order.
  347. $order_id = $order->save();
  348. /**
  349. * Action hook fired after an order is created used to add custom meta to the order.
  350. *
  351. * @since 3.0.0
  352. */
  353. do_action( 'woocommerce_checkout_update_order_meta', $order_id, $data );
  354. /**
  355. * Action hook fired after an order is created.
  356. *
  357. * @since 4.3.0
  358. */
  359. do_action( 'woocommerce_checkout_order_created', $order );
  360. return $order_id;
  361. } catch ( Exception $e ) {
  362. if ( $order && $order instanceof WC_Order ) {
  363. $order->get_data_store()->release_held_coupons( $order );
  364. /**
  365. * Action hook fired when an order is discarded due to Exception.
  366. *
  367. * @since 4.3.0
  368. */
  369. do_action( 'woocommerce_checkout_order_exception', $order );
  370. }
  371. return new WP_Error( 'checkout-error', $e->getMessage() );
  372. }
  373. }
  374. /**
  375. * Copy line items, tax, totals data from cart to order.
  376. *
  377. * @param WC_Order $order Order object.
  378. *
  379. * @throws Exception When unable to create order.
  380. */
  381. public function set_data_from_cart( &$order ) {
  382. $order_vat_exempt = WC()->cart->get_customer()->get_is_vat_exempt() ? 'yes' : 'no';
  383. $order->add_meta_data( 'is_vat_exempt', $order_vat_exempt, true );
  384. $order->set_shipping_total( WC()->cart->get_shipping_total() );
  385. $order->set_discount_total( WC()->cart->get_discount_total() );
  386. $order->set_discount_tax( WC()->cart->get_discount_tax() );
  387. $order->set_cart_tax( WC()->cart->get_cart_contents_tax() + WC()->cart->get_fee_tax() );
  388. $order->set_shipping_tax( WC()->cart->get_shipping_tax() );
  389. $order->set_total( WC()->cart->get_total( 'edit' ) );
  390. $this->create_order_line_items( $order, WC()->cart );
  391. $this->create_order_fee_lines( $order, WC()->cart );
  392. $this->create_order_shipping_lines( $order, WC()->session->get( 'chosen_shipping_methods' ), WC()->shipping()->get_packages() );
  393. $this->create_order_tax_lines( $order, WC()->cart );
  394. $this->create_order_coupon_lines( $order, WC()->cart );
  395. }
  396. /**
  397. * Add line items to the order.
  398. *
  399. * @param WC_Order $order Order instance.
  400. * @param WC_Cart $cart Cart instance.
  401. */
  402. public function create_order_line_items( &$order, $cart ) {
  403. foreach ( $cart->get_cart() as $cart_item_key => $values ) {
  404. /**
  405. * Filter hook to get initial item object.
  406. *
  407. * @since 3.1.0
  408. */
  409. $item = apply_filters( 'woocommerce_checkout_create_order_line_item_object', new WC_Order_Item_Product(), $cart_item_key, $values, $order );
  410. $product = $values['data'];
  411. $item->legacy_values = $values; // @deprecated 4.4.0 For legacy actions.
  412. $item->legacy_cart_item_key = $cart_item_key; // @deprecated 4.4.0 For legacy actions.
  413. $item->set_props(
  414. array(
  415. 'quantity' => $values['quantity'],
  416. 'variation' => $values['variation'],
  417. 'subtotal' => $values['line_subtotal'],
  418. 'total' => $values['line_total'],
  419. 'subtotal_tax' => $values['line_subtotal_tax'],
  420. 'total_tax' => $values['line_tax'],
  421. 'taxes' => $values['line_tax_data'],
  422. )
  423. );
  424. if ( $product ) {
  425. $item->set_props(
  426. array(
  427. 'name' => $product->get_name(),
  428. 'tax_class' => $product->get_tax_class(),
  429. 'product_id' => $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id(),
  430. 'variation_id' => $product->is_type( 'variation' ) ? $product->get_id() : 0,
  431. )
  432. );
  433. }
  434. $item->set_backorder_meta();
  435. /**
  436. * Action hook to adjust item before save.
  437. *
  438. * @since 3.0.0
  439. */
  440. do_action( 'woocommerce_checkout_create_order_line_item', $item, $cart_item_key, $values, $order );
  441. // Add item to order and save.
  442. $order->add_item( $item );
  443. }
  444. }
  445. /**
  446. * Add fees to the order.
  447. *
  448. * @param WC_Order $order Order instance.
  449. * @param WC_Cart $cart Cart instance.
  450. */
  451. public function create_order_fee_lines( &$order, $cart ) {
  452. foreach ( $cart->get_fees() as $fee_key => $fee ) {
  453. $item = new WC_Order_Item_Fee();
  454. $item->legacy_fee = $fee; // @deprecated 4.4.0 For legacy actions.
  455. $item->legacy_fee_key = $fee_key; // @deprecated 4.4.0 For legacy actions.
  456. $item->set_props(
  457. array(
  458. 'name' => $fee->name,
  459. 'tax_class' => $fee->taxable ? $fee->tax_class : 0,
  460. 'amount' => $fee->amount,
  461. 'total' => $fee->total,
  462. 'total_tax' => $fee->tax,
  463. 'taxes' => array(
  464. 'total' => $fee->tax_data,
  465. ),
  466. )
  467. );
  468. /**
  469. * Action hook to adjust item before save.
  470. *
  471. * @since 3.0.0
  472. */
  473. do_action( 'woocommerce_checkout_create_order_fee_item', $item, $fee_key, $fee, $order );
  474. // Add item to order and save.
  475. $order->add_item( $item );
  476. }
  477. }
  478. /**
  479. * Add shipping lines to the order.
  480. *
  481. * @param WC_Order $order Order Instance.
  482. * @param array $chosen_shipping_methods Chosen shipping methods.
  483. * @param array $packages Packages.
  484. */
  485. public function create_order_shipping_lines( &$order, $chosen_shipping_methods, $packages ) {
  486. foreach ( $packages as $package_key => $package ) {
  487. if ( isset( $chosen_shipping_methods[ $package_key ], $package['rates'][ $chosen_shipping_methods[ $package_key ] ] ) ) {
  488. $shipping_rate = $package['rates'][ $chosen_shipping_methods[ $package_key ] ];
  489. $item = new WC_Order_Item_Shipping();
  490. $item->legacy_package_key = $package_key; // @deprecated 4.4.0 For legacy actions.
  491. $item->set_props(
  492. array(
  493. 'method_title' => $shipping_rate->label,
  494. 'method_id' => $shipping_rate->method_id,
  495. 'instance_id' => $shipping_rate->instance_id,
  496. 'total' => wc_format_decimal( $shipping_rate->cost ),
  497. 'taxes' => array(
  498. 'total' => $shipping_rate->taxes,
  499. ),
  500. )
  501. );
  502. foreach ( $shipping_rate->get_meta_data() as $key => $value ) {
  503. $item->add_meta_data( $key, $value, true );
  504. }
  505. /**
  506. * Action hook to adjust item before save.
  507. *
  508. * @since 3.0.0
  509. */
  510. do_action( 'woocommerce_checkout_create_order_shipping_item', $item, $package_key, $package, $order );
  511. // Add item to order and save.
  512. $order->add_item( $item );
  513. }
  514. }
  515. }
  516. /**
  517. * Add tax lines to the order.
  518. *
  519. * @param WC_Order $order Order instance.
  520. * @param WC_Cart $cart Cart instance.
  521. */
  522. public function create_order_tax_lines( &$order, $cart ) {
  523. foreach ( array_keys( $cart->get_cart_contents_taxes() + $cart->get_shipping_taxes() + $cart->get_fee_taxes() ) as $tax_rate_id ) {
  524. if ( $tax_rate_id && apply_filters( 'woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated' ) !== $tax_rate_id ) {
  525. $item = new WC_Order_Item_Tax();
  526. $item->set_props(
  527. array(
  528. 'rate_id' => $tax_rate_id,
  529. 'tax_total' => $cart->get_tax_amount( $tax_rate_id ),
  530. 'shipping_tax_total' => $cart->get_shipping_tax_amount( $tax_rate_id ),
  531. 'rate_code' => WC_Tax::get_rate_code( $tax_rate_id ),
  532. 'label' => WC_Tax::get_rate_label( $tax_rate_id ),
  533. 'compound' => WC_Tax::is_compound( $tax_rate_id ),
  534. 'rate_percent' => WC_Tax::get_rate_percent_value( $tax_rate_id ),
  535. )
  536. );
  537. /**
  538. * Action hook to adjust item before save.
  539. *
  540. * @since 3.0.0
  541. */
  542. do_action( 'woocommerce_checkout_create_order_tax_item', $item, $tax_rate_id, $order );
  543. // Add item to order and save.
  544. $order->add_item( $item );
  545. }
  546. }
  547. }
  548. /**
  549. * Add coupon lines to the order.
  550. *
  551. * @param WC_Order $order Order instance.
  552. * @param WC_Cart $cart Cart instance.
  553. */
  554. public function create_order_coupon_lines( &$order, $cart ) {
  555. foreach ( $cart->get_coupons() as $code => $coupon ) {
  556. $item = new WC_Order_Item_Coupon();
  557. $item->set_props(
  558. array(
  559. 'code' => $code,
  560. 'discount' => $cart->get_coupon_discount_amount( $code ),
  561. 'discount_tax' => $cart->get_coupon_discount_tax_amount( $code ),
  562. )
  563. );
  564. // Avoid storing used_by - it's not needed and can get large.
  565. $coupon_data = $coupon->get_data();
  566. unset( $coupon_data['used_by'] );
  567. $item->add_meta_data( 'coupon_data', $coupon_data );
  568. /**
  569. * Action hook to adjust item before save.
  570. *
  571. * @since 3.0.0
  572. */
  573. do_action( 'woocommerce_checkout_create_order_coupon_item', $item, $code, $coupon, $order );
  574. // Add item to order and save.
  575. $order->add_item( $item );
  576. }
  577. }
  578. /**
  579. * See if a fieldset should be skipped.
  580. *
  581. * @since 3.0.0
  582. * @param string $fieldset_key Fieldset key.
  583. * @param array $data Posted data.
  584. * @return bool
  585. */
  586. protected function maybe_skip_fieldset( $fieldset_key, $data ) {
  587. if ( 'shipping' === $fieldset_key && ( ! $data['ship_to_different_address'] || ! WC()->cart->needs_shipping_address() ) ) {
  588. return true;
  589. }
  590. if ( 'account' === $fieldset_key && ( is_user_logged_in() || ( ! $this->is_registration_required() && empty( $data['createaccount'] ) ) ) ) {
  591. return true;
  592. }
  593. return false;
  594. }
  595. /**
  596. * Get posted data from the checkout form.
  597. *
  598. * @since 3.1.0
  599. * @return array of data.
  600. */
  601. public function get_posted_data() {
  602. // phpcs:disable WordPress.Security.NonceVerification.Missing
  603. $data = array(
  604. 'terms' => (int) isset( $_POST['terms'] ),
  605. 'createaccount' => (int) ( $this->is_registration_enabled() ? ! empty( $_POST['createaccount'] ) : false ),
  606. 'payment_method' => isset( $_POST['payment_method'] ) ? wc_clean( wp_unslash( $_POST['payment_method'] ) ) : '',
  607. 'shipping_method' => isset( $_POST['shipping_method'] ) ? wc_clean( wp_unslash( $_POST['shipping_method'] ) ) : '',
  608. 'ship_to_different_address' => ! empty( $_POST['ship_to_different_address'] ) && ! wc_ship_to_billing_address_only(),
  609. 'woocommerce_checkout_update_totals' => isset( $_POST['woocommerce_checkout_update_totals'] ),
  610. );
  611. // phpcs:enable WordPress.Security.NonceVerification.Missing
  612. $skipped = array();
  613. $form_was_shown = isset( $_POST['woocommerce-process-checkout-nonce'] ); // phpcs:disable WordPress.Security.NonceVerification.Missing
  614. foreach ( $this->get_checkout_fields() as $fieldset_key => $fieldset ) {
  615. if ( $this->maybe_skip_fieldset( $fieldset_key, $data ) ) {
  616. $skipped[] = $fieldset_key;
  617. continue;
  618. }
  619. foreach ( $fieldset as $key => $field ) {
  620. $type = sanitize_title( isset( $field['type'] ) ? $field['type'] : 'text' );
  621. if ( isset( $_POST[ $key ] ) && '' !== $_POST[ $key ] ) { // phpcs:disable WordPress.Security.NonceVerification.Missing
  622. $value = wp_unslash( $_POST[ $key ] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
  623. } elseif ( isset( $field['default'] ) && 'checkbox' !== $type && ! $form_was_shown ) {
  624. $value = $field['default'];
  625. } else {
  626. $value = '';
  627. }
  628. if ( '' !== $value ) {
  629. switch ( $type ) {
  630. case 'checkbox':
  631. $value = 1;
  632. break;
  633. case 'multiselect':
  634. $value = implode( ', ', wc_clean( $value ) );
  635. break;
  636. case 'textarea':
  637. $value = wc_sanitize_textarea( $value );
  638. break;
  639. case 'password':
  640. break;
  641. default:
  642. $value = wc_clean( $value );
  643. break;
  644. }
  645. }
  646. $data[ $key ] = apply_filters( 'woocommerce_process_checkout_' . $type . '_field', apply_filters( 'woocommerce_process_checkout_field_' . $key, $value ) );
  647. }
  648. }
  649. if ( in_array( 'shipping', $skipped, true ) && ( WC()->cart->needs_shipping_address() || wc_ship_to_billing_address_only() ) ) {
  650. foreach ( $this->get_checkout_fields( 'shipping' ) as $key => $field ) {
  651. $data[ $key ] = isset( $data[ 'billing_' . substr( $key, 9 ) ] ) ? $data[ 'billing_' . substr( $key, 9 ) ] : '';
  652. }
  653. }
  654. // BW compatibility.
  655. $this->legacy_posted_data = $data;
  656. return apply_filters( 'woocommerce_checkout_posted_data', $data );
  657. }
  658. /**
  659. * Validates the posted checkout data based on field properties.
  660. *
  661. * @since 3.0.0
  662. * @param array $data An array of posted data.
  663. * @param WP_Error $errors Validation error.
  664. */
  665. protected function validate_posted_data( &$data, &$errors ) {
  666. foreach ( $this->get_checkout_fields() as $fieldset_key => $fieldset ) {
  667. $validate_fieldset = true;
  668. if ( $this->maybe_skip_fieldset( $fieldset_key, $data ) ) {
  669. $validate_fieldset = false;
  670. }
  671. foreach ( $fieldset as $key => $field ) {
  672. if ( ! isset( $data[ $key ] ) ) {
  673. continue;
  674. }
  675. $required = ! empty( $field['required'] );
  676. $format = array_filter( isset( $field['validate'] ) ? (array) $field['validate'] : array() );
  677. $field_label = isset( $field['label'] ) ? $field['label'] : '';
  678. if ( $validate_fieldset &&
  679. ( isset( $field['type'] ) && 'country' === $field['type'] && '' !== $data[ $key ] ) &&
  680. ! WC()->countries->country_exists( $data[ $key ] ) ) {
  681. /* translators: ISO 3166-1 alpha-2 country code */
  682. $errors->add( $key . '_validation', sprintf( __( "'%s' is not a valid country code.", 'woocommerce' ), $data[ $key ] ) );
  683. }
  684. switch ( $fieldset_key ) {
  685. case 'shipping':
  686. /* translators: %s: field name */
  687. $field_label = sprintf( _x( 'Shipping %s', 'checkout-validation', 'woocommerce' ), $field_label );
  688. break;
  689. case 'billing':
  690. /* translators: %s: field name */
  691. $field_label = sprintf( _x( 'Billing %s', 'checkout-validation', 'woocommerce' ), $field_label );
  692. break;
  693. }
  694. if ( in_array( 'postcode', $format, true ) ) {
  695. $country = isset( $data[ $fieldset_key . '_country' ] ) ? $data[ $fieldset_key . '_country' ] : WC()->customer->{"get_{$fieldset_key}_country"}();
  696. $data[ $key ] = wc_format_postcode( $data[ $key ], $country );
  697. if ( $validate_fieldset && '' !== $data[ $key ] && ! WC_Validation::is_postcode( $data[ $key ], $country ) ) {
  698. switch ( $country ) {
  699. case 'IE':
  700. /* translators: %1$s: field name, %2$s finder.eircode.ie URL */
  701. $postcode_validation_notice = sprintf( __( '%1$s is not valid. You can look up the correct Eircode <a target="_blank" href="%2$s">here</a>.', 'woocommerce' ), '<strong>' . esc_html( $field_label ) . '</strong>', 'https://finder.eircode.ie' );
  702. break;
  703. default:
  704. /* translators: %s: field name */
  705. $postcode_validation_notice = sprintf( __( '%s is not a valid postcode / ZIP.', 'woocommerce' ), '<strong>' . esc_html( $field_label ) . '</strong>' );
  706. }
  707. $errors->add( $key . '_validation', apply_filters( 'woocommerce_checkout_postcode_validation_notice', $postcode_validation_notice, $country, $data[ $key ] ), array( 'id' => $key ) );
  708. }
  709. }
  710. if ( in_array( 'phone', $format, true ) ) {
  711. if ( $validate_fieldset && '' !== $data[ $key ] && ! WC_Validation::is_phone( $data[ $key ] ) ) {
  712. /* translators: %s: phone number */
  713. $errors->add( $key . '_validation', sprintf( __( '%s is not a valid phone number.', 'woocommerce' ), '<strong>' . esc_html( $field_label ) . '</strong>' ), array( 'id' => $key ) );
  714. }
  715. }
  716. if ( in_array( 'email', $format, true ) && '' !== $data[ $key ] ) {
  717. $email_is_valid = is_email( $data[ $key ] );
  718. $data[ $key ] = sanitize_email( $data[ $key ] );
  719. if ( $validate_fieldset && ! $email_is_valid ) {
  720. /* translators: %s: email address */
  721. $errors->add( $key . '_validation', sprintf( __( '%s is not a valid email address.', 'woocommerce' ), '<strong>' . esc_html( $field_label ) . '</strong>' ), array( 'id' => $key ) );
  722. continue;
  723. }
  724. }
  725. if ( '' !== $data[ $key ] && in_array( 'state', $format, true ) ) {
  726. $country = isset( $data[ $fieldset_key . '_country' ] ) ? $data[ $fieldset_key . '_country' ] : WC()->customer->{"get_{$fieldset_key}_country"}();
  727. $valid_states = WC()->countries->get_states( $country );
  728. if ( ! empty( $valid_states ) && is_array( $valid_states ) && count( $valid_states ) > 0 ) {
  729. $valid_state_values = array_map( 'wc_strtoupper', array_flip( array_map( 'wc_strtoupper', $valid_states ) ) );
  730. $data[ $key ] = wc_strtoupper( $data[ $key ] );
  731. if ( isset( $valid_state_values[ $data[ $key ] ] ) ) {
  732. // With this part we consider state value to be valid as well, convert it to the state key for the valid_states check below.
  733. $data[ $key ] = $valid_state_values[ $data[ $key ] ];
  734. }
  735. if ( $validate_fieldset && ! in_array( $data[ $key ], $valid_state_values, true ) ) {
  736. /* translators: 1: state field 2: valid states */
  737. $errors->add( $key . '_validation', sprintf( __( '%1$s is not valid. Please enter one of the following: %2$s', 'woocommerce' ), '<strong>' . esc_html( $field_label ) . '</strong>', implode( ', ', $valid_states ) ), array( 'id' => $key ) );
  738. }
  739. }
  740. }
  741. if ( $validate_fieldset && $required && '' === $data[ $key ] ) {
  742. /* translators: %s: field name */
  743. $errors->add( $key . '_required', apply_filters( 'woocommerce_checkout_required_field_notice', sprintf( __( '%s is a required field.', 'woocommerce' ), '<strong>' . esc_html( $field_label ) . '</strong>' ), $field_label ), array( 'id' => $key ) );
  744. }
  745. }
  746. }
  747. }
  748. /**
  749. * Validates that the checkout has enough info to proceed.
  750. *
  751. * @since 3.0.0
  752. * @param array $data An array of posted data.
  753. * @param WP_Error $errors Validation errors.
  754. */
  755. protected function validate_checkout( &$data, &$errors ) {
  756. $this->validate_posted_data( $data, $errors );
  757. $this->check_cart_items();
  758. // phpcs:ignore WordPress.Security.NonceVerification.Missing
  759. if ( empty( $data['woocommerce_checkout_update_totals'] ) && empty( $data['terms'] ) && ! empty( $_POST['terms-field'] ) ) {
  760. $errors->add( 'terms', __( 'Please read and accept the terms and conditions to proceed with your order.', 'woocommerce' ) );
  761. }
  762. if ( WC()->cart->needs_shipping() ) {
  763. $shipping_country = isset( $data['shipping_country'] ) ? $data['shipping_country'] : WC()->customer->get_shipping_country();
  764. if ( empty( $shipping_country ) ) {
  765. $errors->add( 'shipping', __( 'Please enter an address to continue.', 'woocommerce' ) );
  766. } elseif ( ! in_array( $shipping_country, array_keys( WC()->countries->get_shipping_countries() ), true ) ) {
  767. if ( WC()->countries->country_exists( $shipping_country ) ) {
  768. /* translators: %s: shipping location (prefix e.g. 'to' + ISO 3166-1 alpha-2 country code) */
  769. $errors->add( 'shipping', sprintf( __( 'Unfortunately <strong>we do not ship %s</strong>. Please enter an alternative shipping address.', 'woocommerce' ), WC()->countries->shipping_to_prefix() . ' ' . $shipping_country ) );
  770. }
  771. } else {
  772. $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
  773. foreach ( WC()->shipping()->get_packages() as $i => $package ) {
  774. if ( ! isset( $chosen_shipping_methods[ $i ], $package['rates'][ $chosen_shipping_methods[ $i ] ] ) ) {
  775. $errors->add( 'shipping', __( 'No shipping method has been selected. Please double check your address, or contact us if you need any help.', 'woocommerce' ) );
  776. }
  777. }
  778. }
  779. }
  780. if ( WC()->cart->needs_payment() ) {
  781. $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
  782. if ( ! isset( $available_gateways[ $data['payment_method'] ] ) ) {
  783. $errors->add( 'payment', __( 'Invalid payment method.', 'woocommerce' ) );
  784. } else {
  785. $available_gateways[ $data['payment_method'] ]->validate_fields();
  786. }
  787. }
  788. do_action( 'woocommerce_after_checkout_validation', $data, $errors );
  789. }
  790. /**
  791. * Set address field for customer.
  792. *
  793. * @since 3.0.7
  794. * @param string $field String to update.
  795. * @param string $key Field key.
  796. * @param array $data Array of data to get the value from.
  797. */
  798. protected function set_customer_address_fields( $field, $key, $data ) {
  799. $billing_value = null;
  800. $shipping_value = null;
  801. if ( isset( $data[ "billing_{$field}" ] ) && is_callable( array( WC()->customer, "set_billing_{$field}" ) ) ) {
  802. $billing_value = $data[ "billing_{$field}" ];
  803. $shipping_value = $data[ "billing_{$field}" ];
  804. }
  805. if ( isset( $data[ "shipping_{$field}" ] ) && is_callable( array( WC()->customer, "set_shipping_{$field}" ) ) ) {
  806. $shipping_value = $data[ "shipping_{$field}" ];
  807. }
  808. if ( ! is_null( $billing_value ) && is_callable( array( WC()->customer, "set_billing_{$field}" ) ) ) {
  809. WC()->customer->{"set_billing_{$field}"}( $billing_value );
  810. }
  811. if ( ! is_null( $shipping_value ) && is_callable( array( WC()->customer, "set_shipping_{$field}" ) ) ) {
  812. WC()->customer->{"set_shipping_{$field}"}( $shipping_value );
  813. }
  814. }
  815. /**
  816. * Update customer and session data from the posted checkout data.
  817. *
  818. * @since 3.0.0
  819. * @param array $data Posted data.
  820. */
  821. protected function update_session( $data ) {
  822. // Update both shipping and billing to the passed billing address first if set.
  823. $address_fields = array(
  824. 'first_name',
  825. 'last_name',
  826. 'company',
  827. 'email',
  828. 'phone',
  829. 'address_1',
  830. 'address_2',
  831. 'city',
  832. 'postcode',
  833. 'state',
  834. 'country',
  835. );
  836. array_walk( $address_fields, array( $this, 'set_customer_address_fields' ), $data );
  837. WC()->customer->save();
  838. // Update customer shipping and payment method to posted method.
  839. $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
  840. if ( is_array( $data['shipping_method'] ) ) {
  841. foreach ( $data['shipping_method'] as $i => $value ) {
  842. $chosen_shipping_methods[ $i ] = $value;
  843. }
  844. }
  845. WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
  846. WC()->session->set( 'chosen_payment_method', $data['payment_method'] );
  847. // Update cart totals now we have customer address.
  848. WC()->cart->calculate_totals();
  849. }
  850. /**
  851. * Process an order that does require payment.
  852. *
  853. * @since 3.0.0
  854. * @param int $order_id Order ID.
  855. * @param string $payment_method Payment method.
  856. */
  857. protected function process_order_payment( $order_id, $payment_method ) {
  858. $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
  859. if ( ! isset( $available_gateways[ $payment_method ] ) ) {
  860. return;
  861. }
  862. // Store Order ID in session so it can be re-used after payment failure.
  863. WC()->session->set( 'order_awaiting_payment', $order_id );
  864. // Process Payment.
  865. $result = $available_gateways[ $payment_method ]->process_payment( $order_id );
  866. // Redirect to success/confirmation/payment page.
  867. if ( isset( $result['result'] ) && 'success' === $result['result'] ) {
  868. $result['order_id'] = $order_id;
  869. $result = apply_filters( 'woocommerce_payment_successful_result', $result, $order_id );
  870. if ( ! is_ajax() ) {
  871. // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
  872. wp_redirect( $result['redirect'] );
  873. exit;
  874. }
  875. wp_send_json( $result );
  876. }
  877. }
  878. /**
  879. * Process an order that doesn't require payment.
  880. *
  881. * @since 3.0.0
  882. * @param int $order_id Order ID.
  883. */
  884. protected function process_order_without_payment( $order_id ) {
  885. $order = wc_get_order( $order_id );
  886. $order->payment_complete();
  887. wc_empty_cart();
  888. if ( ! is_ajax() ) {
  889. wp_safe_redirect(
  890. apply_filters( 'woocommerce_checkout_no_payment_needed_redirect', $order->get_checkout_order_received_url(), $order )
  891. );
  892. exit;
  893. }
  894. wp_send_json(
  895. array(
  896. 'result' => 'success',
  897. 'redirect' => apply_filters( 'woocommerce_checkout_no_payment_needed_redirect', $order->get_checkout_order_received_url(), $order ),
  898. )
  899. );
  900. }
  901. /**
  902. * Create a new customer account if needed.
  903. *
  904. * @throws Exception When not able to create customer.
  905. * @param array $data Posted data.
  906. */
  907. protected function process_customer( $data ) {
  908. $customer_id = apply_filters( 'woocommerce_checkout_customer_id', get_current_user_id() );
  909. if ( ! is_user_logged_in() && ( $this->is_registration_required() || ! empty( $data['createaccount'] ) ) ) {
  910. $username = ! empty( $data['account_username'] ) ? $data['account_username'] : '';
  911. $password = ! empty( $data['account_password'] ) ? $data['account_password'] : '';
  912. $customer_id = wc_create_new_customer(
  913. $data['billing_email'],
  914. $username,
  915. $password,
  916. array(
  917. 'first_name' => ! empty( $data['billing_first_name'] ) ? $data['billing_first_name'] : '',
  918. 'last_name' => ! empty( $data['billing_last_name'] ) ? $data['billing_last_name'] : '',
  919. )
  920. );
  921. if ( is_wp_error( $customer_id ) ) {
  922. throw new Exception( $customer_id->get_error_message() );
  923. }
  924. wc_set_customer_auth_cookie( $customer_id );
  925. // As we are now logged in, checkout will need to refresh to show logged in data.
  926. WC()->session->set( 'reload_checkout', true );
  927. // Also, recalculate cart totals to reveal any role-based discounts that were unavailable before registering.
  928. WC()->cart->calculate_totals();
  929. }
  930. // On multisite, ensure user exists on current site, if not add them before allowing login.
  931. if ( $customer_id && is_multisite() && is_user_logged_in() && ! is_user_member_of_blog() ) {
  932. add_user_to_blog( get_current_blog_id(), $customer_id, 'customer' );
  933. }
  934. // Add customer info from other fields.
  935. if ( $customer_id && apply_filters( 'woocommerce_checkout_update_customer_data', true, $this ) ) {
  936. $customer = new WC_Customer( $customer_id );
  937. if ( ! empty( $data['billing_first_name'] ) && '' === $customer->get_first_name() ) {
  938. $customer->set_first_name( $data['billing_first_name'] );
  939. }
  940. if ( ! empty( $data['billing_last_name'] ) && '' === $customer->get_last_name() ) {
  941. $customer->set_last_name( $data['billing_last_name'] );
  942. }
  943. // If the display name is an email, update to the user's full name.
  944. if ( is_email( $customer->get_display_name() ) ) {
  945. $customer->set_display_name( $customer->get_first_name() . ' ' . $customer->get_last_name() );
  946. }
  947. foreach ( $data as $key => $value ) {
  948. // Use setters where available.
  949. if ( is_callable( array( $customer, "set_{$key}" ) ) ) {
  950. $customer->{"set_{$key}"}( $value );
  951. // Store custom fields prefixed with wither shipping_ or billing_.
  952. } elseif ( 0 === stripos( $key, 'billing_' ) || 0 === stripos( $key, 'shipping_' ) ) {
  953. $customer->update_meta_data( $key, $value );
  954. }
  955. }
  956. /**
  957. * Action hook to adjust customer before save.
  958. *
  959. * @since 3.0.0
  960. */
  961. do_action( 'woocommerce_checkout_update_customer', $customer, $data );
  962. $customer->save();
  963. }
  964. do_action( 'woocommerce_checkout_update_user_meta', $customer_id, $data );
  965. }
  966. /**
  967. * If checkout failed during an AJAX call, send failure response.
  968. */
  969. protected function send_ajax_failure_response() {
  970. if ( is_ajax() ) {
  971. // Only print notices if not reloading the checkout, otherwise they're lost in the page reload.
  972. if ( ! isset( WC()->session->reload_checkout ) ) {
  973. $messages = wc_print_notices( true );
  974. }
  975. $response = array(
  976. 'result' => 'failure',
  977. 'messages' => isset( $messages ) ? $messages : '',
  978. 'refresh' => isset( WC()->session->refresh_totals ),
  979. 'reload' => isset( WC()->session->reload_checkout ),
  980. );
  981. unset( WC()->session->refresh_totals, WC()->session->reload_checkout );
  982. wp_send_json( $response );
  983. }
  984. }
  985. /**
  986. * Process the checkout after the confirm order button is pressed.
  987. *
  988. * @throws Exception When validation fails.
  989. */
  990. public function process_checkout() {
  991. try {
  992. $nonce_value = wc_get_var( $_REQUEST['woocommerce-process-checkout-nonce'], wc_get_var( $_REQUEST['_wpnonce'], '' ) ); // phpcs:ignore
  993. if ( empty( $nonce_value ) || ! wp_verify_nonce( $nonce_value, 'woocommerce-process_checkout' ) ) {
  994. WC()->session->set( 'refresh_totals', true );
  995. throw new Exception( __( 'We were unable to process your order, please try again.', 'woocommerce' ) );
  996. }
  997. wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
  998. wc_set_time_limit( 0 );
  999. do_action( 'woocommerce_before_checkout_process' );
  1000. if ( WC()->cart->is_empty() ) {
  1001. /* translators: %s: shop cart url */
  1002. throw new Exception( sprintf( __( 'Sorry, your session has expired. <a href="%s" class="wc-backward">Return to shop</a>', 'woocommerce' ), esc_url( wc_get_page_permalink( 'shop' ) ) ) );
  1003. }
  1004. do_action( 'woocommerce_checkout_process' );
  1005. $errors = new WP_Error();
  1006. $posted_data = $this->get_posted_data();
  1007. // Update session for customer and totals.
  1008. $this->update_session( $posted_data );
  1009. // Validate posted data and cart items before proceeding.
  1010. $this->validate_checkout( $posted_data, $errors );
  1011. foreach ( $errors->errors as $code => $messages ) {
  1012. $data = $errors->get_error_data( $code );
  1013. foreach ( $messages as $message ) {
  1014. wc_add_notice( $message, 'error', $data );
  1015. }
  1016. }
  1017. if ( empty( $posted_data['woocommerce_checkout_update_totals'] ) && 0 === wc_notice_count( 'error' ) ) {
  1018. $this->process_customer( $posted_data );
  1019. $order_id = $this->create_order( $posted_data );
  1020. $order = wc_get_order( $order_id );
  1021. if ( is_wp_error( $order_id ) ) {
  1022. throw new Exception( $order_id->get_error_message() );
  1023. }
  1024. if ( ! $order ) {
  1025. throw new Exception( __( 'Unable to create order.', 'woocommerce' ) );
  1026. }
  1027. do_action( 'woocommerce_checkout_order_processed', $order_id, $posted_data, $order );
  1028. /**
  1029. * Note that woocommerce_cart_needs_payment is only used in
  1030. * WC_Checkout::process_checkout() to keep backwards compatibility.
  1031. * Use woocommerce_order_needs_payment instead.
  1032. *
  1033. * Note that at this point you can't rely on the Cart Object anymore,
  1034. * since it could be empty see:
  1035. * https://github.com/woocommerce/woocommerce/issues/24631
  1036. */
  1037. if ( apply_filters( 'woocommerce_cart_needs_payment', $order->needs_payment(), WC()->cart ) ) {
  1038. $this->process_order_payment( $order_id, $posted_data['payment_method'] );
  1039. } else {
  1040. $this->process_order_without_payment( $order_id );
  1041. }
  1042. }
  1043. } catch ( Exception $e ) {
  1044. wc_add_notice( $e->getMessage(), 'error' );
  1045. }
  1046. $this->send_ajax_failure_response();
  1047. }
  1048. /**
  1049. * Get a posted address field after sanitization and validation.
  1050. *
  1051. * @param string $key Field key.
  1052. * @param string $type Type of address. Available options: 'billing' or 'shipping'.
  1053. * @return string
  1054. */
  1055. public function get_posted_address_data( $key, $type = 'billing' ) {
  1056. if ( 'billing' === $type || false === $this->legacy_posted_data['ship_to_different_address'] ) {
  1057. $return = isset( $this->legacy_posted_data[ 'billing_' . $key ] ) ? $this->legacy_posted_data[ 'billing_' . $key ] : '';
  1058. } else {
  1059. $return = isset( $this->legacy_posted_data[ 'shipping_' . $key ] ) ? $this->legacy_posted_data[ 'shipping_' . $key ] : '';
  1060. }
  1061. return $return;
  1062. }
  1063. /**
  1064. * Gets the value either from POST, or from the customer object. Sets the default values in checkout fields.
  1065. *
  1066. * @param string $input Name of the input we want to grab data for. e.g. billing_country.
  1067. * @return string The default value.
  1068. */
  1069. public function get_value( $input ) {
  1070. // If the form was posted, get the posted value. This will only tend to happen when JavaScript is disabled client side.
  1071. if ( ! empty( $_POST[ $input ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
  1072. return wc_clean( wp_unslash( $_POST[ $input ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
  1073. }
  1074. // Allow 3rd parties to short circuit the logic and return their own default value.
  1075. $value = apply_filters( 'woocommerce_checkout_get_value', null, $input );
  1076. if ( ! is_null( $value ) ) {
  1077. return $value;
  1078. }
  1079. /**
  1080. * For logged in customers, pull data from their account rather than the session which may contain incomplete data.
  1081. * Another reason is that WC sets shipping address to the billing address on the checkout updates unless the
  1082. * "ship to another address" box is checked. @see issue #20975.
  1083. */
  1084. $customer_object = false;
  1085. if ( is_user_logged_in() ) {
  1086. // Load customer object, but keep it cached to avoid reloading it multiple times.
  1087. if ( is_null( $this->logged_in_customer ) ) {
  1088. $this->logged_in_customer = new WC_Customer( get_current_user_id(), true );
  1089. }
  1090. $customer_object = $this->logged_in_customer;
  1091. }
  1092. if ( ! $customer_object ) {
  1093. $customer_object = WC()->customer;
  1094. }
  1095. if ( is_callable( array( $customer_object, "get_$input" ) ) ) {
  1096. $value = $customer_object->{"get_$input"}();
  1097. } elseif ( $customer_object->meta_exists( $input ) ) {
  1098. $value = $customer_object->get_meta( $input, true );
  1099. }
  1100. if ( '' === $value ) {
  1101. $value = null;
  1102. }
  1103. return apply_filters( 'default_checkout_' . $input, $value, $input );
  1104. }
  1105. }