&ailoquence_sig=. * Ailoquence lo firma con el Store Secret; aquí se comprueba la firma y la caducidad y se * reconstruye el carrito antes de llevar al checkout. Sin el secreto no se puede fabricar uno. * * Todas las peticiones a Ailoquence van firmadas (HMAC-SHA256 del cuerpo con el Store Secret, * cabecera X-Ailoquence-Signature) y llevan la Store Public Key y la hora, para que no valga * reenviar una antigua. Ver WpStoreNewsletterController en el backend. */ // Dos campos y no uno: la casilla significa cosas opuestas según el cliente ("quiero el recordatorio" // para un visitante, "no lo quiero" para quien ya compró) y WooCommerce recuerda el último valor de // cada campo de contacto en el cliente. Con un solo ID, quien dio su permiso como visitante veía // después, ya como cliente, marcada la casilla de rechazarlo. define('AILOQUENCE_CART_FIELD', 'ailoquence/cart-reminder'); define('AILOQUENCE_CART_OPTOUT_FIELD', 'ailoquence/cart-reminder-optout'); /** Campo del checkout de bloques que corresponde a este cliente. */ function ailoquence_cart_field_id($returning) { return $returning ? AILOQUENCE_CART_OPTOUT_FIELD : AILOQUENCE_CART_FIELD; } // ── Ajustes ── /** Interruptor general; por defecto activado (comportamiento de las versiones anteriores). */ function ailoquence_newsletter_enabled() { $store_opt = ailoquence_get_store_options(); return !isset($store_opt['newsletter_enabled']) || !empty($store_opt['newsletter_enabled']); } /** Se pueden capturar carritos: tienda conectada a Ailoquence y newsletter activado. */ function ailoquence_cart_capture_active() { $store_opt = ailoquence_get_store_options(); return ailoquence_is_woocommerce_active() && !empty($store_opt['store_connected']) && !empty($store_opt['connection_id']) && ailoquence_newsletter_enabled(); } /** * Petición firmada a /api/wp/store/{connectionId}{$path}. $blocking false para lo que ocurre en el * checkout del cliente (no debe esperar a Ailoquence); true para lo que hace el administrador. */ function ailoquence_signed_post($path, array $data, $blocking = true) { $store_opt = ailoquence_get_store_options(); if (empty($store_opt['connection_id']) || empty($store_opt['store_secret'])) { return new WP_Error('ailoquence_not_connected', __('The store is not connected to Ailoquence.', 'ailoquence-connector')); } $body = wp_json_encode(array_merge([ 'publicKey' => $store_opt['store_public_key'], 'ts' => time(), ], $data)); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- HMAC signature encoding, not obfuscation. $signature = base64_encode(hash_hmac('sha256', $body, $store_opt['store_secret'], true)); return wp_remote_post(ailoquence_api_base_url() . '/wp/store/' . rawurlencode($store_opt['connection_id']) . $path, [ 'timeout' => $blocking ? 15 : 3, 'blocking' => $blocking, 'headers' => [ 'Content-Type' => 'application/json', 'X-Ailoquence-Signature' => $signature, ], 'body' => $body, ]); } /** * Guarda el interruptor y se lo comunica a Ailoquence. Si Ailoquence no responde se guarda igual * (el plugin deja de capturar carritos ya) y se avisa de que hay que reintentar. */ function ailoquence_set_newsletter_enabled($enabled) { $store_opt = ailoquence_get_store_options(); $store_opt['newsletter_enabled'] = $enabled ? 1 : 0; ailoquence_update_store_options($store_opt); if (empty($store_opt['store_connected'])) return true; $response = ailoquence_signed_post('/newsletter', ['enabled' => (bool) $enabled]); if (is_wp_error($response)) return $response; $code = (int) wp_remote_retrieve_response_code($response); if ($code < 200 || $code >= 300) { // El ajuste local ya está guardado (la tienda deja de pedir permiso al momento); falta que la app lo sepa. /* translators: %d: HTTP status code. */ return new WP_Error('ailoquence_toggle_failed', sprintf(__('Saved on this site, but Ailoquence did not receive the change (code %d), so its alerts may not have changed yet. Save again in a few minutes.', 'ailoquence-connector'), $code)); } return true; } // ── Consentimiento en el checkout ── /** Cliente con sesión iniciada y algún pedido pagado en esta tienda. */ function ailoquence_is_returning_customer() { if (!is_user_logged_in() || !function_exists('wc_get_customer_order_count')) return false; return wc_get_customer_order_count(get_current_user_id()) > 0; } /** Texto de la casilla según el caso (es también la prueba que se guarda). */ function ailoquence_cart_field_label($returning) { return $returning ? __('Don\'t send me an email with my cart if I leave without finishing the purchase', 'ailoquence-connector') : __('Save my cart and email me a reminder if I don\'t finish the purchase', 'ailoquence-connector'); } function ailoquence_cart_field_description($returning) { return $returning ? __('As you have bought from us before, if you leave without finishing we may send you one email with your cart. You can unsubscribe from any email.', 'ailoquence-connector') : __('Optional. We will send you one email with your cart; you can unsubscribe from it.', 'ailoquence-connector'); } /** * Checkout de bloques (WooCommerce 8.9+): campo adicional en "Contact information". El valor viaja * con la información de contacto del Store API mientras el cliente rellena el checkout. */ add_action('woocommerce_init', function () { if (!function_exists('woocommerce_register_additional_checkout_field') || !ailoquence_cart_capture_active()) return; $returning = ailoquence_is_returning_customer(); woocommerce_register_additional_checkout_field([ 'id' => ailoquence_cart_field_id($returning), 'label' => ailoquence_cart_field_label($returning), 'location' => 'contact', 'type' => 'checkbox', ]); }); /** Checkout clásico (shortcode): casilla antes del botón de pagar. */ add_action('woocommerce_review_order_before_submit', function () { if (!ailoquence_cart_capture_active()) return; $returning = ailoquence_is_returning_customer(); ?>

