options->isUsable()) { return; } // Avoid double-charging in nested calculate_totals calls. if (did_action('woocommerce_cart_calculate_fees') > 1 && $this->feeAlreadyAdded($cart)) { return; } $amount = $this->selection->resolveAmount(); if ($amount <= 0.0) { return; } // Tips and donations are not taxed. $cart->add_fee($this->feeLabel(), $amount, false); } /** * AJAX endpoint: store the customer's choice, then let WooCommerce's checkout * AJAX re-render totals. Nonce-protected; no capability needed (front-end * shoppers, logged-in or guest). */ public function handleAjax(): void { check_ajax_referer('tipping_set', 'nonce'); $mode = isset($_POST['mode']) ? sanitize_key(wp_unslash((string) $_POST['mode'])) : 'none'; $choice = ['mode' => $mode]; if ('preset' === $mode && isset($_POST['preset'])) { $choice['preset'] = absint(wp_unslash((string) $_POST['preset'])); } if (isset($_POST['recipient'])) { $choice['recipient'] = sanitize_key(wp_unslash((string) $_POST['recipient'])); } $this->selection->store($choice); wp_send_json_success([ 'amount' => $this->selection->resolveAmount(), ]); } /** * Persist the applied tip onto the order at checkout, so it is auditable in * the admin and in emails (it is already part of the order totals as a fee). */ public function persistOnOrder(\WC_Order $order, mixed $data): void { unset($data); if (! $this->options->isUsable()) { return; } $amount = $this->selection->resolveAmount(); // A block checkout draft order is updated in place: drop a tip removed since. $order->delete_meta_data(self::ORDER_META); $order->delete_meta_data(self::ORDER_PRESET_META); $order->delete_meta_data(self::ORDER_RECIPIENT_META); if ($amount > 0.0) { $order->update_meta_data(self::ORDER_META, wc_format_decimal($amount)); $choice = $this->selection->current(); if ('preset' === $choice['mode']) { $order->update_meta_data(self::ORDER_PRESET_META, (string) $choice['preset']); } if ('' !== $choice['recipient']) { $order->update_meta_data(self::ORDER_RECIPIENT_META, $choice['recipient']); } } } private function feeLabel(): string { return $this->options->label(); } /** * Whether a fee with our label is already present on the cart. */ private function feeAlreadyAdded(\WC_Cart $cart): bool { $label = $this->feeLabel(); foreach ($cart->get_fees() as $fee) { if (isset($fee->name) && $fee->name === $label) { return true; } } return false; } }