From 62827e1ed2e67ab0f1178f27578c3337c3e7586a Mon Sep 17 00:00:00 2001 From: Mayisha <33387139+Mayisha@users.noreply.github.com> Date: Tue, 17 Sep 2024 02:55:11 +0600 Subject: [PATCH] Create backend classes for express checkout element (#3429) * create 'WC_Stripe_Express_Checkout_Element' class * register script for shortcode checkout * move ajax functions to separate class * move helper functions to a separate class * include and initialize express checkout classes * make functions public in the helper class --- .../express-checkout/express-checkout.js | 6 +- client/entrypoints/express-checkout/index.js | 1 + ...c-stripe-express-checkout-ajax-handler.php | 310 +++++ ...ass-wc-stripe-express-checkout-element.php | 352 +++++ ...lass-wc-stripe-express-checkout-helper.php | 1185 +++++++++++++++++ .../class-wc-stripe-payment-request.php | 5 + webpack.config.js | 1 + woocommerce-gateway-stripe.php | 26 +- 8 files changed, 1878 insertions(+), 8 deletions(-) create mode 100644 client/entrypoints/express-checkout/index.js create mode 100644 includes/payment-methods/class-wc-stripe-express-checkout-ajax-handler.php create mode 100644 includes/payment-methods/class-wc-stripe-express-checkout-element.php create mode 100644 includes/payment-methods/class-wc-stripe-express-checkout-helper.php diff --git a/client/blocks/express-checkout/express-checkout.js b/client/blocks/express-checkout/express-checkout.js index 345758acc..297fda109 100644 --- a/client/blocks/express-checkout/express-checkout.js +++ b/client/blocks/express-checkout/express-checkout.js @@ -1,4 +1,4 @@ -/* global wc_stripe_payment_request_params */ +/* global wc_stripe_express_checkout_params */ import React from 'react'; import { Elements, ExpressCheckoutElement } from '@stripe/react-stripe-js'; @@ -13,8 +13,8 @@ export const ExpressCheckout = ( props ) => { const buttonOptions = { buttonType: { - googlePay: wc_stripe_payment_request_params.button.type, - applePay: wc_stripe_payment_request_params.button.type, + googlePay: wc_stripe_express_checkout_params.button.type, + applePay: wc_stripe_express_checkout_params.button.type, }, }; diff --git a/client/entrypoints/express-checkout/index.js b/client/entrypoints/express-checkout/index.js new file mode 100644 index 000000000..f69a9256f --- /dev/null +++ b/client/entrypoints/express-checkout/index.js @@ -0,0 +1 @@ +// express checkout element integration for shortcode goes here. diff --git a/includes/payment-methods/class-wc-stripe-express-checkout-ajax-handler.php b/includes/payment-methods/class-wc-stripe-express-checkout-ajax-handler.php new file mode 100644 index 000000000..ade4b0132 --- /dev/null +++ b/includes/payment-methods/class-wc-stripe-express-checkout-ajax-handler.php @@ -0,0 +1,310 @@ +express_checkout_helper = $express_checkout_helper; + } + + /** + * Initialize hooks. + * + * @return void + */ + public function init() { + add_action( 'wc_ajax_wc_stripe_get_cart_details', [ $this, 'ajax_get_cart_details' ] ); + add_action( 'wc_ajax_wc_stripe_get_shipping_options', [ $this, 'ajax_get_shipping_options' ] ); + add_action( 'wc_ajax_wc_stripe_update_shipping_method', [ $this, 'ajax_update_shipping_method' ] ); + add_action( 'wc_ajax_wc_stripe_create_order', [ $this, 'ajax_create_order' ] ); + add_action( 'wc_ajax_wc_stripe_add_to_cart', [ $this, 'ajax_add_to_cart' ] ); + add_action( 'wc_ajax_wc_stripe_get_selected_product_data', [ $this, 'ajax_get_selected_product_data' ] ); + add_action( 'wc_ajax_wc_stripe_clear_cart', [ $this, 'ajax_clear_cart' ] ); + add_action( 'wc_ajax_wc_stripe_log_errors', [ $this, 'ajax_log_errors' ] ); + } + + /** + * Get cart details. + */ + public function ajax_get_cart_details() { + check_ajax_referer( 'wc-stripe-express-checkout', 'security' ); + + if ( ! defined( 'WOOCOMMERCE_CART' ) ) { + define( 'WOOCOMMERCE_CART', true ); + } + + WC()->cart->calculate_totals(); + + $currency = get_woocommerce_currency(); + + // Set mandatory payment details. + $data = [ + 'shipping_required' => WC()->cart->needs_shipping(), + 'order_data' => [ + 'currency' => strtolower( $currency ), + 'country_code' => substr( get_option( 'woocommerce_default_country' ), 0, 2 ), + ], + ]; + + $data['order_data'] += $this->express_checkout_helper->build_display_items(); + + wp_send_json( $data ); + } + + + /** + * Adds the current product to the cart. Used on product detail page. + * + * @return array $data Results of adding the product to the cart. + */ + public function ajax_add_to_cart() { + check_ajax_referer( 'wc-stripe-add-to-cart', 'security' ); + + if ( ! defined( 'WOOCOMMERCE_CART' ) ) { + define( 'WOOCOMMERCE_CART', true ); + } + + WC()->shipping->reset_shipping(); + + $product_id = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0; + $qty = ! isset( $_POST['qty'] ) ? 1 : absint( $_POST['qty'] ); + $product = wc_get_product( $product_id ); + $product_type = $product->get_type(); + + // First empty the cart to prevent wrong calculation. + WC()->cart->empty_cart(); + + if ( ( 'variable' === $product_type || 'variable-subscription' === $product_type ) && isset( $_POST['attributes'] ) ) { + $attributes = wc_clean( wp_unslash( $_POST['attributes'] ) ); + + $data_store = WC_Data_Store::load( 'product' ); + $variation_id = $data_store->find_matching_product_variation( $product, $attributes ); + + WC()->cart->add_to_cart( $product->get_id(), $qty, $variation_id, $attributes ); + } + + if ( in_array( $product_type, [ 'simple', 'variation', 'subscription', 'subscription_variation' ], true ) ) { + WC()->cart->add_to_cart( $product->get_id(), $qty ); + } + + WC()->cart->calculate_totals(); + + $data = []; + $data += $this->express_checkout_helper->build_display_items(); + $data['result'] = 'success'; + + // @phpstan-ignore-next-line (return statement is added) + wp_send_json( $data ); + } + + /** + * Clears cart. + */ + public function ajax_clear_cart() { + check_ajax_referer( 'wc-stripe-clear-cart', 'security' ); + + WC()->cart->empty_cart(); + exit; + } + + /** + * Get shipping options. + * + * @see WC_Cart::get_shipping_packages(). + * @see WC_Shipping::calculate_shipping(). + * @see WC_Shipping::get_packages(). + */ + public function ajax_get_shipping_options() { + check_ajax_referer( 'wc-stripe-express-checkout-shipping', 'security' ); + + $shipping_address = filter_input_array( + INPUT_POST, + [ + 'country' => FILTER_SANITIZE_SPECIAL_CHARS, + 'state' => FILTER_SANITIZE_SPECIAL_CHARS, + 'postcode' => FILTER_SANITIZE_SPECIAL_CHARS, + 'city' => FILTER_SANITIZE_SPECIAL_CHARS, + 'address' => FILTER_SANITIZE_SPECIAL_CHARS, + 'address_2' => FILTER_SANITIZE_SPECIAL_CHARS, + ] + ); + $product_view_options = filter_input_array( INPUT_POST, [ 'is_product_page' => FILTER_SANITIZE_SPECIAL_CHARS ] ); + $should_show_itemized_view = ! isset( $product_view_options['is_product_page'] ) ? true : filter_var( $product_view_options['is_product_page'], FILTER_VALIDATE_BOOLEAN ); + + $data = $this->express_checkout_helper->get_shipping_options( $shipping_address, $should_show_itemized_view ); + wp_send_json( $data ); + } + + /** + * Update shipping method. + */ + public function ajax_update_shipping_method() { + check_ajax_referer( 'wc-stripe-update-shipping-method', 'security' ); + + if ( ! defined( 'WOOCOMMERCE_CART' ) ) { + define( 'WOOCOMMERCE_CART', true ); + } + + $shipping_methods = filter_input( INPUT_POST, 'shipping_method', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY ); + $this->express_checkout_helper->update_shipping_method( $shipping_methods ); + + WC()->cart->calculate_totals(); + + $product_view_options = filter_input_array( INPUT_POST, [ 'is_product_page' => FILTER_SANITIZE_SPECIAL_CHARS ] ); + $should_show_itemized_view = ! isset( $product_view_options['is_product_page'] ) ? true : filter_var( $product_view_options['is_product_page'], FILTER_VALIDATE_BOOLEAN ); + + $data = []; + $data += $this->express_checkout_helper->build_display_items( $should_show_itemized_view ); + $data['result'] = 'success'; + + wp_send_json( $data ); + } + + /** + * Gets the selected product data. + * + * @return array $data The selected product data. + */ + public function ajax_get_selected_product_data() { + check_ajax_referer( 'wc-stripe-get-selected-product-data', 'security' ); + + try { // @phpstan-ignore-line (return statement is added) + $product_id = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0; + $qty = ! isset( $_POST['qty'] ) ? 1 : apply_filters( 'woocommerce_add_to_cart_quantity', absint( $_POST['qty'] ), $product_id ); + $addon_value = isset( $_POST['addon_value'] ) ? max( floatval( $_POST['addon_value'] ), 0 ) : 0; + $product = wc_get_product( $product_id ); + $variation_id = null; + + if ( ! is_a( $product, 'WC_Product' ) ) { + /* translators: 1) The product Id */ + throw new Exception( sprintf( __( 'Product with the ID (%1$s) cannot be found.', 'woocommerce-gateway-stripe' ), $product_id ) ); + } + + if ( in_array( $product->get_type(), [ 'variable', 'variable-subscription' ], true ) && isset( $_POST['attributes'] ) ) { + $attributes = wc_clean( wp_unslash( $_POST['attributes'] ) ); + + $data_store = WC_Data_Store::load( 'product' ); + $variation_id = $data_store->find_matching_product_variation( $product, $attributes ); + + if ( ! empty( $variation_id ) ) { + $product = wc_get_product( $variation_id ); + } + } + + if ( $this->express_checkout_helper->is_invalid_subscription_product( $product, true ) ) { + throw new Exception( __( 'The chosen subscription product is not supported.', 'woocommerce-gateway-stripe' ) ); + } + + // Force quantity to 1 if sold individually and check for existing item in cart. + if ( $product->is_sold_individually() ) { + $qty = apply_filters( 'wc_stripe_payment_request_add_to_cart_sold_individually_quantity', 1, $qty, $product_id, $variation_id ); + } + + if ( ! $product->has_enough_stock( $qty ) ) { + /* translators: 1) product name 2) quantity in stock */ + throw new Exception( sprintf( __( 'You cannot add that amount of "%1$s"; to the cart because there is not enough stock (%2$s remaining).', 'woocommerce-gateway-stripe' ), $product->get_name(), wc_format_stock_quantity_for_display( $product->get_stock_quantity(), $product ) ) ); + } + + $total = $qty * $this->express_checkout_helper->get_product_price( $product ) + $addon_value; + + $quantity_label = 1 < $qty ? ' (x' . $qty . ')' : ''; + + $data = []; + $items = []; + + $items[] = [ + 'label' => $product->get_name() . $quantity_label, + 'amount' => WC_Stripe_Helper::get_stripe_amount( $total ), + ]; + + if ( wc_tax_enabled() ) { + $items[] = [ + 'label' => __( 'Tax', 'woocommerce-gateway-stripe' ), + 'amount' => 0, + 'pending' => true, + ]; + } + + if ( wc_shipping_enabled() && $product->needs_shipping() ) { + $items[] = [ + 'label' => __( 'Shipping', 'woocommerce-gateway-stripe' ), + 'amount' => 0, + 'pending' => true, + ]; + + $data['shippingOptions'] = [ + 'id' => 'pending', + 'label' => __( 'Pending', 'woocommerce-gateway-stripe' ), + 'detail' => '', + 'amount' => 0, + ]; + } + + $data['displayItems'] = $items; + $data['total'] = [ + 'label' => $this->express_checkout_helper->get_total_label(), + 'amount' => WC_Stripe_Helper::get_stripe_amount( $total ), + ]; + + $data['requestShipping'] = ( wc_shipping_enabled() && $product->needs_shipping() ); + $data['currency'] = strtolower( get_woocommerce_currency() ); + $data['country_code'] = substr( get_option( 'woocommerce_default_country' ), 0, 2 ); + + wp_send_json( $data ); + } catch ( Exception $e ) { + wp_send_json( [ 'error' => wp_strip_all_tags( $e->getMessage() ) ] ); + } + } + + /** + * Create order. Security is handled by WC. + */ + public function ajax_create_order() { + if ( WC()->cart->is_empty() ) { + wp_send_json_error( __( 'Empty cart', 'woocommerce-gateway-stripe' ) ); + } + + if ( ! defined( 'WOOCOMMERCE_CHECKOUT' ) ) { + define( 'WOOCOMMERCE_CHECKOUT', true ); + } + + // Normalizes billing and shipping state values. + $this->express_checkout_helper->normalize_state(); + + // In case the state is required, but is missing, add a more descriptive error notice. + $this->express_checkout_helper->validate_state(); + + WC()->checkout()->process_checkout(); + + die( 0 ); + } + + /** + * Log errors coming from express checkout elements + */ + public function ajax_log_errors() { + check_ajax_referer( 'wc-stripe-log-errors', 'security' ); + + $errors = isset( $_POST['errors'] ) ? wc_clean( wp_unslash( $_POST['errors'] ) ) : ''; + + WC_Stripe_Logger::log( $errors ); + + exit; + } +} diff --git a/includes/payment-methods/class-wc-stripe-express-checkout-element.php b/includes/payment-methods/class-wc-stripe-express-checkout-element.php new file mode 100644 index 000000000..7e41cf8cf --- /dev/null +++ b/includes/payment-methods/class-wc-stripe-express-checkout-element.php @@ -0,0 +1,352 @@ +stripe_settings = WC_Stripe_Helper::get_stripe_settings(); + + $this->express_checkout_helper = $express_checkout_helper; + $this->express_checkout_ajax_handler = $express_checkout_ajax_handler; + $this->express_checkout_ajax_handler->init(); + } + + /** + * Initialize hooks. + * + * @return void + */ + public function init() { + // Check if ECE feature flag is enabled. + if ( ! WC_Stripe_Feature_Flags::is_stripe_ece_enabled() ) { + return; + } + + // Checks if Stripe Gateway is enabled. + if ( empty( $this->stripe_settings ) || ( isset( $this->stripe_settings['enabled'] ) && 'yes' !== $this->stripe_settings['enabled'] ) ) { + return; + } + + // Don't initiate this class if express checkout element is disabled. + if ( ! $this->express_checkout_helper->is_express_checkout_enabled() ) { + return; + } + + // Don't load for change payment method page. + if ( isset( $_GET['change_payment_method'] ) ) { + return; + } + + add_action( 'template_redirect', [ $this, 'set_session' ] ); + add_action( 'template_redirect', [ $this, 'handle_express_checkout_redirect' ] ); + + add_action( 'wp_enqueue_scripts', [ $this, 'scripts' ] ); + + add_action( 'woocommerce_after_add_to_cart_form', [ $this, 'display_express_checkout_button_html' ], 1 ); + add_action( 'woocommerce_proceed_to_checkout', [ $this, 'display_express_checkout_button_html' ], 25 ); + add_action( 'woocommerce_checkout_before_customer_details', [ $this, 'display_express_checkout_button_html' ], 1 ); + + add_filter( 'woocommerce_gateway_title', [ $this, 'filter_gateway_title' ], 10, 2 ); + add_action( 'woocommerce_checkout_order_processed', [ $this, 'add_order_meta' ], 10, 2 ); + add_filter( 'woocommerce_login_redirect', [ $this, 'get_login_redirect_url' ], 10, 3 ); + add_filter( 'woocommerce_registration_redirect', [ $this, 'get_login_redirect_url' ], 10, 3 ); + } + + /** + * Get this instance. + * + * @return class + */ + public static function instance() { + return self::$_this; + } + + /** + * Sets the WC customer session if one is not set. + * This is needed so nonces can be verified by AJAX Request. + * + * @return void + */ + public function set_session() { + if ( ! $this->express_checkout_helper->is_product() || ( isset( WC()->session ) && WC()->session->has_session() ) ) { + return; + } + + WC()->session->set_customer_session_cookie( true ); + } + + /** + * Handles express checkout redirect when the redirect dialog "Continue" button is clicked. + */ + public function handle_express_checkout_redirect() { + if ( + ! empty( $_GET['wc_stripe_express_checkout_redirect_url'] ) + && ! empty( $_GET['_wpnonce'] ) + && wp_verify_nonce( $_GET['_wpnonce'], 'wc-stripe-set-redirect-url' ) // @codingStandardsIgnoreLine + ) { + $url = rawurldecode( esc_url_raw( wp_unslash( $_GET['wc_stripe_express_checkout_redirect_url'] ) ) ); + // Sets a redirect URL cookie for 10 minutes, which we will redirect to after authentication. + // Users will have a 10 minute timeout to login/create account, otherwise redirect URL expires. + wc_setcookie( 'wc_stripe_express_checkout_redirect_url', $url, time() + MINUTE_IN_SECONDS * 10 ); + // Redirects to "my-account" page. + wp_safe_redirect( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) ); + exit; + } + } + + /** + * Returns the login redirect URL. + * + * @param string $redirect Default redirect URL. + * @return string Redirect URL. + */ + public function get_login_redirect_url( $redirect ) { + $url = esc_url_raw( wp_unslash( isset( $_COOKIE['wc_stripe_express_checkout_redirect_url'] ) ? $_COOKIE['wc_stripe_express_checkout_redirect_url'] : '' ) ); + + if ( empty( $url ) ) { + return $redirect; + } + wc_setcookie( 'wc_stripe_express_checkout_redirect_url', null ); + + return $url; + } + + /** + * Returns the JavaScript configuration object used for any pages with express checkout element. + * + * @return array The settings used for the Stripe express checkout element in JavaScript. + */ + public function javascript_params() { + $needs_shipping = 'no'; + if ( ! is_null( WC()->cart ) && WC()->cart->needs_shipping() ) { + $needs_shipping = 'yes'; + } + + return [ + 'ajax_url' => WC_AJAX::get_endpoint( '%%endpoint%%' ), + 'stripe' => [ + 'allow_prepaid_card' => apply_filters( 'wc_stripe_allow_prepaid_card', true ) ? 'yes' : 'no', + 'locale' => WC_Stripe_Helper::convert_wc_locale_to_stripe_locale( get_locale() ), + 'is_link_enabled' => WC_Stripe_UPE_Payment_Method_Link::is_link_enabled(), + 'is_express_checkout_enabled' => $this->express_checkout_helper->is_express_checkout_enabled(), + ], + 'nonce' => [ + 'payment' => wp_create_nonce( 'wc-stripe-express-checkout-element' ), + 'shipping' => wp_create_nonce( 'wc-stripe-express-checkout-element-shipping' ), + 'update_shipping' => wp_create_nonce( 'wc-stripe-update-shipping-method' ), + 'checkout' => wp_create_nonce( 'woocommerce-process_checkout' ), + 'add_to_cart' => wp_create_nonce( 'wc-stripe-add-to-cart' ), + 'get_selected_product_data' => wp_create_nonce( 'wc-stripe-get-selected-product-data' ), + 'log_errors' => wp_create_nonce( 'wc-stripe-log-errors' ), + 'clear_cart' => wp_create_nonce( 'wc-stripe-clear-cart' ), + ], + 'i18n' => [ + 'no_prepaid_card' => __( 'Sorry, we\'re not accepting prepaid cards at this time.', 'woocommerce-gateway-stripe' ), + /* translators: Do not translate the [option] placeholder */ + 'unknown_shipping' => __( 'Unknown shipping option "[option]".', 'woocommerce-gateway-stripe' ), + ], + 'checkout' => [ + 'url' => wc_get_checkout_url(), + 'currency_code' => strtolower( get_woocommerce_currency() ), + 'country_code' => substr( get_option( 'woocommerce_default_country' ), 0, 2 ), + 'needs_shipping' => $needs_shipping, + // Defaults to 'required' to match how core initializes this option. + 'needs_payer_phone' => 'required' === get_option( 'woocommerce_checkout_phone_field', 'required' ), + ], + 'button' => $this->express_checkout_helper->get_button_settings(), + 'login_confirmation' => $this->express_checkout_helper->get_login_confirmation_settings(), + 'is_product_page' => $this->express_checkout_helper->is_product(), + 'product' => $this->express_checkout_helper->get_product_data(), + ]; + } + + /** + * Load scripts and styles. + */ + public function scripts() { + // If page is not supported, bail. + if ( ! $this->express_checkout_helper->is_page_supported() ) { + return; + } + + if ( ! $this->express_checkout_helper->should_show_express_checkout_button() ) { + return; + } + + $asset_path = WC_STRIPE_PLUGIN_PATH . '/build/express_checkout.asset.php'; + $version = WC_STRIPE_VERSION; + $dependencies = []; + if ( file_exists( $asset_path ) ) { + $asset = require $asset_path; + $version = is_array( $asset ) && isset( $asset['version'] ) + ? $asset['version'] + : $version; + $dependencies = is_array( $asset ) && isset( $asset['dependencies'] ) + ? $asset['dependencies'] + : $dependencies; + } + + wp_register_script( 'stripe', 'https://js.stripe.com/v3/', '', '3.0', true ); + wp_register_script( + 'wc_stripe_express_checkout', + WC_STRIPE_PLUGIN_URL . '/build/express_checkout.js', + array_merge( [ 'jquery', 'stripe' ], $dependencies ), + $version, + true + ); + + wp_enqueue_style( + 'wc_stripe_express_checkout_style', + WC_STRIPE_PLUGIN_URL . '/build/express_checkout.css', + [], + $version + ); + + wp_localize_script( + 'wc_stripe_express_checkout', + 'wc_stripe_express_checkout_params', + apply_filters( + 'wc_stripe_express_checkout_params', + $this->javascript_params() + ) + ); + + wp_enqueue_script( 'wc_stripe_express_checkout' ); + } + + /** + * Add needed order meta + * + * @param integer $order_id The order ID. + * @param array $posted_data The posted data from checkout form. + * + * @return void + */ + public function add_order_meta( $order_id, $posted_data ) { + if ( empty( $_POST['express_checkout_type'] ) || ! isset( $_POST['payment_method'] ) || 'stripe' !== $_POST['payment_method'] ) { + return; + } + + $order = wc_get_order( $order_id ); + + $express_checkout_type = wc_clean( wp_unslash( $_POST['express_checkout_type'] ) ); + + if ( 'apple_pay' === $express_checkout_type ) { + $order->set_payment_method_title( 'Apple Pay (Stripe)' ); + $order->save(); + } elseif ( 'google_pay' === $express_checkout_type ) { + $order->set_payment_method_title( 'Google Pay (Stripe)' ); + $order->save(); + } + } + + /** + * Filters the gateway title to reflect express checkout type + */ + public function filter_gateway_title( $title, $id ) { + global $theorder; + + // If $theorder is empty (i.e. non-HPOS), fallback to using the global post object. + if ( empty( $theorder ) && ! empty( $GLOBALS['post']->ID ) ) { + $theorder = wc_get_order( $GLOBALS['post']->ID ); + } + + if ( ! is_object( $theorder ) ) { + return $title; + } + + $method_title = $theorder->get_payment_method_title(); + + if ( 'stripe' === $id && ! empty( $method_title ) ) { + if ( 'Apple Pay (Stripe)' === $method_title + || 'Google Pay (Stripe)' === $method_title + ) { + return $method_title; + } + } + + return $title; + } + + /** + * Display the express checkout button. + */ + public function display_express_checkout_button_html() { + $gateways = WC()->payment_gateways->get_available_payment_gateways(); + + if ( ! isset( $gateways['stripe'] ) ) { + return; + } + + if ( ! $this->express_checkout_helper->is_page_supported() ) { + return; + } + + if ( ! $this->express_checkout_helper->should_show_express_checkout_button() ) { + return; + } + + ?> +
+ display_express_checkout_button_separator_html(); + } + + /** + * Display express checkout button separator. + */ + public function display_express_checkout_button_separator_html() { + if ( ! is_checkout() && ! is_wc_endpoint_url( 'order-pay' ) ) { + return; + } + + if ( is_checkout() && ! in_array( 'checkout', $this->express_checkout_helper->get_button_locations(), true ) ) { + return; + } + + ?> + + + stripe_settings = WC_Stripe_Helper::get_stripe_settings(); + $this->testmode = ( ! empty( $this->stripe_settings['testmode'] ) && 'yes' === $this->stripe_settings['testmode'] ) ? true : false; + $this->total_label = ! empty( $this->stripe_settings['statement_descriptor'] ) ? WC_Stripe_Helper::clean_statement_descriptor( $this->stripe_settings['statement_descriptor'] ) : ''; + + $this->total_label = str_replace( "'", '', $this->total_label ) . apply_filters( 'wc_stripe_payment_request_total_label_suffix', ' (via WooCommerce)' ); + + } + + /** + * Checks whether authentication is required for checkout. + * + * @return bool + */ + public function is_authentication_required() { + // If guest checkout is disabled and account creation upon checkout is not possible, authentication is required. + if ( 'no' === get_option( 'woocommerce_enable_guest_checkout', 'yes' ) && ! $this->is_account_creation_possible() ) { + return true; + } + // If cart contains subscription and account creation upon checkout is not posible, authentication is required. + if ( $this->has_subscription_product() && ! $this->is_account_creation_possible() ) { + return true; + } + + return false; + } + + /** + * Checks whether account creation is possible upon checkout. + * + * @return bool + */ + public function is_account_creation_possible() { + // If automatically generate username/password are disabled, we can not include any of those fields, + // during express checkout. So account creation is not possible. + return ( + 'yes' === get_option( 'woocommerce_enable_signup_and_login_from_checkout', 'no' ) && + 'yes' === get_option( 'woocommerce_registration_generate_username', 'yes' ) && + 'yes' === get_option( 'woocommerce_registration_generate_password', 'yes' ) + ); + } + + /** + * Gets the button type. + * + * @return string + */ + public function get_button_type() { + return isset( $this->stripe_settings['payment_request_button_type'] ) ? $this->stripe_settings['payment_request_button_type'] : 'default'; + } + + /** + * Gets the button theme. + * + * @return string + */ + public function get_button_theme() { + return isset( $this->stripe_settings['payment_request_button_theme'] ) ? $this->stripe_settings['payment_request_button_theme'] : 'dark'; + } + + /** + * Gets the button height. + * + * @return string + */ + public function get_button_height() { + $height = isset( $this->stripe_settings['payment_request_button_size'] ) ? $this->stripe_settings['payment_request_button_size'] : 'default'; + if ( 'small' === $height ) { + return '40'; + } + + if ( 'large' === $height ) { + return '56'; + } + + return '48'; + } + + /** + * Gets total label. + * + * @return string + */ + public function get_total_label() { + return $this->total_label; + } + + /** + * Gets the product total price. + * + * @param object $product WC_Product_* object. + * @return integer Total price. + */ + public function get_product_price( $product ) { + $product_price = $product->get_price(); + // Add subscription sign-up fees to product price. + if ( in_array( $product->get_type(), [ 'subscription', 'subscription_variation' ] ) && class_exists( 'WC_Subscriptions_Product' ) ) { + $product_price = $product->get_price() + WC_Subscriptions_Product::get_sign_up_fee( $product ); + } + + return $product_price; + } + + /** + * Gets the product data for the currently viewed page + * + * @return mixed Returns false if not on a product page, the product information otherwise. + */ + public function get_product_data() { + if ( ! $this->is_product() ) { + return false; + } + + $product = $this->get_product(); + $variation_id = 0; + + if ( in_array( $product->get_type(), [ 'variable', 'variable-subscription' ], true ) ) { + $variation_attributes = $product->get_variation_attributes(); + $attributes = []; + + foreach ( $variation_attributes as $attribute_name => $attribute_values ) { + $attribute_key = 'attribute_' . sanitize_title( $attribute_name ); + + // Passed value via GET takes precedence, then POST, otherwise get the default value for given attribute + if ( isset( $_GET[ $attribute_key ] ) ) { + $attributes[ $attribute_key ] = wc_clean( wp_unslash( $_GET[ $attribute_key ] ) ); + } elseif ( isset( $_POST[ $attribute_key ] ) ) { + $attributes[ $attribute_key ] = wc_clean( wp_unslash( $_POST[ $attribute_key ] ) ); + } else { + $attributes[ $attribute_key ] = $product->get_variation_default_attribute( $attribute_name ); + } + } + + $data_store = WC_Data_Store::load( 'product' ); + $variation_id = $data_store->find_matching_product_variation( $product, $attributes ); + + if ( ! empty( $variation_id ) ) { + $product = wc_get_product( $variation_id ); + } + } + + $data = []; + $items = []; + + $items[] = [ + 'label' => $product->get_name(), + 'amount' => WC_Stripe_Helper::get_stripe_amount( $this->get_product_price( $product ) ), + ]; + + if ( wc_tax_enabled() ) { + $items[] = [ + 'label' => __( 'Tax', 'woocommerce-gateway-stripe' ), + 'amount' => 0, + 'pending' => true, + ]; + } + + if ( wc_shipping_enabled() && $product->needs_shipping() ) { + $items[] = [ + 'label' => __( 'Shipping', 'woocommerce-gateway-stripe' ), + 'amount' => 0, + 'pending' => true, + ]; + + $data['shippingOptions'] = [ + 'id' => 'pending', + 'label' => __( 'Pending', 'woocommerce-gateway-stripe' ), + 'detail' => '', + 'amount' => 0, + ]; + } + + $data['displayItems'] = $items; + $data['total'] = [ + 'label' => apply_filters( 'wc_stripe_payment_request_total_label', $this->total_label ), + 'amount' => WC_Stripe_Helper::get_stripe_amount( $this->get_product_price( $product ) ), + ]; + + $data['requestShipping'] = ( wc_shipping_enabled() && $product->needs_shipping() && 0 !== wc_get_shipping_method_count( true ) ); + $data['currency'] = strtolower( get_woocommerce_currency() ); + $data['country_code'] = substr( get_option( 'woocommerce_default_country' ), 0, 2 ); + + // On product page load, if there's a variation already selected, check if it's supported. + $data['validVariationSelected'] = ! empty( $variation_id ) ? $this->is_product_supported( $product ) : true; + + return apply_filters( 'wc_stripe_payment_request_product_data', $data, $product ); + } + + /** + * Normalizes postal code in case of redacted data from Apple Pay. + * + * @param string $postcode Postal code. + * @param string $country Country. + */ + public function get_normalized_postal_code( $postcode, $country ) { + /** + * Currently, Apple Pay truncates the UK and Canadian postal codes to the first 4 and 3 characters respectively + * when passing it back from the shippingcontactselected object. This causes WC to invalidate + * the postal code and not calculate shipping zones correctly. + */ + if ( 'GB' === $country ) { + // Replaces a redacted string with something like LN10***. + return str_pad( preg_replace( '/\s+/', '', $postcode ), 7, '*' ); + } + if ( 'CA' === $country ) { + // Replaces a redacted string with something like L4Y***. + return str_pad( preg_replace( '/\s+/', '', $postcode ), 6, '*' ); + } + + return $postcode; + } + + /** + * Checks to make sure product type is supported. + * + * @return array + */ + public function supported_product_types() { + return apply_filters( + 'wc_stripe_payment_request_supported_types', + [ + 'simple', + 'variable', + 'variation', + 'subscription', + 'variable-subscription', + 'subscription_variation', + 'booking', + 'bundle', + 'composite', + ] + ); + } + + /** + * Checks the cart to see if all items are allowed to be used. + * + * @return boolean + */ + public function allowed_items_in_cart() { + // Pre Orders compatibility where we don't support charge upon release. + if ( $this->is_pre_order_item_in_cart() && $this->is_pre_order_product_charged_upon_release( $this->get_pre_order_product_from_cart() ) ) { + return false; + } + + // If the cart is not available we don't have any unsupported products in the cart, so we + // return true. This can happen e.g. when loading the cart or checkout blocks in Gutenberg. + if ( is_null( WC()->cart ) ) { + return true; + } + + foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { + $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); + + if ( ! in_array( $_product->get_type(), $this->supported_product_types() ) ) { + return false; + } + + // Subscriptions with a trial period that need shipping are not supported. + if ( $this->is_invalid_subscription_product( $_product ) ) { + return false; + } + } + + // We don't support multiple packages with express checkout buttons because we can't offer + // a good UX. + $packages = WC()->cart->get_shipping_packages(); + if ( 1 < count( $packages ) ) { + return false; + } + + return true; + } + + /** + * Returns true if the given product is a subscription that cannot be purchased with express checkout buttons. + * + * Invalid subscription products include those with: + * - a free trial that requires shipping (synchronised subscriptions with a delayed first payment are considered to have a free trial) + * - a synchronised subscription with no upfront payment and is virtual (this limitation only applies to the product page as we cannot calculate totals correctly) + * + * If the product is a variable subscription, this function will return true if all of its variations have a trial and require shipping. + * + * @since 7.8.0 + * + * @param WC_Product|null $product Product object. + * @param boolean $is_product_page_request Whether this is a request from the product page. + * + * @return boolean + */ + public function is_invalid_subscription_product( $product, $is_product_page_request = false ) { + if ( ! class_exists( 'WC_Subscriptions_Product' ) || ! class_exists( 'WC_Subscriptions_Synchroniser' ) || ! WC_Subscriptions_Product::is_subscription( $product ) ) { + return false; + } + + $is_invalid = true; + + if ( $product->get_type() === 'variable-subscription' ) { + $products = $product->get_available_variations( 'object' ); + } else { + $products = [ $product ]; + } + + foreach ( $products as $product ) { + $needs_shipping = $product->needs_shipping(); + $is_synced = WC_Subscriptions_Synchroniser::is_product_synced( $product ); + $is_payment_upfront = WC_Subscriptions_Synchroniser::is_payment_upfront( $product ); + $has_trial_period = WC_Subscriptions_Product::get_trial_length( $product ) > 0; + + if ( $is_product_page_request && $is_synced && ! $is_payment_upfront && ! $needs_shipping ) { + /** + * This condition prevents the purchase of virtual synced subscription products with no upfront costs via express checkout buttons from the product page. + * + * The main issue is that calling $product->get_price() on a synced subscription does not take into account a mock trial period or prorated price calculations + * until the product is in the cart. This means that the totals passed to express checkout element are incorrect when purchasing from the product page. + * Another part of the problem is because the product is virtual this stops the Stripe PaymentRequest API from triggering the necessary `shippingaddresschange` event + * which is when we call WC()->cart->calculate_totals(); which would fix the totals. + * + * The fix here is to not allow virtual synced subscription products with no upfront costs to be purchased via express checkout buttons on the product page. + */ + continue; + } elseif ( $is_synced && ! $is_payment_upfront && $needs_shipping ) { + continue; + } elseif ( $has_trial_period && $needs_shipping ) { + continue; + } else { + // If we made it this far, the product is valid. Break out of the foreach and return early as we only care about invalid cases. + $is_invalid = false; + break; + } + } + + return $is_invalid; + } + + /** + * Checks whether cart contains a subscription product or this is a subscription product page. + * + * @return boolean + */ + public function has_subscription_product() { + if ( ! class_exists( 'WC_Subscriptions_Product' ) ) { + return false; + } + + if ( $this->is_product() ) { + $product = $this->get_product(); + if ( WC_Subscriptions_Product::is_subscription( $product ) ) { + return true; + } + } elseif ( WC_Stripe_Helper::has_cart_or_checkout_on_current_page() ) { + foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { + $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); + if ( WC_Subscriptions_Product::is_subscription( $_product ) ) { + return true; + } + } + } + + return false; + } + + /** + * Checks if this is a product page or content contains a product_page shortcode. + * + * @return boolean + */ + public function is_product() { + return is_product() || wc_post_content_has_shortcode( 'product_page' ); + } + + /** + * Get product from product page or product_page shortcode. + * + * @return WC_Product Product object. + */ + public function get_product() { + global $post; + + if ( is_product() ) { + return wc_get_product( $post->ID ); + } elseif ( wc_post_content_has_shortcode( 'product_page' ) ) { + // Get id from product_page shortcode. + preg_match( '/\[product_page id="(?