plugin = $plugin; } public function set_cart(ThreeDL_CC_Free_Cart $cart): void { $this->cart = $cart; } public function hooks(): void { add_action('rest_api_init', [$this, 'register_rest_routes']); add_action('template_redirect', [$this, 'maybe_import_remote_product'], 1); add_action('template_redirect', [$this, 'maybe_redirect_destination'], 2); if ($this->plugin->is_main()) { add_filter('allowed_redirect_hosts', [$this, 'allow_trusted_source_redirect_hosts'], 20, 2); } if ($this->plugin->is_source()) { add_action('template_redirect', [$this, 'maybe_handle_source_return_notice'], 0); add_action('woocommerce_add_to_cart', [$this, 'capture_added_item'], 900, 6); add_filter('woocommerce_add_to_cart_redirect', [$this, 'redirect_after_add_to_cart'], 99, 2); add_filter('woocommerce_get_cart_url', [$this, 'filter_source_cart_url'], 99, 1); add_filter('woocommerce_get_checkout_url', [$this, 'filter_source_checkout_url'], 99, 1); add_filter('woocommerce_loop_add_to_cart_link', [$this, 'disable_ajax_loop_add_to_cart'], 99, 3); add_filter('allowed_redirect_hosts', [$this, 'allow_main_store_redirect_host'], 20, 2); add_action('wp_enqueue_scripts', [$this, 'enqueue_source_redirect_script']); add_action('wp_ajax_3dl_cc_free_pending_transfer', [$this, 'ajax_pending_transfer']); add_action('wp_ajax_nopriv_3dl_cc_free_pending_transfer', [$this, 'ajax_pending_transfer']); } } public function register_rest_routes(): void { register_rest_route(self::REST_NAMESPACE, '/product/validate', [ 'methods' => 'POST', 'callback' => [$this, 'rest_validate_product'], 'permission_callback' => [$this, 'rest_validate_product_permission'], ]); } public function capture_added_item($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data): void { if (!$this->plugin->is_source() || !$this->source_config_ready()) { return; } $effective_id = $variation_id ? absint($variation_id) : absint($product_id); $product = wc_get_product($effective_id); if (!$product) { return; } $payload = $this->build_product_payload($product, absint($product_id), absint($variation_id), max(1, (int) $quantity)); if (is_wp_error($payload)) { wc_add_notice($payload->get_error_message(), 'error'); return; } $this->pending_transfer_url = $this->build_import_url($payload); $this->pending_cart_item_key = (string) $cart_item_key; if (WC()->session) { WC()->session->set('3dl_cc_free_pending_transfer_url', $this->pending_transfer_url); WC()->session->set('3dl_cc_free_pending_cart_item_key', $this->pending_cart_item_key); } } public function redirect_after_add_to_cart($url, $adding_to_cart) { if (!$this->plugin->is_source()) { return $url; } $transfer_url = $this->pending_transfer_url; $cart_key = $this->pending_cart_item_key; if ($transfer_url === '' && WC()->session) { $transfer_url = (string) WC()->session->get('3dl_cc_free_pending_transfer_url', ''); $cart_key = (string) WC()->session->get('3dl_cc_free_pending_cart_item_key', ''); } if ($transfer_url === '') { return $url; } $this->consume_pending_transfer($cart_key); return $transfer_url; } public function enqueue_source_redirect_script(): void { if (!$this->plugin->is_source()) { return; } wp_enqueue_script('jquery'); $ajax_url = add_query_arg( [ 'action' => '3dl_cc_free_pending_transfer', '_ajax_nonce' => wp_create_nonce('3dl_cc_free_pending_transfer'), ], admin_url('admin-ajax.php') ); $script = 'jQuery(function($){var busy=false;function go(){if(busy)return;busy=true;fetch(' . wp_json_encode($ajax_url) . ',{credentials:"same-origin",cache:"no-store"}).then(function(r){return r.json();}).then(function(j){if(j&&j.success&&j.data&&j.data.url){window.location.href=j.data.url;return;}busy=false;}).catch(function(){busy=false;});}$(document.body).on("added_to_cart",go);document.body.addEventListener("wc-blocks_added_to_cart",go);});'; wp_add_inline_script('jquery', $script, 'after'); } public function ajax_pending_transfer(): void { if (!check_ajax_referer('3dl_cc_free_pending_transfer', '_ajax_nonce', false)) { wp_send_json_error(['message' => __('Invalid request.', '3dl-central-checkout-for-woocommerce')], 403); } if (!$this->plugin->is_source()) { wp_send_json_error(['message' => __('This site is not configured as a source store.', '3dl-central-checkout-for-woocommerce')], 400); } $url = WC()->session ? (string) WC()->session->get('3dl_cc_free_pending_transfer_url', '') : ''; $cart_key = WC()->session ? (string) WC()->session->get('3dl_cc_free_pending_cart_item_key', '') : ''; if ($url === '') { wp_send_json_error(['message' => __('No pending product transfer was found.', '3dl-central-checkout-for-woocommerce')], 404); } $this->consume_pending_transfer($cart_key); wp_send_json_success(['url' => esc_url_raw($url)]); } private function consume_pending_transfer(string $cart_key = ''): void { if ($cart_key !== '' && WC()->cart && isset(WC()->cart->cart_contents[$cart_key])) { WC()->cart->remove_cart_item($cart_key); WC()->cart->set_session(); } if (WC()->session) { WC()->session->__unset('3dl_cc_free_pending_transfer_url'); WC()->session->__unset('3dl_cc_free_pending_cart_item_key'); } $this->pending_transfer_url = ''; $this->pending_cart_item_key = ''; } public function disable_ajax_loop_add_to_cart(string $html, $product, array $args): string { if (!$this->plugin->is_source() || !is_a($product, 'WC_Product')) { return $html; } if (!$product->is_type('simple') || !$product->is_purchasable() || !$product->is_in_stock()) { return $html; } $url = add_query_arg('add-to-cart', $product->get_id(), home_url('/')); $classes = 'button product_type_simple add_to_cart_button'; return sprintf( '%4$s', esc_url($url), esc_attr($classes), absint($product->get_id()), esc_html($product->add_to_cart_text()) ); } public function allow_trusted_source_redirect_hosts(array $hosts, string $host): array { foreach ($this->plugin->trusted_sources() as $source_url) { $source_host = wp_parse_url($source_url, PHP_URL_HOST); if (is_string($source_host) && $source_host !== '') { $hosts[] = strtolower($source_host); } } return array_values(array_unique(array_filter($hosts))); } public function maybe_handle_source_return_notice(): void { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only return marker; no privileged action is performed from this value. if (!$this->plugin->is_source() || empty($_GET['3dl_cc_free_added'])) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only return marker; no privileged action is performed from this value. if (sanitize_text_field(wp_unslash($_GET['3dl_cc_free_added'])) !== '1') { return; } if (function_exists('wc_add_notice')) { wc_add_notice(__('Product added to the central cart.', '3dl-central-checkout-for-woocommerce'), 'success'); } $request_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw((string) wp_unslash($_SERVER['REQUEST_URI'])) : '/'; $site = wp_parse_url(home_url('/')); $scheme = is_array($site) ? (string) ($site['scheme'] ?? 'https') : 'https'; $host = is_array($site) ? (string) ($site['host'] ?? '') : ''; $port = is_array($site) && !empty($site['port']) ? ':' . absint($site['port']) : ''; $current_url = $host !== '' ? $scheme . '://' . $host . $port . $request_uri : home_url('/'); $clean_url = remove_query_arg('3dl_cc_free_added', $current_url); wp_safe_redirect($clean_url ?: home_url('/')); exit; } public function allow_main_store_redirect_host(array $hosts, string $host): array { $main_host = wp_parse_url($this->plugin->main_store_url(), PHP_URL_HOST); if (is_string($main_host) && $main_host !== '') { $hosts[] = strtolower($main_host); } return array_values(array_unique(array_filter($hosts))); } public function filter_source_cart_url($url) { return $this->main_destination_url('cart') ?: $url; } public function filter_source_checkout_url($url) { return $this->main_destination_url('checkout') ?: $url; } public function maybe_redirect_destination(): void { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This parameter only selects a safe local redirect destination. if (!$this->plugin->is_main() || empty($_GET[self::DESTINATION_QUERY])) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This parameter only selects a safe local redirect destination. $destination = sanitize_key((string) wp_unslash($_GET[self::DESTINATION_QUERY])); if ($destination === 'cart') { wp_safe_redirect(wc_get_cart_url()); exit; } if ($destination === 'checkout') { wp_safe_redirect(wc_get_checkout_url()); exit; } } public function maybe_import_remote_product(): void { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Cross-store imports are authenticated below with a short-lived HMAC-signed payload, not a WordPress user nonce. if (!$this->plugin->is_main() || empty($_GET[self::IMPORT_QUERY])) { return; } if (!$this->main_config_ready()) { $this->fail_to_cart(__('Central Checkout is not configured on the main store.', '3dl-central-checkout-for-woocommerce')); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The payload is verified immediately below using HMAC-SHA256 and an expiry timestamp. $encoded = isset($_GET['payload']) ? sanitize_text_field((string) wp_unslash($_GET['payload'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The signature is the authentication mechanism for this cross-store request. $signature = isset($_GET['sig']) ? sanitize_text_field((string) wp_unslash($_GET['sig'])) : ''; $json = $this->base64url_decode($encoded); if ($json === '' || $signature === '' || !$this->signature_valid($json, $signature)) { $this->fail_to_cart(__('The product transfer signature is invalid.', '3dl-central-checkout-for-woocommerce')); } $payload = json_decode($json, true); if (!is_array($payload)) { $this->fail_to_cart(__('The product transfer data is invalid.', '3dl-central-checkout-for-woocommerce')); } $timestamp = absint($payload['time'] ?? 0); if (!$timestamp || abs(time() - $timestamp) > $this->plugin->transfer_ttl()) { $this->fail_to_cart(__('The product transfer link has expired. Please add the product again.', '3dl-central-checkout-for-woocommerce')); } $source_url = $this->plugin->normalize_url((string) ($payload['source_url'] ?? '')); if (!$this->plugin->source_is_trusted($source_url)) { $this->fail_to_cart(__('This source store is not trusted by the main store.', '3dl-central-checkout-for-woocommerce')); } $currency = sanitize_text_field((string) ($payload['currency'] ?? '')); if ($currency === '' || strtoupper($currency) !== strtoupper(get_woocommerce_currency())) { $this->fail_to_cart(__('The source store uses a different currency than the main store.', '3dl-central-checkout-for-woocommerce')); } $weight_unit = sanitize_key((string) ($payload['weight_unit'] ?? '')); $dimension_unit = sanitize_key((string) ($payload['dimension_unit'] ?? '')); if ($weight_unit !== sanitize_key((string) get_option('woocommerce_weight_unit', 'kg')) || $dimension_unit !== sanitize_key((string) get_option('woocommerce_dimension_unit', 'cm'))) { $this->fail_to_cart(__('The source store uses different weight or dimension units than the main store.', '3dl-central-checkout-for-woocommerce')); } if (!$this->cart || !$this->cart->import_remote_item($payload)) { $this->fail_to_cart(__('The product could not be added to the central cart.', '3dl-central-checkout-for-woocommerce')); } $after_add = sanitize_key((string) ($payload['after_add'] ?? 'return_source')); if ($after_add === 'return_source') { $return_url = $this->source_return_url($payload, $source_url); if ($return_url !== '') { wp_safe_redirect(add_query_arg('3dl_cc_free_added', '1', $return_url)); exit; } } wc_add_notice(__('Product added to the central cart.', '3dl-central-checkout-for-woocommerce'), 'success'); wp_safe_redirect(wc_get_cart_url()); exit; } public function rest_validate_product_permission(WP_REST_Request $request) { if (!$this->plugin->is_source() || !$this->source_config_ready()) { return new WP_Error( '3dl_cc_free_source_not_ready', __('This site is not configured as a source store.', '3dl-central-checkout-for-woocommerce'), ['status' => 403] ); } $raw = (string) $request->get_body(); $signature = sanitize_text_field((string) $request->get_header('x-3dl-cc-free-signature')); if ($raw === '' || $signature === '' || !$this->signature_valid($raw, $signature)) { return new WP_Error( '3dl_cc_free_invalid_signature', __('Invalid request signature.', '3dl-central-checkout-for-woocommerce'), ['status' => 403] ); } return true; } public function rest_validate_product(WP_REST_Request $request) { $raw = (string) $request->get_body(); $payload = json_decode($raw, true); if (!is_array($payload)) { return new WP_REST_Response(['success' => false, 'message' => __('Invalid request data.', '3dl-central-checkout-for-woocommerce')], 400); } $main_url = $this->plugin->normalize_url((string) ($payload['main_url'] ?? '')); if ($main_url === '' || !hash_equals(strtolower($this->plugin->main_store_url()), strtolower($main_url))) { return new WP_REST_Response(['success' => false, 'message' => __('The requesting main store does not match this source store configuration.', '3dl-central-checkout-for-woocommerce')], 403); } $timestamp = absint($payload['time'] ?? 0); if (!$timestamp || abs(time() - $timestamp) > $this->plugin->transfer_ttl()) { return new WP_REST_Response(['success' => false, 'message' => __('The validation request has expired.', '3dl-central-checkout-for-woocommerce')], 408); } $variation_id = absint($payload['variation_id'] ?? 0); $product_id = absint($payload['product_id'] ?? 0); $lookup_id = $variation_id ?: $product_id; $product = $lookup_id ? wc_get_product($lookup_id) : false; if (!$product) { return new WP_REST_Response(['success' => true, 'available' => false, 'message' => __('Product was not found on the source store.', '3dl-central-checkout-for-woocommerce')], 200); } $qty = max(1, absint($payload['qty'] ?? 1)); $available = $product->is_purchasable() && $product->is_in_stock(); $message = $available ? __('Product is available.', '3dl-central-checkout-for-woocommerce') : __('Product is not currently purchasable or in stock.', '3dl-central-checkout-for-woocommerce'); if ($available && $product->managing_stock() && !$product->backorders_allowed()) { $stock = $product->get_stock_quantity(); if ($stock !== null && $qty > (int) $stock) { $available = false; $message = __('The requested quantity is not available on the source store.', '3dl-central-checkout-for-woocommerce'); } } $current_price = (float) $product->get_price('edit'); $sent_price = (float) wc_format_decimal($payload['price'] ?? 0, wc_get_price_decimals()); $price_changed = abs($current_price - $sent_price) > 0.0001; if ($available && $price_changed) { $available = false; $message = __('The product price changed on the source store.', '3dl-central-checkout-for-woocommerce'); } if (strtoupper((string) ($payload['currency'] ?? '')) !== strtoupper(get_woocommerce_currency())) { $available = false; $message = __('The source store currency no longer matches the central cart.', '3dl-central-checkout-for-woocommerce'); } return new WP_REST_Response([ 'success' => true, 'available' => $available, 'message' => $message, 'price' => wc_format_decimal($current_price, wc_get_price_decimals()), 'price_changed' => $price_changed ? 'yes' : 'no', 'stock_status' => $product->get_stock_status(), 'stock_quantity' => $product->get_stock_quantity(), ], 200); } public function validate_remote_item(array $remote, int $qty) { $secret = $this->plugin->get_secret(); $source_url = $this->plugin->normalize_url((string) ($remote['source_url'] ?? '')); if ($secret === '' || !$this->plugin->source_is_trusted($source_url)) { return new WP_Error('3dl_cc_free_untrusted_source', __('A remote cart item comes from an untrusted source store.', '3dl-central-checkout-for-woocommerce')); } $payload = [ 'main_url' => $this->plugin->current_store_url(), 'product_id' => absint($remote['product_id'] ?? 0), 'variation_id' => absint($remote['variation_id'] ?? 0), 'qty' => max(1, $qty), 'price' => wc_format_decimal($remote['price'] ?? 0, wc_get_price_decimals()), 'currency' => get_woocommerce_currency(), 'time' => time(), ]; $body = wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if (!$body) { return new WP_Error('3dl_cc_free_bad_validation_payload', __('Could not prepare remote product validation.', '3dl-central-checkout-for-woocommerce')); } $endpoint = trailingslashit($source_url) . 'wp-json/' . self::REST_NAMESPACE . '/product/validate'; $response = wp_remote_post($endpoint, [ 'timeout' => 8, 'headers' => [ 'Content-Type' => 'application/json; charset=utf-8', 'X-3DL-CC-Free-Signature' => hash_hmac('sha256', $body, $secret), ], 'body' => $body, ]); if (is_wp_error($response)) { $message = sprintf( /* translators: 1: source store URL, 2: remote request error message. */ __('Could not verify a product on %1$s: %2$s', '3dl-central-checkout-for-woocommerce'), esc_html($source_url), $response->get_error_message() ); return new WP_Error('3dl_cc_free_source_unreachable', $message); } $code = (int) wp_remote_retrieve_response_code($response); $json = json_decode((string) wp_remote_retrieve_body($response), true); if ($code < 200 || $code >= 300 || !is_array($json) || empty($json['success'])) { $message = sprintf( /* translators: %s: source store URL. */ __('The source store %s did not return a valid product check.', '3dl-central-checkout-for-woocommerce'), esc_html($source_url) ); return new WP_Error('3dl_cc_free_bad_source_response', $message); } if (empty($json['available'])) { $message = !empty($json['message']) ? (string) $json['message'] : __('The product is no longer available.', '3dl-central-checkout-for-woocommerce'); return new WP_Error('3dl_cc_free_remote_unavailable', $message); } return true; } private function build_product_payload($product, int $product_id, int $variation_id, int $qty) { if (!is_a($product, 'WC_Product')) { return new WP_Error('3dl_cc_free_invalid_product', __('The selected product could not be loaded.', '3dl-central-checkout-for-woocommerce')); } if (!$product->is_purchasable()) { return new WP_Error('3dl_cc_free_not_purchasable', __('This product cannot currently be purchased.', '3dl-central-checkout-for-woocommerce')); } $image_id = $product->get_image_id(); if (!$image_id && $variation_id) { $parent = wc_get_product($product_id); if ($parent) { $image_id = $parent->get_image_id(); } } $image_url = $image_id ? (string) wp_get_attachment_image_url($image_id, 'woocommerce_thumbnail') : ''; return [ 'source_url' => $this->plugin->current_store_url(), 'source_name' => wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES), 'product_id' => $product_id, 'variation_id' => $variation_id, 'name' => $product->get_name(), 'sku' => (string) $product->get_sku(), 'product_url' => (string) $product->get_permalink(), 'image_url' => esc_url_raw($image_url), 'price' => wc_format_decimal((float) $product->get_price('edit'), wc_get_price_decimals()), 'currency' => get_woocommerce_currency(), 'tax_status' => sanitize_key((string) $product->get_tax_status()), 'tax_class' => sanitize_title((string) $product->get_tax_class()), 'virtual' => $product->is_virtual() ? 'yes' : 'no', 'weight' => (string) $product->get_weight('edit'), 'length' => (string) $product->get_length('edit'), 'width' => (string) $product->get_width('edit'), 'height' => (string) $product->get_height('edit'), 'shipping_class' => sanitize_title((string) $product->get_shipping_class()), 'attributes' => $this->display_attributes($product), 'weight_unit' => sanitize_key((string) get_option('woocommerce_weight_unit', 'kg')), 'dimension_unit' => sanitize_key((string) get_option('woocommerce_dimension_unit', 'cm')), 'qty' => $qty, 'after_add' => $this->plugin->after_add_behavior(), 'time' => time(), ]; } private function display_attributes($product): array { if (!is_a($product, 'WC_Product_Variation')) { return []; } $out = []; foreach ($product->get_variation_attributes() as $key => $value) { if ($value === '') { continue; } $taxonomy = str_replace('attribute_', '', (string) $key); $label = wc_attribute_label($taxonomy, $product); $display = (string) $value; if (taxonomy_exists($taxonomy)) { $term = get_term_by('slug', (string) $value, $taxonomy); if ($term && !is_wp_error($term)) { $display = (string) $term->name; } } $out[sanitize_text_field((string) $label)] = sanitize_text_field($display); } return $out; } private function source_return_url(array $payload, string $source_url): string { $candidate = esc_url_raw((string) ($payload['product_url'] ?? '')); if ($candidate === '') { return $source_url; } $source = wp_parse_url($source_url); $target = wp_parse_url($candidate); if (!is_array($source) || !is_array($target)) { return $source_url; } $source_scheme = strtolower((string) ($source['scheme'] ?? '')); $target_scheme = strtolower((string) ($target['scheme'] ?? '')); $source_host = strtolower((string) ($source['host'] ?? '')); $target_host = strtolower((string) ($target['host'] ?? '')); $source_path = trailingslashit((string) ($source['path'] ?? '/')); $target_path = trailingslashit((string) ($target['path'] ?? '/')); if ($source_scheme !== $target_scheme || $source_host === '' || $source_host !== $target_host) { return $source_url; } if (strpos($target_path, $source_path) !== 0) { return $source_url; } return $candidate; } private function build_import_url(array $payload): string { $main = $this->plugin->main_store_url(); $json = wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($main === '' || !$json) { return ''; } $encoded = $this->base64url_encode($json); return add_query_arg([ self::IMPORT_QUERY => '1', 'payload' => $encoded, 'sig' => hash_hmac('sha256', $json, $this->plugin->get_secret()), ], $main); } private function main_destination_url(string $destination): string { $main = $this->plugin->main_store_url(); if ($main === '') { return ''; } return add_query_arg(self::DESTINATION_QUERY, $destination, $main); } private function source_config_ready(): bool { return $this->plugin->is_source() && $this->plugin->main_store_url() !== '' && $this->plugin->get_secret() !== ''; } private function main_config_ready(): bool { return $this->plugin->is_main() && $this->plugin->get_secret() !== '' && !empty($this->plugin->trusted_sources()); } private function signature_valid(string $payload, string $signature): bool { $secret = $this->plugin->get_secret(); return $secret !== '' && preg_match('/^[a-f0-9]{64}$/i', $signature) && hash_equals(hash_hmac('sha256', $payload, $secret), strtolower($signature)); } private function base64url_encode(string $value): string { return rtrim(strtr(base64_encode($value), '+/', '-_'), '='); } private function base64url_decode(string $value): string { if ($value === '' || !preg_match('/^[A-Za-z0-9_-]+$/', $value)) { return ''; } $pad = strlen($value) % 4; if ($pad) { $value .= str_repeat('=', 4 - $pad); } $decoded = base64_decode(strtr($value, '-_', '+/'), true); return is_string($decoded) ? $decoded : ''; } private function fail_to_cart(string $message): void { if (function_exists('wc_add_notice')) { wc_add_notice($message, 'error'); } wp_safe_redirect(function_exists('wc_get_cart_url') ? wc_get_cart_url() : home_url('/')); exit; } }