64 || ! wc_coupons_enabled() || ! WC()->cart || ! WC()->session ) { return array( 'status' => 'invalid', 'message' => '', ); } if ( ! WC()->session->has_session() ) { WC()->session->set_customer_session_cookie( true ); } if ( WC()->cart->has_discount( $code ) || ( WC()->cart->is_empty() && WC()->session->get( self::SESSION ) === $code ) ) { return array( 'status' => 'known', 'message' => '', ); } $coupon = new \WC_Coupon( $code ); if ( ! $coupon->get_id() ) { return array( 'status' => 'invalid', 'message' => __( 'This discount code does not exist.', 'aiolos-checkout-for-woocommerce' ), ); } if ( WC()->cart->is_empty() ) { WC()->session->set( self::SESSION, $code ); return array( 'status' => 'waiting', /* translators: %s: discount code */ 'message' => sprintf( __( 'The code %s will be applied when you add a product to your cart.', 'aiolos-checkout-for-woocommerce' ), strtoupper( $code ) ), ); } wc_clear_notices(); $applied = WC()->cart->apply_coupon( $code ); $errors = wc_get_notices( 'error' ); wc_clear_notices(); if ( ! $applied ) { $first = $errors ? reset( $errors ) : array(); return array( 'status' => 'invalid', 'message' => wp_strip_all_tags( (string) ( is_array( $first ) ? ( $first['notice'] ?? '' ) : $first ) ), ); } return array( 'status' => 'applied', /* translators: %s: discount code */ 'message' => sprintf( __( 'The code %s was applied to your cart.', 'aiolos-checkout-for-woocommerce' ), strtoupper( $code ) ), ); } /** * Reads the code from the link (page requests). */ public static function from_link(): void { // A plain link a customer follows: nothing to protect with a nonce; WooCommerce validates the code. if ( is_admin() || wp_doing_ajax() || empty( $_GET[ self::PARAM ] ) || ! function_exists( 'WC' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return; } $result = self::handle( sanitize_text_field( wp_unslash( $_GET[ self::PARAM ] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( '' !== $result['message'] ) { wc_add_notice( esc_html( $result['message'] ), 'invalid' === $result['status'] ? 'error' : 'success' ); } } /** * The same for a page served from a cache (asked by the side cart's script). */ public static function ajax(): void { $code = isset( $_POST['code'] ) ? sanitize_text_field( wp_unslash( $_POST['code'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- applying a public code to one's own cart; WooCommerce validates it. wp_send_json_success( self::handle( $code ) ); } /** * Applies a waiting code once the cart has a product. */ public static function apply_pending(): void { $session = WC()->session; $code = $session ? (string) $session->get( self::SESSION ) : ''; if ( '' === $code ) { return; } $session->set( self::SESSION, null ); if ( ! WC()->cart->has_discount( $code ) ) { WC()->cart->apply_coupon( $code ); } } }