get(\Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFields::class); return (bool) $fields->get_field_from_object($field, $customer, 'other'); } catch (\Throwable $e) { return false; } } /** Checkout de bloques: cada vez que el cliente actualiza sus datos de contacto o dirección. */ add_action('woocommerce_store_api_cart_update_customer_from_request', function ($customer, $request) { if (!ailoquence_cart_capture_active() || !$customer) return; $field = ailoquence_cart_field_id(ailoquence_is_returning_customer()); $checked = ailoquence_blocks_field_checked($customer, $field); $additional = $request->get_param('additional_fields'); if (is_array($additional) && array_key_exists($field, $additional)) { $checked = !empty($additional[$field]); } // Los campos adicionales del checkout de bloques no muestran descripción: solo se vio la etiqueta. ailoquence_capture_cart($customer->get_billing_email(), $customer->get_billing_first_name(), $checked, false); }, 10, 2); /** * Cliente con sesión que abre el checkout: su email ya viene relleno, así que si solo mira y se va * no hay ninguna actualización que lo capture (y es justo el caso más habitual de quien ya compró). * Se captura al cargar la página con sus datos guardados y el valor que tenga la casilla. */ add_action('template_redirect', function () { if (!ailoquence_cart_capture_active() || !is_user_logged_in() || !function_exists('is_checkout') || !is_checkout() || is_wc_endpoint_url('order-received') || !WC()->customer) return; $customer = WC()->customer; $returning = ailoquence_is_returning_customer(); $blocks = function_exists('has_block') && has_block('woocommerce/checkout', wc_get_page_id('checkout')); // En el clásico la casilla siempre empieza desmarcada; en bloques, con el último valor guardado. $checked = $blocks ? ailoquence_blocks_field_checked($customer, ailoquence_cart_field_id($returning)) : false; ailoquence_capture_cart($customer->get_billing_email(), $customer->get_billing_first_name(), $checked, !$blocks); }); /** * Decide si hay base para guardar el carrito y, si la hay y algo cambió, se lo envía a Ailoquence * (sin esperar respuesta). $checked: la casilla — "quiero el recordatorio" para un visitante, * "no lo quiero" para un cliente anterior. $shown_description: si el checkout mostró también la * descripción bajo la casilla (clásico sí, bloques no); la prueba del consentimiento guarda solo * lo que el cliente vio. */ function ailoquence_capture_cart($email, $first_name, $checked, $shown_description) { if (!function_exists('WC') || !WC()->session || !WC()->cart) return; $returning = ailoquence_is_returning_customer(); $basis = $returning ? ($checked ? '' : 'EXISTING_CUSTOMER') : ($checked ? 'CONSENT' : ''); $token = WC()->session->get('ailoquence_cart_token'); $email = sanitize_email((string) $email); if ($basis === '' || !is_email($email)) { // Sin permiso (o lo retiró): si ya se había enviado, se cierra en Ailoquence. if ($token && WC()->session->get('ailoquence_cart_sent')) { ailoquence_signed_post('/cart', ['cartToken' => $token, 'emptied' => true], false); WC()->session->set('ailoquence_cart_sent', null); WC()->session->set('ailoquence_cart_hash', null); } return; } $items = []; foreach (WC()->cart->get_cart() as $line) { $items[] = [ 'productId' => (int) $line['product_id'], 'variationId' => (int) ($line['variation_id'] ?? 0), 'quantity' => (int) $line['quantity'], ]; } if (empty($items)) return; if (!$token) { $token = wp_generate_password(32, false, false); WC()->session->set('ailoquence_cart_token', $token); } $data = [ 'cartToken' => $token, 'email' => $email, 'firstName' => sanitize_text_field((string) $first_name), 'items' => $items, 'total' => (float) WC()->cart->get_total('edit'), 'currency' => get_woocommerce_currency(), 'basis' => $basis, 'consentText' => ailoquence_cart_field_label($returning) . ($shown_description ? ' — ' . ailoquence_cart_field_description($returning) : ''), 'consentAt' => time(), ]; // Solo si cambió algo relevante (el checkout recalcula a menudo). $hash = md5(wp_json_encode([$email, $first_name, $items, $basis])); if (WC()->session->get('ailoquence_cart_hash') === $hash) return; ailoquence_signed_post('/cart', $data, false); WC()->session->set('ailoquence_cart_hash', $hash); WC()->session->set('ailoquence_cart_sent', 1); } /** Pedido hecho: el carrito siguiente es otro (Ailoquence ya cierra este al recibir el pedido). */ function ailoquence_reset_cart_token() { if (function_exists('WC') && WC()->session) { WC()->session->set('ailoquence_cart_token', null); WC()->session->set('ailoquence_cart_hash', null); WC()->session->set('ailoquence_cart_sent', null); } } add_action('woocommerce_checkout_order_processed', 'ailoquence_reset_cart_token'); add_action('woocommerce_store_api_checkout_order_processed', 'ailoquence_reset_cart_token'); // ── Enlace "Complete my purchase" ── /** Base64 URL-safe sin relleno, como lo genera Ailoquence (Base64.getUrlEncoder().withoutPadding()). */ function ailoquence_base64url($binary) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- URL-safe encoding of a signed payload. return rtrim(strtr(base64_encode($binary), '+/', '-_'), '='); } function ailoquence_base64url_decode($text) { $text = strtr((string) $text, '-_', '+/'); $pad = strlen($text) % 4; if ($pad) $text .= str_repeat('=', 4 - $pad); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- decoding a signed payload. return base64_decode($text, true); } /** * Reconstruye el carrito del enlace firmado y lleva al checkout. Firma o caducidad inválidas: se * lleva al carrito con un aviso, sin tocar lo que hubiera. */ add_action('wp_loaded', function () { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- signed link from an email (HMAC), not a form. if (!isset($_GET['ailoquence_cart'], $_GET['ailoquence_sig']) || !ailoquence_is_woocommerce_active() || !function_exists('WC') || !WC()->cart) return; $payload = sanitize_text_field(wp_unslash($_GET['ailoquence_cart'])); $signature = sanitize_text_field(wp_unslash($_GET['ailoquence_sig'])); // phpcs:enable WordPress.Security.NonceVerification.Recommended $store_opt = ailoquence_get_store_options(); $expected = empty($store_opt['store_secret']) ? '' : ailoquence_base64url(hash_hmac('sha256', $payload, $store_opt['store_secret'], true)); $decoded = ailoquence_base64url_decode($payload); $parts = $decoded === false ? [] : explode('|', $decoded); if ($expected === '' || !hash_equals($expected, $signature) || count($parts) !== 2 || (int) $parts[1] < time()) { wc_add_notice(__('This link to your cart has expired or is not valid. Your current cart has not been changed.', 'ailoquence-connector'), 'notice'); wp_safe_redirect(wc_get_cart_url()); exit; } WC()->cart->empty_cart(); foreach (explode(',', $parts[0]) as $line) { $values = array_map('intval', explode(':', $line)); if (count($values) !== 3 || $values[0] <= 0 || $values[2] <= 0) continue; list($product_id, $variation_id, $quantity) = $values; $variation = $variation_id > 0 ? wc_get_product_variation_attributes($variation_id) : []; WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variation); } wp_safe_redirect(WC()->cart->is_empty() ? wc_get_cart_url() : wc_get_checkout_url()); exit; }); // ── Privacidad ── add_action('admin_init', function () { if (!function_exists('wp_add_privacy_policy_content')) return; wp_add_privacy_policy_content('Ailoquence Connector', wp_kses_post(wpautop( __('This store uses Ailoquence (https://ailoquence.com) to send email alerts to its customers, such as new products, sales, products back in stock, review requests and repurchase reminders. For this, Ailoquence processes your email address, first name and order history on behalf of this store, as its data processor. If you leave your cart without finishing the purchase, the checkout asks for your permission to email you one reminder (customers who have bought before and are logged in are informed and can opt out with a checkbox); only then are your email address, first name and cart contents sent to Ailoquence, together with the text you were shown and the time. Every email includes a link to unsubscribe.', 'ailoquence-connector') ))); });