Plugin Directory

Changeset 3814612


Ignore:
Timestamp:
11/20/2026 11:29:07 PM (less than one hour ago)
Author:
wondertaxlabs
Message:

Update to version 1.4.1 from GitHub

Location:
wondertax-labs-audita
Files:
4 added
4 deleted
17 edited
1 copied

Legend:

Unmodified
Added
Removed
  • wondertax-labs-audita/assets/icon-256x256.png

    • Property svn:mime-type changed from application/octet-stream to image/png
  • wondertax-labs-audita/assets/icon-362x362.png

    • Property svn:mime-type changed from application/octet-stream to image/png
  • wondertax-labs-audita/assets/icon.svg

    • Property svn:mime-type set to image/svg+xml
  • wondertax-labs-audita/tags/1.4.1/README.md

    r3713776 r3814612  
    1 # WonderTax Labs: Audita
    2 
    3 **Version:** 1.3.7
     1# WonderTax Labs: Audita™
     2
     3**Version:** 1.4.1
    44
    55Your zero-cost, zero-risk sales tax audit agent for every WooCommerce transaction. Connect your store to WonderTax Labs in minutes — your always-on tax auditor that catches errors before auditors do.
    … …  
    77## Features
    88
    9 - **OAuth Integration** - Secure connection between WooCommerce and WonderTax Labs
     9- **Secure Connection** - A token exchange and signed requests between WooCommerce and WonderTax Labs
    1010- **Open WonderTax Labs** - One-click access to your tax compliance dashboard directly from WordPress admin
    1111- **Auto-Update Support** - One-click plugin upgrades directly from WordPress admin when new versions are available
    12 - **Automatic Order Sync** - Webhooks for order.created, order.updated, order.deleted events
     12- **Automatic Order Sync** - Order webhooks (order.created, order.updated, order.deleted) that WonderTax Labs registers on connect
    1313- **Live/Test Mode Indicator** - Visual badges showing API key mode (Test or Live)
    1414- **Transaction Activity Stats** - View recent transaction counts right in WordPress admin
    … …  
    2929### For Users
    3030
    31 1. Download the plugin ZIP file [wondertax-labs-audita-v1.3.7.zip](https://app.wonder.tax/wondertax-labs-audita-v1.3.7.zip)
     311. Download the plugin ZIP file [wondertax-labs-audita-v1.4.1.zip](https://app.wonder.tax/wondertax-labs-audita-v1.4.1.zip)
    32322. In WordPress admin, go to Plugins > Add New > Upload Plugin
    33333. Upload the ZIP file and activate
    34 4. Navigate to WooCommerce > WonderTax Labs: Audita
     344. Navigate to WooCommerce > WonderTax Labs: Audita™
    35355. Click "Connect to WonderTax Labs"
    36 6. **That's it!** Your WonderTax Labs account is created automatically from your WordPress admin email
     366. **Sign in to WonderTax Labs** (or create an account) when asked: the store is bound only to a business you
     37   administer, and no account is identified or created from the WordPress site
    3738
    3839If you already have a WonderTax Labs account with multiple businesses, you'll be asked to choose which entity to connect, or create a new one.
    39 
    40 ### For Developers
    41 
    42 Clone this repository into your WordPress plugins directory:
    43 
    44 ```bash
    45 cd wp-content/plugins/
    46 git clone https://github.com/WonderTax-Labs-Red/diablo.git
    47 cd diablo/wondertax-labs-audita
    48 ```
    49 
    50 Or symlink during development:
    51 
    52 ```bash
    53 cd wp-content/plugins/
    54 ln -s /path/to/diablo/wondertax-labs-audita wondertax-labs-audita
    55 ```
    5640
    5741## Architecture
    … …  
    6448├── includes/
    6549│   ├── class-wondertax-admin.php    # Admin settings page UI
    66 │   ├── class-wondertax-oauth.php    # OAuth credential generation
    67 │   ├── class-wondertax-webhooks.php # Webhook registration
    68 │   ├── class-wondertax-tax-calc.php # Real-time tax calculation
    69 │   └── class-wondertax-updater.php  # Auto-update functionality
     50│   ├── class-wondertax-not-taxable-notice.php # Names the products WooCommerce marks not taxable
     51│   ├── class-wondertax-tax-service.php # Holds the checkout tax setting WonderTax Labs names (hourly sync + ack)
     52│   └── class-wondertax-tax-calc.php # Applies the checkout tax WonderTax Labs answers, when it holds the setting
    7053├── assets/
    7154│   └── css/admin.css                # Admin page styles
    … …  
    7760### Data Flow
    7861
    79 1. **OAuth Connection**
    80    - User clicks "Connect" in WordPress admin
    81    - Plugin generates WooCommerce REST API credentials
    82    - Credentials sent to SvelteKit backend via callback URL
    83    - Backend encrypts and stores credentials in database
    84 
    85 2. **Webhook Registration**
    86    - On successful connection, plugin creates WC_Webhook instances
    87    - Webhooks configured for: order.created, order.updated, order.deleted
    88    - Webhook secret shared with backend for signature verification
    89 
    90 3. **Real-Time Tax Calculation**
    91    - Classic Checkout: Hooks into `woocommerce_find_rates` filter
    92    - Block Checkout: Hooks into Store API via `woocommerce_store_api_cart_update_customer_from_request`
    93    - Builds tax request from cart data and customer address
    94    - Signs request with webhook secret
    95    - Calls SvelteKit `/api/woocommerce/tax-service` endpoint
    96    - Returns tax rates in WooCommerce format
     621. **Connection**
     63   - A store manager clicks "Connect" in WordPress admin
     64   - The plugin creates new WooCommerce REST API credentials, a webhook secret and an install secret, kept as a connect in
     65     progress (`wondertax_pending_connection`): the working connection and its API key are untouched
     66   - The browser goes to `/api/integrations/woocommerce/connect` with a one-time token, signed with the new install secret;
     67     WonderTax Labs fetches the credentials server to server from `/wp-json/wondertax/v1/credentials`
     68   - Once the store is bound in WonderTax Labs, the plugin promotes the connect in progress only when a status read signed
     69     with its new install secret is answered (on the return to WordPress, on the settings page, or on the hourly sync);
     70     then the previous API key is deleted. A connect not confirmed within an hour is discarded. ⚠️ Until it is promoted,
     71     checkout requests are still signed with the working connection's webhook secret, which WonderTax Labs replaced at the
     72     bind: a held store's checkouts are refused (its own rates apply) until then — at most until the hourly sync
     73
     742. **Webhooks**
     75   - WonderTax Labs registers the order webhooks itself on connect, through the REST API, with the stored webhook secret,
     76     and repairs and dedupes its own on a reconnect. The plugin registers none. A disconnect deletes, before it removes the
     77     API key, the ones WonderTax Labs registered (delivering to its order routes on `WONDERTAX_BACKEND_URL`), since WonderTax
     78     Labs' own cleanup reads the store with that key; a disconnect and an uninstall delete any that earlier versions
     79     registered (`wondertax_webhook_ids`)
     80
     813. **Checkout Tax Setting (server-driven)**
     82   - Hourly WP-cron (`wondertax_tax_service_sync`) and each admin page load post a signed `report` and read `taxService` from its signed reply (never from the status read). A refused or failed ack is read again and retried once
     83   - `desired: on`: records the store's own setting (`woocommerce_calc_taxes`, `woocommerce_tax_based_on`, whether standard rate tables exist) under a short lock, switches `woocommerce_tax_based_on` to `shipping`, sets `woocommerce_calc_taxes` ("Enable taxes") to `yes`, and acks `on` with that record. While the setting is held, WooCommerce's taxes stay on (`wc_tax_enabled`) even if the merchant turns "Enable taxes" off, since turning it off does not exempt a sale. An active WooCommerce Tax, TaxJar, Avalara, Vertex, Quaderno or Stripe Tax plugin (WooCommerce Shipping & Tax only while its taxes are on) is acked as a `conflict` instead, and nothing is switched — checked on every sync, so one found while the setting is held gives the store back first. A store whose prices are entered with tax is acked `unsupported` and never switched, and one that changes to it while held is given back once the save completes (flagged by `update_option_woocommerce_prices_include_tax`, run on `woocommerce_settings_saved` or `shutdown`, under the lock; `tax_based_on` is put back only while it is still `shipping`)
     84   - `desired: off` after a takeover: puts back the recorded setting and acks `off`
     85   - Deactivation and disconnect put back the recorded setting and ack `released` (`deactivated` or `disconnected`); one not accepted is acked again until it is (hourly after a disconnect, after a reactivation for a deactivation). A disconnect that cannot put the setting back (another request holds the lock) changes nothing and asks the store manager to try again. A confirmed connect drops a `released` ack WonderTax Labs never heard; until then it is kept
     86   - A release turns `woocommerce_calc_taxes` back to the recorded value only while it is still `yes` (the takeover's value). When it still differs from what was recorded at the takeover, a WordPress admin notice asks a store manager (`manage_woocommerce`) once whether to keep the current setting or turn it back ("Keep it on" / "Turn it off", or the reverse); the actions are nonce-checked admin-post requests. Dismissing keeps the current setting, deactivation keeps it and asks nothing, and a later takeover clears an unanswered question. The answer is sent in the next signed `report` (`release_taxes_answer`); WonderTax Labs records it and changes nothing
     87   - Acks are signed POSTs to `/api/integrations/woocommerce/tax-service/ack` (per-install secret, `site_url|state|timestamp|nonce|payload`)
     88   - While the setting is held, each cart is quoted by the signed `/api/woocommerce/tax-service` (with `X-WC-Webhook-Source`, `X-WC-Webhook-Topic` and `X-WC-Webhook-Signature`), on each line's total after coupons, with the cart's fees and shipping. A negative fee (a discount) is spread over the lines, the charged fees and the shipping exactly as the order's import spreads it, and is never taxed itself. The exact per-line, per-fee, shipping and per-jurisdiction amounts answered are applied (`woocommerce_after_calculate_totals`), and on Block Checkout put on the order's lines. A refusal leaves the store's own rates
    9789
    98904. **Order Webhooks**
    … …  
    116108- Backend performs timing-safe signature comparison
    117109
    118 ### OAuth Flow
    119 
    120 - State parameter uses cryptographically secure random bytes
    121 - One-time use state tokens (deleted after validation)
    122 - State expires after 10 minutes
     110### Signed Requests
     111
     112- The connect link, the dashboard link, the status read, the mode switch and every report are HMAC-SHA256 signed with the
     113  connection's install secret, with a timestamp and a nonce
     114- The connect token is one-time use and expires after an hour
    123115
    124116## Configuration
    … …  
    132124The plugin communicates with these SvelteKit endpoints:
    133125
    134 - `POST /api/woocommerce/auth/callback` - OAuth credential submission
    135 - `POST /api/woocommerce/tax-service` - Real-time tax calculation
    136 - `POST /api/woocommerce/webhooks/order-created` - New order webhook
    137 - `POST /api/woocommerce/webhooks/order-updated` - Updated order webhook
    138 - `POST /api/woocommerce/webhooks/order-deleted` - Deleted order webhook
     126- `GET /api/integrations/woocommerce/connect` - The connect link (signed, one-time token)
     127- `GET /api/integrations/woocommerce/status` - Connection status for the admin page (signed: `site_url|status|timestamp|nonce`)
     128- `GET /api/integrations/woocommerce/open` - The signed "Open WonderTax Labs" link
     129- `POST /api/integrations/woocommerce/mode` - The signed Live/Test Mode switch
     130- `POST /api/integrations/woocommerce/tax-service/ack` - Signed report of the checkout tax setting held; its reply is the setting to hold
     131- `POST /api/woocommerce/tax-service` - Checkout tax quote, while the setting is held
     132- `POST /api/integrations/woocommerce/webhooks/order-*` - The order webhooks WonderTax Labs registers (WooCommerce delivers
     133  them; `/api/woocommerce/webhooks/order-*` still serves webhooks registered by earlier versions)
    139134
    140135## Development
    … …  
    153148Manual testing checklist:
    154149
    155 - [ ] OAuth connection flow
    156 - [ ] Disconnect functionality
    157 - [ ] Real-time tax calculation toggle
    158 - [ ] Webhook registration
     150- [ ] Connect, and a reconnect abandoned midway (the working connection stays)
     151- [ ] Disconnect functionality (WonderTax Labs stops importing; the API key is removed)
     152- [ ] Checkout tax setting sync (takeover, conflict, release)
     153- [ ] The webhooks WonderTax Labs registered appear under WooCommerce > Settings > Advanced > Webhooks
    159154- [ ] Tax calculation during checkout
    160155- [ ] Webhook delivery on order events
    … …  
    1851804. Check error logs for specific error messages
    186181
    187 ### Tax Calculation Not Working
     182### Checkout Tax Not Applied
    188183
    1891841. Verify connection is active (WooCommerce > WonderTax Labs)
    190 2. Verify tax calculation is enabled in settings
     1852. Verify the store holds the setting (option `wondertax_tax_service_state` is `on`)
    1911863. Check address has all required fields (country, state, postcode)
    1921874. Only US addresses are currently supported
  • wondertax-labs-audita/tags/1.4.1/changelog.txt

    r3713774 r3814612  
    1 *** WonderTax Labs Audita Changelog ***
     1*** WonderTax Labs Audita™ Changelog ***
     2
     32026-11-13 - version 1.4.1
     4* Changed - Connecting no longer sends the site's admin email address to WonderTax Labs; you sign in to WonderTax Labs yourself
     5* Changed - Reconnecting keeps your working connection until WonderTax Labs confirms the new one
     6* Changed - Disconnecting removes the API key the plugin created and the webhooks WonderTax Labs or earlier versions registered, and WonderTax Labs stops importing your orders
     7* Changed - A disconnect that cannot put your own tax settings back right away changes nothing and asks you to try again
     8* Changed - The connection status is read with a signed request
     9* Changed - Each tax line shows the name of its jurisdiction
     10* Changed - Each fee's name is sent with the checkout, so WonderTax Labs can classify it
     11* Changed - The settings page says whether WonderTax Labs answers your checkout tax
     12* Added - A notice when WonderTax Labs has not answered several checkout tax requests in a row (a refusal of one cart, such as an address, does not count); it clears once WonderTax Labs answers again, starts or stops answering your checkout tax, or the store is disconnected
     13* Added - Vertex, Quaderno and Stripe Tax are recognized as other tax engines, checked while WonderTax Labs answers your checkout tax too
     14* Removed - The unused app-started connection flow and the plugin's own webhook registration
     15* Security - Every settings action requires the Manage WooCommerce capability
     16
     172026-11-06 - version 1.4.0
     18* Changed - Settings sync with your WonderTax Labs account
     19* Changed - Checkout requests carry the line details Audita™ needs
     20* Removed - The manual tax setting
    221
    3222026-09-25 - version 1.3.7
    … …  
    6786
    68872025-05-07 - version 1.2.4
    69 * Update - Plugin title changed to "WonderTax Labs: Audita" throughout admin UI
    70 * Update - Menu item and page title updated to "WonderTax Labs: Audita"
     88* Update - Plugin title changed to "WonderTax Labs: Audita™" throughout admin UI
     89* Update - Menu item and page title updated to "WonderTax Labs: Audita™"
    7190
    72912025-05-07 - version 1.2.3
  • wondertax-labs-audita/tags/1.4.1/includes/class-wondertax-admin.php

    r3713774 r3814612  
    1010
    1111// Exit if accessed directly
    12 if (!defined('ABSPATH')) {
     12if ( ! defined( 'ABSPATH' ) ) {
    1313        exit;
    1414}
    … …  
    1717 * Admin settings class
    1818 */
    19 class WonderTax_Admin
    20 {
     19class WonderTax_Admin {
     20
    2121        /**
    2222         * Singleton instance
    … …  
    2727
    2828        /**
     29         * The option holding a connect in progress: the new credentials, webhook secret, install secret and API key id, kept
     30         * apart from the working connection until WonderTax Labs confirms it (confirm_pending_connection).
     31         */
     32        const PENDING_OPTION = 'wondertax_pending_connection';
     33
     34        /**
     35         * Seconds a connect in progress waits for its confirmation: the connect link's signature window.
     36         */
     37        const PENDING_TTL = HOUR_IN_SECONDS;
     38
     39        /**
     40         * Seconds the one-time credential token can be redeemed: WonderTax Labs redeems it as the browser lands, before anyone
     41         * signs in, so it needs only the redirect's moment, never the connect's whole hour.
     42         */
     43        const TOKEN_TTL = 15 * MINUTE_IN_SECONDS;
     44
     45        /**
     46         * The install secret of the connect in progress whose status read went unanswered in this request, else '': it is read
     47         * once per request, however many steps of a page load ask (confirm_pending_connection).
     48         *
     49         * @var string
     50         */
     51        private static $unconfirmed_secret = '';
     52
     53        /**
    2954         * Get singleton instance
    3055         *
    3156         * @return WonderTax_Admin
    3257         */
    33         public static function get_instance()
    34         {
    35                 if (null === self::$instance) {
     58        public static function get_instance() {
     59                if ( null === self::$instance ) {
    3660                        self::$instance = new self();
    3761                }
    … …  
    4266         * Constructor
    4367         */
    44         private function __construct()
    45         {
    46                 add_action('admin_menu', array($this, 'add_admin_menu'));
    47                 add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    48                 add_action('admin_init', array($this, 'handle_settings_actions'));
    49                 add_action('wp_ajax_wondertax_switch_mode', array($this, 'ajax_switch_mode'));
     68        private function __construct() {
     69                add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
     70                add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
     71                add_action( 'admin_init', array( $this, 'handle_settings_actions' ) );
     72                add_action( 'wp_ajax_wondertax_switch_mode', array( $this, 'ajax_switch_mode' ) );
    5073        }
    5174
    … …  
    5376         * Add admin menu
    5477         */
    55         public function add_admin_menu()
    56         {
     78        public function add_admin_menu() {
    5779                add_submenu_page(
    5880                        'woocommerce',
    59                         __('WonderTax Labs: Audita', 'wondertax-labs-audita'),
    60                         __('WonderTax Labs: Audita', 'wondertax-labs-audita'),
     81                        __( 'WonderTax Labs: Audita™', 'wondertax-labs-audita' ),
     82                        __( 'WonderTax Labs: Audita™', 'wondertax-labs-audita' ),
    6183                        'manage_woocommerce',
    6284                        'wondertax-labs-audita',
    63                         array($this, 'render_admin_page')
     85                        array( $this, 'render_admin_page' )
    6486                );
    6587        }
    … …  
    7092         * @param string $hook Current admin page hook.
    7193         */
    72         public function enqueue_admin_assets($hook)
    73         {
     94        public function enqueue_admin_assets( $hook ) {
    7495                // Only load on our admin page
    75                 if ('woocommerce_page_wondertax-labs-audita' !== $hook) {
     96                if ( 'woocommerce_page_wondertax-labs-audita' !== $hook ) {
    7697                        return;
    7798                }
    … …  
    87108                        'wondertax-admin',
    88109                        WONDERTAX_PLUGIN_URL . 'assets/js/admin.js',
    89                         array('jquery'),
     110                        array( 'jquery' ),
    90111                        WONDERTAX_VERSION,
    91112                        true
    92113                );
    93114
    94                 wp_localize_script('wondertax-admin', 'wondertaxAdmin', array(
    95                         'ajaxUrl' => admin_url('admin-ajax.php'),
    96                         'nonce' => wp_create_nonce('wondertax_switch_mode'),
    97                         'strings' => array(
    98                                 'switching' => __('Switching...', 'wondertax-labs-audita'),
    99                                 'switchToLive' => __('Switch to Live Mode', 'wondertax-labs-audita'),
    100                                 'switchToTest' => __('Switch to Test Mode', 'wondertax-labs-audita'),
    101                                 'error' => __('Failed to switch mode. Please try again.', 'wondertax-labs-audita'),
    102                         ),
    103                 ));
    104         }
    105 
    106         /**
    107          * Handle settings page actions
    108          */
    109         public function handle_settings_actions()
    110         {
     115                wp_localize_script(
     116                        'wondertax-admin',
     117                        'wondertaxAdmin',
     118                        array(
     119                                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
     120                                'nonce'   => wp_create_nonce( 'wondertax_switch_mode' ),
     121                                'strings' => array(
     122                                        'switching'    => __( 'Switching...', 'wondertax-labs-audita' ),
     123                                        'switchToLive' => __( 'Switch to Live Mode', 'wondertax-labs-audita' ),
     124                                        'switchToTest' => __( 'Switch to Test Mode', 'wondertax-labs-audita' ),
     125                                        'error'        => __( 'Failed to switch mode. Please try again.', 'wondertax-labs-audita' ),
     126                                ),
     127                        )
     128                );
     129        }
     130
     131        /**
     132         * Handle settings page actions. ⛔ Every action needs a store manager (`manage_woocommerce`): admin_init runs for any
     133         * signed-in user, before WordPress checks the page's own capability.
     134         */
     135        public function handle_settings_actions() {
    111136                // Check if we're on the settings page
    112                 if (!isset($_GET['page']) || 'wondertax-labs-audita' !== $_GET['page']) {
     137                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The page slug only routes; each action below checks its own nonce.
     138                if ( ! isset( $_GET['page'] ) || 'wondertax-labs-audita' !== $_GET['page'] ) {
    113139                        return;
    114140                }
    115 
    116                 // Handle successful connection return from WonderTax Labs
    117                 if (isset($_GET['connected']) && '1' === $_GET['connected']) {
    118                         // Mark as connected (credentials were stored before redirect)
    119                         update_option('wondertax_connected', true);
    120                         add_settings_error(
    121                                 'wondertax',
    122                                 'connected',
    123                                 __('Successfully connected to WonderTax Labs!', 'wondertax-labs-audita'),
    124                                 'success'
    125                         );
    126                 }
    127 
    128                 // Handle connect action
    129                 if (isset($_GET['action']) && 'connect' === $_GET['action']) {
    130                         // Check if this is from WonderTax Labs app (has state and callback_url)
    131                         // or from the WordPress "Connect" button (has nonce)
    132                         if (isset($_GET['state']) && isset($_GET['callback_url'])) {
    133                                 // WonderTax-initiated flow: store params and show confirmation UI
    134                                 // This prevents CSRF by requiring user to confirm with a WordPress nonce
    135                                 $this->handle_oauth_initiation();
    136                         } else {
    137                                 // WordPress-initiated flow: check nonce and do signed redirect
    138                                 check_admin_referer('wondertax_connect', 'wondertax_nonce');
    139                                 $this->handle_connect();
     141                if ( ! current_user_can( 'manage_woocommerce' ) ) {
     142                        return;
     143                }
     144
     145                // The return from WonderTax Labs after the store was bound. ⛔ The query is never trusted: the connect in progress is
     146                // promoted only when WonderTax Labs answers a status read signed with its new install secret.
     147                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- A return flag only; the signed status read decides.
     148                if ( isset( $_GET['connected'] ) && '1' === $_GET['connected'] ) {
     149                        $confirmed = self::confirm_pending_connection();
     150                        if ( true === $confirmed ) {
     151                                add_settings_error(
     152                                        'wondertax',
     153                                        'connected',
     154                                        __( 'Successfully connected to WonderTax Labs!', 'wondertax-labs-audita' ),
     155                                        'success'
     156                                );
     157                        } elseif ( false === $confirmed ) {
     158                                add_settings_error(
     159                                        'wondertax',
     160                                        'connect_unconfirmed',
     161                                        __( 'WonderTax Labs has not confirmed the connection yet. If you finished connecting in WonderTax Labs, reload this page in a minute; otherwise, click Connect again.', 'wondertax-labs-audita' ),
     162                                        'warning'
     163                                );
    140164                        }
    141165                }
    142166
    143                 // Handle confirmed OAuth connection (after user clicks confirm button with nonce)
    144                 if (isset($_POST['wondertax_confirm_oauth'])) {
    145                         check_admin_referer('wondertax_confirm_oauth', 'wondertax_nonce');
    146                         $this->handle_confirmed_oauth();
     167                // Handle connect action (the Connect button, nonce-protected)
     168                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- check_admin_referer verifies the nonce before anything runs.
     169                if ( isset( $_GET['action'] ) && 'connect' === $_GET['action'] ) {
     170                        check_admin_referer( 'wondertax_connect', 'wondertax_nonce' );
     171                        $this->handle_connect();
    147172                }
    148173
    149174                // Handle disconnect
    150                 if (isset($_POST['wondertax_disconnect']) && check_admin_referer('wondertax_disconnect', 'wondertax_nonce')) {
     175                if ( isset( $_POST['wondertax_disconnect'] ) && check_admin_referer( 'wondertax_disconnect', 'wondertax_nonce' ) ) {
    151176                        $this->handle_disconnect();
    152177                }
    153 
    154                 // Tax calculation toggle disabled - audit only mode
    155                 // if (isset($_POST['wondertax_toggle_tax']) && check_admin_referer('wondertax_toggle_tax', 'wondertax_nonce')) {
    156                 //      $this->handle_tax_toggle();
    157                 // }
    158         }
    159 
    160         /**
    161          * Handle connect action - generates credentials and redirects to WonderTax Labs
    162          * Uses secure token exchange: credentials stored locally, only token sent in URL
    163          */
    164         private function handle_connect()
    165         {
     178        }
     179
     180        /**
     181         * Handle connect action - generates the new connection's credentials and redirects to WonderTax Labs.
     182         * Uses secure token exchange: credentials stored locally, only a token sent in the URL.
     183         *
     184         * ⭐ The new credentials, webhook secret and install secret are kept as a connect IN PROGRESS (PENDING_OPTION): the
     185         * store's working connection — its options and its WooCommerce API key — is untouched until WonderTax Labs confirms the
     186         * new one, so a connect abandoned midway never breaks a working store.
     187         */
     188        private function handle_connect() {
    166189                try {
     190                        // A connect left unfinished before is discarded first (its API key row with it).
     191                        self::discard_pending_connection();
     192
    167193                        // Generate WooCommerce REST API credentials
    168194                        $credentials = $this->generate_api_credentials();
    169195
    170                         // Generate webhook secret
     196                        // Generate webhook secret and this connection's install secret
    171197                        $webhook_secret = $this->generate_webhook_secret();
    172 
    173                         // Store credentials locally (permanent storage)
    174                         update_option('wondertax_consumer_key', $credentials['consumer_key']);
    175                         update_option('wondertax_consumer_secret', $credentials['consumer_secret']);
    176                         update_option('wondertax_webhook_secret', $webhook_secret);
    177                         update_option('wondertax_site_url', get_site_url());
    178 
    179                         // Get admin email and store name for user identification
    180                         $admin_email = get_option('admin_email');
    181                         $store_name = get_bloginfo('name');
     198                        $install_secret = 'wtl_' . bin2hex( random_bytes( 32 ) );
     199                        $site_url       = get_site_url();
     200
     201                        update_option(
     202                                self::PENDING_OPTION,
     203                                array(
     204                                        'consumer_key'    => $credentials['consumer_key'],
     205                                        'consumer_secret' => $credentials['consumer_secret'],
     206                                        'api_key_id'      => $credentials['key_id'],
     207                                        'webhook_secret'  => $webhook_secret,
     208                                        'install_secret'  => $install_secret,
     209                                        'site_url'        => $site_url,
     210                                        'created'         => time(),
     211                                ),
     212                                false
     213                        );
     214
     215                        // ⭐ An unheard released ack is kept until this connect is CONFIRMED (`confirm_pending_connection` deletes it): an
     216                        // abandoned connect must not drop a disconnect WonderTax Labs has yet to hear, and until the new install secret is
     217                        // written the retry is signed with the old one, which can only retire the old installation.
     218
     219                        // The store's name, offered as the name of a new business. No email is sent: a link proves only that the site signed
     220                        // it, so WonderTax Labs never identifies or creates an account from it — the person signs in themselves.
     221                        $store_name = get_bloginfo( 'name' );
    182222
    183223                        // Generate a one-time token for credential exchange
    184                         $connect_token = bin2hex(random_bytes(32));
    185 
    186                         // Store credentials in a transient for token exchange (5 minute expiry)
    187                         // WonderTax Labs backend will call our REST API to fetch these
     224                        $connect_token = bin2hex( random_bytes( 32 ) );
     225
     226                        // Store credentials in a transient for the token exchange. WonderTax Labs backend calls our REST API to fetch
     227                        // these; one hour, the connect link's signature window.
    188228                        $credential_data = array(
    189                                 'site_url' => get_site_url(),
    190                                 'consumer_key' => $credentials['consumer_key'],
     229                                'site_url'        => $site_url,
     230                                'consumer_key'    => $credentials['consumer_key'],
    191231                                'consumer_secret' => $credentials['consumer_secret'],
    192                                 'webhook_secret' => $webhook_secret,
    193                                 'admin_email' => $admin_email,
    194                                 'store_name' => $store_name,
     232                                'webhook_secret'  => $webhook_secret,
     233                                'install_secret'  => $install_secret,
     234                                'store_name'      => $store_name,
    195235                        );
    196                         set_transient('wondertax_connect_' . $connect_token, $credential_data, 3600); // 1 hour to match HMAC window
    197 
    198                         // Build signed redirect URL (only token in URL, not credentials)
    199                         $redirect_url = $this->build_secure_connect_url($connect_token);
     236                        set_transient( 'wondertax_connect_' . $connect_token, $credential_data, self::TOKEN_TTL );
     237
     238                        // Build signed redirect URL (only token in URL, not credentials), signed with the new install secret
     239                        $redirect_url = $this->build_secure_connect_url( $connect_token, $site_url, $install_secret );
    200240
    201241                        // Add WonderTax backend to allowed redirect hosts for wp_safe_redirect
    202                         add_filter('allowed_redirect_hosts', array($this, 'allow_wondertax_redirect'));
     242                        add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wondertax_redirect' ) );
    203243
    204244                        // Redirect to WonderTax Labs connect endpoint (use wp_safe_redirect for security)
    205                         wp_safe_redirect($redirect_url);
     245                        wp_safe_redirect( $redirect_url );
    206246                        exit;
    207247
    208                 } catch (Exception $e) {
    209                         // Clean up failed connection
    210                         $this->cleanup_failed_connection();
     248                } catch ( Exception $e ) {
     249                        // Clean up the failed connect only: the working connection stays as it was
     250                        self::discard_pending_connection();
    211251
    212252                        // Show error
    … …  
    216256                                sprintf(
    217257                                        /* translators: %s: error message */
    218                                         __('Failed to connect: %s', 'wondertax-labs-audita'),
     258                                        __( 'Failed to connect: %s', 'wondertax-labs-audita' ),
    219259                                        $e->getMessage()
    220260                                ),
    … …  
    225265
    226266        /**
    227          * Handle OAuth initiation from WonderTax Labs app
    228          * This is used when an existing WonderTax user initiates connection from their dashboard.
    229          * Stores OAuth parameters and redirects to confirmation page to prevent CSRF attacks.
    230          */
    231         private function handle_oauth_initiation()
    232         {
    233                 // Verify user has permission to manage WooCommerce before processing OAuth
    234                 if (!current_user_can('manage_woocommerce')) {
    235                         add_settings_error(
    236                                 'wondertax',
    237                                 'permission_denied',
    238                                 __('You do not have permission to connect this store.', 'wondertax-labs-audita'),
    239                                 'error'
     267         * ⭐ PROMOTES A CONNECT IN PROGRESS once WonderTax Labs confirms it: a status read signed with the connect's NEW install
     268         * secret verifies only when WonderTax Labs bound the new connection (it holds that secret only then). Promoting makes
     269         * the new credentials and secrets the working ones, deletes the previous WooCommerce API key, and marks the store
     270         * connected. Asked on the return from WonderTax Labs, on the settings page and on the hourly sync, so a merchant who
     271         * never comes back to WordPress is still promoted. A connect older than PENDING_TTL is discarded. A connect whose read
     272         * went unanswered is not read again in the same request. Promoting deletes any released ack still waiting to be heard,
     273         * so it is never retried against the new installation.
     274         *
     275         * @return bool|null True when promoted, false when not confirmed (yet), null when no connect is in progress.
     276         */
     277        public static function confirm_pending_connection() {
     278                $pending = get_option( self::PENDING_OPTION, null );
     279                if ( ! is_array( $pending ) || empty( $pending['install_secret'] ) || empty( $pending['site_url'] ) ) {
     280                        return null;
     281                }
     282                if ( time() - (int) ( isset( $pending['created'] ) ? $pending['created'] : 0 ) > self::PENDING_TTL ) {
     283                        self::discard_pending_connection();
     284                        return null;
     285                }
     286                if ( (string) $pending['install_secret'] === self::$unconfirmed_secret ) {
     287                        return false;
     288                }
     289                $status = self::signed_status_read( (string) $pending['site_url'], (string) $pending['install_secret'] );
     290                if ( null === $status ) {
     291                        self::$unconfirmed_secret = (string) $pending['install_secret'];
     292                        return false;
     293                }
     294
     295                // Before the new install secret becomes the working one: a request cut short never leaves the ack to be signed with it.
     296                delete_option( WonderTax_Tax_Service::RELEASE_UNACKED_OPTION );
     297
     298                global $wpdb;
     299                $previous_key_id = (int) get_option( 'wondertax_api_key_id', 0 );
     300                $new_key_id      = (int) $pending['api_key_id'];
     301                if ( $previous_key_id && $previous_key_id !== $new_key_id ) {
     302                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, write operation
     303                        $wpdb->delete(
     304                                $wpdb->prefix . 'woocommerce_api_keys',
     305                                array( 'key_id' => $previous_key_id ),
     306                                array( '%d' )
    240307                        );
    241                         return;
    242                 }
    243 
    244                 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initial OAuth request from external service, user confirmation with nonce required before processing
    245                 $state = isset($_GET['state']) ? sanitize_text_field(wp_unslash($_GET['state'])) : '';
    246                 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initial OAuth request from external service, user confirmation with nonce required before processing
    247                 $callback_url = isset($_GET['callback_url']) ? esc_url_raw(wp_unslash($_GET['callback_url'])) : '';
    248 
    249                 if (empty($state) || empty($callback_url)) {
    250                         add_settings_error(
    251                                 'wondertax',
    252                                 'invalid_oauth_params',
    253                                 __('Invalid OAuth parameters. Please try again.', 'wondertax-labs-audita'),
    254                                 'error'
     308                }
     309                update_option( 'wondertax_consumer_key', $pending['consumer_key'] );
     310                update_option( 'wondertax_consumer_secret', $pending['consumer_secret'] );
     311                update_option( 'wondertax_webhook_secret', $pending['webhook_secret'] );
     312                update_option( 'wondertax_site_url', $pending['site_url'] );
     313                update_option( 'wondertax_install_secret', $pending['install_secret'] );
     314                update_option( 'wondertax_api_key_id', $new_key_id );
     315                update_option( 'wondertax_connected', true );
     316                delete_option( self::PENDING_OPTION );
     317                return true;
     318        }
     319
     320        /**
     321         * Discards a connect in progress: its API key row (never the working one) and its record.
     322         */
     323        public static function discard_pending_connection() {
     324                $pending = get_option( self::PENDING_OPTION, null );
     325                if ( is_array( $pending ) && ! empty( $pending['api_key_id'] )
     326                        && (int) $pending['api_key_id'] !== (int) get_option( 'wondertax_api_key_id', 0 ) ) {
     327                        global $wpdb;
     328                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, cleanup operation
     329                        $wpdb->delete(
     330                                $wpdb->prefix . 'woocommerce_api_keys',
     331                                array( 'key_id' => (int) $pending['api_key_id'] ),
     332                                array( '%d' )
    255333                        );
    256                         return;
    257                 }
    258 
    259                 // Validate callback_url against allowed backend origin
    260                 if (!$this->is_allowed_backend_url($callback_url)) {
    261                         add_settings_error(
    262                                 'wondertax',
    263                                 'invalid_callback_url',
    264                                 __('Invalid callback URL. The URL does not match the expected WonderTax Labs backend.', 'wondertax-labs-audita'),
    265                                 'error'
    266                         );
    267                         return;
    268                 }
    269 
    270                 // Store OAuth parameters in a user-specific transient for confirmation
    271                 // This requires the user to explicitly confirm the connection with a nonce-protected form
    272                 $user_id = get_current_user_id();
    273                 $oauth_data = array(
    274                         'state' => $state,
    275                         'callback_url' => $callback_url,
    276                         'timestamp' => time(),
    277                 );
    278                 set_transient('wondertax_pending_oauth_' . $user_id, $oauth_data, 600); // 10 minute expiry
    279 
    280                 // Redirect to settings page with confirmation flag
    281                 // The render_admin_page() method will show a confirmation form
    282                 wp_safe_redirect(
     334                }
     335                delete_option( self::PENDING_OPTION );
     336        }
     337
     338        /**
     339         * ⭐ A STATUS READ SIGNED WITH AN INSTALL SECRET: `site_url|status|timestamp|nonce`, HMAC-SHA256 hex, as the mode switch
     340         * signs. WonderTax Labs answers the full status only to a good signature for a connected site.
     341         *
     342         * @param string $site_url       The site URL the connection is bound under.
     343         * @param string $install_secret The install secret to sign with.
     344         * @return array|null The status, or null when it was not answered.
     345         */
     346        public static function signed_status_read( $site_url, $install_secret ) {
     347                if ( '' === $site_url || '' === $install_secret ) {
     348                        return null;
     349                }
     350                try {
     351                        $nonce = bin2hex( random_bytes( 16 ) );
     352                } catch ( Exception $e ) {
     353                        return null;
     354                }
     355                $timestamp = time();
     356                $hmac      = hash_hmac( 'sha256', $site_url . '|status|' . $timestamp . '|' . $nonce, $install_secret );
     357                $response  = wp_remote_get(
    283358                        add_query_arg(
    284359                                array(
    285                                         'page' => 'wondertax-labs-audita',
    286                                         'confirm_oauth' => '1',
     360                                        'site_url'  => rawurlencode( $site_url ),
     361                                        'timestamp' => $timestamp,
     362                                        'nonce'     => $nonce,
     363                                        'hmac'      => $hmac,
    287364                                ),
    288                                 admin_url('admin.php')
    289                         )
     365                                WONDERTAX_BACKEND_URL . '/api/integrations/woocommerce/status'
     366                        ),
     367                        array( 'timeout' => 5 )
    290368                );
    291                 exit;
    292         }
    293 
    294         /**
    295          * Handle confirmed OAuth connection after user clicks confirm button.
    296          * This method is called after nonce verification in handle_settings_actions().
    297          */
    298         private function handle_confirmed_oauth()
    299         {
    300                 // Verify user has permission
    301                 if (!current_user_can('manage_woocommerce')) {
    302                         add_settings_error(
    303                                 'wondertax',
    304                                 'permission_denied',
    305                                 __('You do not have permission to connect this store.', 'wondertax-labs-audita'),
    306                                 'error'
    307                         );
    308                         return;
    309                 }
    310 
    311                 // Retrieve stored OAuth parameters
    312                 $user_id = get_current_user_id();
    313                 $oauth_data = get_transient('wondertax_pending_oauth_' . $user_id);
    314 
    315                 if (empty($oauth_data) || empty($oauth_data['state']) || empty($oauth_data['callback_url'])) {
    316                         add_settings_error(
    317                                 'wondertax',
    318                                 'oauth_expired',
    319                                 __('OAuth session expired. Please try connecting again from WonderTax Labs.', 'wondertax-labs-audita'),
    320                                 'error'
    321                         );
    322                         return;
    323                 }
    324 
    325                 // Delete the transient immediately (one-time use)
    326                 delete_transient('wondertax_pending_oauth_' . $user_id);
    327 
    328                 // Re-validate callback_url (defense in depth)
    329                 if (!$this->is_allowed_backend_url($oauth_data['callback_url'])) {
    330                         add_settings_error(
    331                                 'wondertax',
    332                                 'invalid_callback_url',
    333                                 __('Invalid callback URL. The URL does not match the expected WonderTax Labs backend.', 'wondertax-labs-audita'),
    334                                 'error'
    335                         );
    336                         return;
    337                 }
    338 
    339                 // Store validated OAuth data in a new transient for the OAuth handler
    340                 // Use a random token to prevent parameter tampering
    341                 try {
    342                         $oauth_token = bin2hex(random_bytes(16));
    343                 } catch (Exception $e) {
    344                         add_settings_error(
    345                                 'wondertax',
    346                                 'token_generation_failed',
    347                                 __('Failed to start OAuth connection. Please try again.', 'wondertax-labs-audita'),
    348                                 'error'
    349                         );
    350                         return;
    351                 }
    352                 set_transient('wondertax_oauth_verified_' . $oauth_token, $oauth_data, 300); // 5 minute expiry
    353 
    354                 // Redirect to OAuth handler with the verification token
    355                 wp_safe_redirect(
    356                         add_query_arg(
    357                                 array(
    358                                         'action' => 'wondertax_oauth',
    359                                         'oauth_token' => $oauth_token,
    360                                 ),
    361                                 admin_url('admin-post.php')
    362                         )
    363                 );
    364                 exit;
    365         }
    366 
    367         /**
    368          * Check if a URL matches the allowed backend origin
    369          *
    370          * @param string $url URL to validate
    371          * @return bool
    372          */
    373         private function is_allowed_backend_url($url)
    374         {
    375                 $parsed = wp_parse_url($url);
    376                 if (!$parsed || !isset($parsed['host'], $parsed['scheme'])) {
    377                         return false;
    378                 }
    379 
    380                 $allowed = $this->get_allowed_backend_origin();
    381                 $url_port = isset($parsed['port']) ? (int) $parsed['port'] : null;
    382                 return $parsed['host'] === $allowed['host']
    383                         && $parsed['scheme'] === $allowed['scheme']
    384                         && $url_port === $allowed['port'];
    385         }
    386 
    387         /**
    388          * Get the allowed backend origin
    389          *
    390          * @return array{host: string, scheme: string, port: int|null}
    391          */
    392         private function get_allowed_backend_origin()
    393         {
    394                 return array(
    395                         'host' => 'app.wonder.tax',
    396                         'scheme' => 'https',
    397                         'port' => null,
    398                 );
     369                if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
     370                        return null;
     371                }
     372                $data = json_decode( wp_remote_retrieve_body( $response ), true );
     373                return is_array( $data ) && ! empty( $data['success'] ) ? $data : null;
    399374        }
    400375
    … …  
    403378         * Only the token is sent in the URL - credentials are exchanged server-to-server.
    404379         *
    405          * @param string $connect_token One-time token for credential exchange
     380         * @param string $connect_token  One-time token for credential exchange
     381         * @param string $site_url       The site URL the connection is bound under.
     382         * @param string $install_secret The new connection's install secret, which signs the link.
    406383         * @return string Signed URL
    407384         */
    408         private function build_secure_connect_url($connect_token)
    409         {
     385        private function build_secure_connect_url( $connect_token, $site_url, $install_secret ) {
    410386                $timestamp = time();
    411                 $site_url = get_site_url();
    412387
    413388                // Parameters to include in URL (no credentials!)
    414389                $params = array(
    415                         'token' => $connect_token,
    416                         'site_url' => $site_url,
     390                        'token'     => $connect_token,
     391                        'site_url'  => $site_url,
    417392                        'timestamp' => $timestamp,
    418393                );
    … …  
    421396                $message = $connect_token . '|' . $site_url . '|' . $timestamp;
    422397
    423                 // Sign with per-install secret
    424                 $hmac = hash_hmac('sha256', $message, wondertax_get_install_secret());
     398                // Sign with the new connection's install secret (the exchange serves it)
     399                $hmac           = hash_hmac( 'sha256', $message, $install_secret );
    425400                $params['hmac'] = $hmac;
    426401
    427402                // Build URL
    428                 $backend_url = $this->get_backend_url();
    429                 return add_query_arg($params, $backend_url . '/api/integrations/woocommerce/connect');
     403                $backend_url = WONDERTAX_BACKEND_URL;
     404                return add_query_arg( $params, $backend_url . '/api/integrations/woocommerce/connect' );
    430405        }
    431406
    … …  
    436411         * @throws Exception If credential generation fails
    437412         */
    438         private function generate_api_credentials()
    439         {
     413        private function generate_api_credentials() {
    440414                global $wpdb;
    441415
    442416                // Verify WooCommerce functions are available
    443                 if (!function_exists('wc_rand_hash') || !function_exists('wc_api_hash')) {
    444                         throw new Exception('WooCommerce API functions not available. Please ensure WooCommerce is active.');
     417                if ( ! function_exists( 'wc_rand_hash' ) || ! function_exists( 'wc_api_hash' ) ) {
     418                        throw new Exception( 'WooCommerce API functions not available. Please ensure WooCommerce is active.' );
    445419                }
    446420
    447421                // Get current user
    448422                $user = wp_get_current_user();
    449                 if (!$user || !$user->ID) {
    450                         throw new Exception('No user logged in');
     423                if ( ! $user || ! $user->ID ) {
     424                        throw new Exception( 'No user logged in' );
    451425                }
    452426
    453427                // Verify user has manage_woocommerce capability
    454                 if (!current_user_can('manage_woocommerce')) {
    455                         throw new Exception('User does not have permission to manage WooCommerce');
     428                if ( ! current_user_can( 'manage_woocommerce' ) ) {
     429                        throw new Exception( 'User does not have permission to manage WooCommerce' );
    456430                }
    457431
    458432                // Check if the API keys table exists (must check before any delete/insert operations)
    459                 $table_name = $wpdb->prefix . 'woocommerce_api_keys';
    460                 $table_name_like = $wpdb->esc_like($table_name);
     433                $table_name      = $wpdb->prefix . 'woocommerce_api_keys';
     434                $table_name_like = $wpdb->esc_like( $table_name );
    461435                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Schema check, not cacheable
    462                 $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name_like));
    463                 if (!$table_exists) {
    464                         throw new Exception('WooCommerce API keys table not found. Please ensure WooCommerce REST API is enabled.');
     436                $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name_like ) );
     437                if ( ! $table_exists ) {
     438                        throw new Exception( 'WooCommerce API keys table not found. Please ensure WooCommerce REST API is enabled.' );
    465439                }
    466440
    467441                // Generate random credentials
    468                 $consumer_key = 'ck_' . wc_rand_hash();
     442                $consumer_key    = 'ck_' . wc_rand_hash();
    469443                $consumer_secret = 'cs_' . wc_rand_hash();
    470444
    471                 // Delete any existing WonderTax Labs API keys
    472                 // First, try to delete by tracked key ID
    473                 $existing_key_id = get_option('wondertax_api_key_id');
    474                 if ($existing_key_id) {
    475                         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, write operation
    476                         $wpdb->delete(
    477                                 $table_name,
    478                                 array('key_id' => $existing_key_id),
    479                                 array('%d')
    480                         );
    481                         delete_option('wondertax_api_key_id');
    482                 }
    483 
    484                 // Also delete any orphaned keys with the same description (in case option was lost)
    485                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, write operation
    486                 $wpdb->delete(
    487                         $table_name,
    488                         array(
    489                                 'user_id' => $user->ID,
    490                                 'description' => 'WonderTax Labs Connector'
    491                         ),
    492                         array('%d', '%s')
    493                 );
     445                // ⛔ The working connection's key is never deleted here: it is replaced only once WonderTax Labs confirms the new
     446                // connection (confirm_pending_connection), so a connect abandoned midway leaves the store working.
    494447
    495448                // Insert into woocommerce_api_keys table
    … …  
    498451                        $table_name,
    499452                        array(
    500                                 'user_id' => $user->ID,
    501                                 'description' => 'WonderTax Labs Connector',
    502                                 'permissions' => 'read_write',
    503                                 'consumer_key' => wc_api_hash($consumer_key),
     453                                'user_id'         => $user->ID,
     454                                'description'     => 'WonderTax Labs Connector',
     455                                'permissions'     => 'read_write',
     456                                'consumer_key'    => wc_api_hash( $consumer_key ),
    504457                                'consumer_secret' => $consumer_secret,
    505                                 'truncated_key' => substr($consumer_key, -7),
     458                                'truncated_key'   => substr( $consumer_key, -7 ),
    506459                        ),
    507                         array('%d', '%s', '%s', '%s', '%s', '%s')
     460                        array( '%d', '%s', '%s', '%s', '%s', '%s' )
    508461                );
    509462
    510                 if (false === $result) {
    511                         throw new Exception('Failed to create API credentials.');
    512                 }
    513 
    514                 // Store the key ID for later cleanup
    515                 update_option('wondertax_api_key_id', $wpdb->insert_id);
     463                if ( false === $result ) {
     464                        throw new Exception( 'Failed to create API credentials.' );
     465                }
    516466
    517467                return array(
    518                         'consumer_key' => $consumer_key,
     468                        'consumer_key'    => $consumer_key,
    519469                        'consumer_secret' => $consumer_secret,
     470                        'key_id'          => (int) $wpdb->insert_id,
    520471                );
    521472        }
    … …  
    526477         * @return string
    527478         */
    528         private function generate_webhook_secret()
    529         {
    530                 return 'whsec_' . bin2hex(random_bytes(32));
    531         }
    532 
    533         /**
    534          * Get the backend URL for WonderTax Labs
    535          *
    536          * @return string
    537          */
    538         private function get_backend_url()
    539         {
    540                 return 'https://app.wonder.tax';
     479        private function generate_webhook_secret() {
     480                return 'whsec_' . bin2hex( random_bytes( 32 ) );
    541481        }
    542482
    … …  
    547487         * @return array Modified allowed hosts.
    548488         */
    549         public function allow_wondertax_redirect($hosts)
    550         {
    551                 $backend_url = $this->get_backend_url();
    552                 $parsed = wp_parse_url($backend_url);
    553                 if (!empty($parsed['host'])) {
     489        public function allow_wondertax_redirect( $hosts ) {
     490                $backend_url = WONDERTAX_BACKEND_URL;
     491                $parsed      = wp_parse_url( $backend_url );
     492                if ( ! empty( $parsed['host'] ) ) {
    554493                        $hosts[] = $parsed['host'];
    555494                }
    … …  
    558497
    559498        /**
    560          * Clean up failed connection
    561          */
    562         private function cleanup_failed_connection()
    563         {
    564                 global $wpdb;
    565 
    566                 // Delete API key if created
    567                 $key_id = get_option('wondertax_api_key_id');
    568                 if ($key_id) {
     499         * Deletes the order webhooks WonderTax Labs registered on this store: those delivering to its order routes on
     500         * WONDERTAX_BACKEND_URL's origin. Every other webhook is the merchant's and is never touched (📗 integration-import ·
     501         * I28).
     502         */
     503        private static function delete_our_webhooks() {
     504                if ( ! class_exists( 'WC_Webhook' ) || ! class_exists( 'WC_Data_Store' ) ) {
     505                        return;
     506                }
     507                $ours = self::url_origin( WONDERTAX_BACKEND_URL );
     508                if ( '' === $ours ) {
     509                        return;
     510                }
     511                $ids = WC_Data_Store::load( 'webhook' )->search_webhooks( array( 'limit' => -1 ) );
     512                foreach ( (array) $ids as $id ) {
     513                        $webhook = new WC_Webhook( $id );
     514                        $url     = (string) $webhook->get_delivery_url();
     515                        $path    = untrailingslashit( (string) wp_parse_url( $url, PHP_URL_PATH ) );
     516                        // Our order routes (and their aliases): a match, never a call — so it is a pattern, not a path.
     517                        $route   = 1 === preg_match( '#^/api/(integrations/)?woocommerce/webhooks/[a-z-]+$#', $path );
     518                        if ( $webhook->get_id() && $route && self::url_origin( $url ) === $ours ) {
     519                                $webhook->delete( true );
     520                        }
     521                }
     522        }
     523
     524        /**
     525         * A URL's origin (scheme, host and any port), lowercased; '' when it has no host.
     526         *
     527         * @param string $url The URL.
     528         * @return string
     529         */
     530        private static function url_origin( $url ) {
     531                $parts = wp_parse_url( $url );
     532                if ( empty( $parts['host'] ) ) {
     533                        return '';
     534                }
     535                $port = isset( $parts['port'] ) ? ':' . $parts['port'] : '';
     536                return strtolower( ( $parts['scheme'] ?? 'https' ) . '://' . $parts['host'] . $port );
     537        }
     538
     539        /**
     540         * Handle store disconnect. ⛔ A store still held is never disconnected: when its own tax setting cannot be put back (the
     541         * lock stayed busy), nothing is deleted and the store manager is asked to try again.
     542         */
     543        private function handle_disconnect() {
     544                // A disconnected store answers no checkout through WonderTax Labs, so its own tax setting is put back first, and
     545                // WonderTax Labs is told while the store can still sign (before its connection options are deleted): it then stops
     546                // importing the store's orders and removes its webhooks.
     547                if ( ! WonderTax_Tax_Service::give_back( 'disconnected' ) ) {
     548                        add_settings_error(
     549                                'wondertax',
     550                                'disconnect_busy',
     551                                __( 'Your store was not disconnected: your own tax settings could not be put back just now, because another request was changing them. Please try again in a moment.', 'wondertax-labs-audita' ),
     552                                'error'
     553                        );
     554                        return;
     555                }
     556                self::discard_pending_connection();
     557                WonderTax_Tax_Service::clear_door_failures();
     558
     559                // The order webhooks earlier versions of the plugin registered are deleted, as uninstall deletes them.
     560                $webhook_ids = get_option( 'wondertax_webhook_ids', array() );
     561                if ( ! empty( $webhook_ids ) && is_array( $webhook_ids ) && class_exists( 'WC_Webhook' ) ) {
     562                        foreach ( $webhook_ids as $webhook_id ) {
     563                                $webhook = new WC_Webhook( $webhook_id );
     564                                if ( $webhook->get_id() ) {
     565                                        $webhook->delete( true );
     566                                }
     567                        }
     568                }
     569                delete_option( 'wondertax_webhook_ids' );
     570                // And the ones WonderTax Labs registered, here and now: its own cleanup reads the store with the key removed next,
     571                // and may run after it is gone.
     572                self::delete_our_webhooks();
     573
     574                // The WooCommerce API key WonderTax Labs read the store with is removed, so nothing can read it any more.
     575                $key_id = (int) get_option( 'wondertax_api_key_id', 0 );
     576                if ( $key_id ) {
     577                        global $wpdb;
    569578                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, cleanup operation
    570579                        $wpdb->delete(
    571580                                $wpdb->prefix . 'woocommerce_api_keys',
    572                                 array('key_id' => $key_id),
    573                                 array('%d')
     581                                array( 'key_id' => $key_id ),
     582                                array( '%d' )
    574583                        );
    575584                }
    576585
    577                 // Clean up options
    578                 delete_option('wondertax_consumer_key');
    579                 delete_option('wondertax_consumer_secret');
    580                 delete_option('wondertax_webhook_secret');
    581                 delete_option('wondertax_site_url');
    582                 delete_option('wondertax_api_key_id');
    583         }
    584 
    585         /**
    586          * Handle store disconnect
    587          */
    588         private function handle_disconnect()
    589         {
    590                 delete_option('wondertax_connected');
    591                 delete_option('wondertax_consumer_key');
    592                 delete_option('wondertax_consumer_secret');
    593                 delete_option('wondertax_webhook_secret');
    594                 delete_option('wondertax_site_url');
    595                 delete_option('wondertax_tax_calculation_enabled');
     586                delete_option( 'wondertax_connected' );
     587                delete_option( 'wondertax_consumer_key' );
     588                delete_option( 'wondertax_consumer_secret' );
     589                delete_option( 'wondertax_webhook_secret' );
     590                delete_option( 'wondertax_site_url' );
     591                delete_option( 'wondertax_api_key_id' );
     592                delete_option( 'wondertax_tax_calculation_enabled' );
    596593
    597594                add_settings_error(
    598595                        'wondertax',
    599596                        'disconnected',
    600                         __('Successfully disconnected from WonderTax Labs.', 'wondertax-labs-audita'),
     597                        __( 'Successfully disconnected from WonderTax Labs.', 'wondertax-labs-audita' ),
    601598                        'success'
    602599                );
    … …  
    604601
    605602        /**
    606          * Handle tax calculation toggle
    607          */
    608         private function handle_tax_toggle()
    609         {
    610                 // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in handle_settings_actions() before calling this method
    611                 $enabled = isset($_POST['tax_calculation_enabled']) ? true : false;
    612                 update_option('wondertax_tax_calculation_enabled', $enabled);
    613 
    614                 add_settings_error(
    615                         'wondertax',
    616                         'tax_toggled',
    617                         $enabled
    618                                 ? __('Real-time tax calculation enabled.', 'wondertax-labs-audita')
    619                                 : __('Real-time tax calculation disabled.', 'wondertax-labs-audita'),
    620                         'success'
    621                 );
    622         }
    623 
    624         /**
    625603         * Check if store is connected
    626604         *
    627605         * @return bool
    628606         */
    629         private function is_connected()
    630         {
    631                 return (bool) get_option('wondertax_connected', false);
     607        private function is_connected() {
     608                return (bool) get_option( 'wondertax_connected', false );
    632609        }
    633610
    … …  
    638615         * @return string|false Signed dashboard URL, or false on error
    639616         */
    640         private function build_authenticated_dashboard_url()
    641         {
     617        private function build_authenticated_dashboard_url() {
    642618                try {
    643619                        $timestamp = time();
    644                         $site_url = get_option('wondertax_site_url', get_site_url());
    645                         $nonce = bin2hex(random_bytes(16));
     620                        $site_url  = get_option( 'wondertax_site_url', get_site_url() );
     621                        $nonce     = bin2hex( random_bytes( 16 ) );
    646622
    647623                        // Build message for HMAC: site_url|timestamp|nonce
    … …  
    649625
    650626                        // Sign with per-install secret
    651                         $hmac = hash_hmac('sha256', $message, wondertax_get_install_secret());
     627                        $hmac = hash_hmac( 'sha256', $message, wondertax_get_install_secret() );
    652628
    653629                        // Build URL parameters
    654630                        $params = array(
    655                                 'site_url' => $site_url,
     631                                'site_url'  => $site_url,
    656632                                'timestamp' => $timestamp,
    657                                 'nonce' => $nonce,
    658                                 'hmac' => $hmac,
     633                                'nonce'     => $nonce,
     634                                'hmac'      => $hmac,
    659635                        );
    660636
    661                         $backend_url = $this->get_backend_url();
    662                         return add_query_arg($params, $backend_url . '/api/integrations/woocommerce/open');
    663                 } catch (Exception $e) {
     637                        $backend_url = WONDERTAX_BACKEND_URL;
     638                        return add_query_arg( $params, $backend_url . '/api/integrations/woocommerce/open' );
     639                } catch ( Exception $e ) {
    664640                        return false;
    665641                }
    … …  
    671647         * @return array|null
    672648         */
    673         private function get_api_key_status()
    674         {
    675                 $site_url = get_option('wondertax_site_url', '');
    676                 if (empty($site_url)) {
     649        private function get_api_key_status() {
     650                $site_url = get_option( 'wondertax_site_url', '' );
     651                if ( empty( $site_url ) ) {
    677652                        return null;
    678653                }
    679654
    680                 // Try to fetch status from backend
    681                 $backend_url = $this->get_backend_url();
    682                 $request_args = array('timeout' => 10);
    683                 $response = wp_remote_get(
    684                         add_query_arg('site_url', $site_url, $backend_url . '/api/integrations/woocommerce/status'),
    685                         $request_args
    686                 );
    687 
    688                 if (is_wp_error($response)) {
    689                         return null;
    690                 }
    691 
    692                 $body = wp_remote_retrieve_body($response);
    693                 $data = json_decode($body, true);
    694 
    695                 if (isset($data['success']) && $data['success']) {
     655                // A status read signed with the store's install secret (an unsigned read is answered with nothing about the store).
     656                $data = self::signed_status_read( $site_url, wondertax_get_install_secret() );
     657
     658                if ( null !== $data ) {
     659                        // Reads the tax service WonderTax Labs asks for from a signed report; the hourly sync does this too.
     660                        WonderTax_Tax_Service::sync();
    696661                        return $data;
    697662                }
    … …  
    703668         * Handle AJAX mode switch request
    704669         */
    705         public function ajax_switch_mode()
    706         {
     670        public function ajax_switch_mode() {
    707671                // Verify nonce
    708                 if (!check_ajax_referer('wondertax_switch_mode', 'nonce', false)) {
    709                         wp_send_json_error(array('message' => __('Security check failed.', 'wondertax-labs-audita')));
     672                if ( ! check_ajax_referer( 'wondertax_switch_mode', 'nonce', false ) ) {
     673                        wp_send_json_error( array( 'message' => __( 'Security check failed.', 'wondertax-labs-audita' ) ) );
    710674                }
    711675
    712676                // Verify user capabilities
    713                 if (!current_user_can('manage_woocommerce')) {
    714                         wp_send_json_error(array('message' => __('You do not have permission to perform this action.', 'wondertax-labs-audita')));
    715                 }
    716 
    717                 $mode = isset($_POST['mode']) ? sanitize_text_field(wp_unslash($_POST['mode'])) : '';
    718                 if (!in_array($mode, array('live', 'test'), true)) {
    719                         wp_send_json_error(array('message' => __('Invalid mode specified.', 'wondertax-labs-audita')));
     677                if ( ! current_user_can( 'manage_woocommerce' ) ) {
     678                        wp_send_json_error( array( 'message' => __( 'You do not have permission to perform this action.', 'wondertax-labs-audita' ) ) );
     679                }
     680
     681                $mode = isset( $_POST['mode'] ) ? sanitize_text_field( wp_unslash( $_POST['mode'] ) ) : '';
     682                if ( ! in_array( $mode, array( 'live', 'test' ), true ) ) {
     683                        wp_send_json_error( array( 'message' => __( 'Invalid mode specified.', 'wondertax-labs-audita' ) ) );
    720684                }
    721685
    722686                // Get site URL
    723                 $site_url = get_option('wondertax_site_url', get_site_url());
     687                $site_url  = get_option( 'wondertax_site_url', get_site_url() );
    724688                $timestamp = time();
    725689
    726690                try {
    727                         $nonce = bin2hex(random_bytes(16));
    728                 } catch (Exception $e) {
    729                         wp_send_json_error(array('message' => __('Failed to generate request nonce.', 'wondertax-labs-audita')));
     691                        $nonce = bin2hex( random_bytes( 16 ) );
     692                } catch ( Exception $e ) {
     693                        wp_send_json_error( array( 'message' => __( 'Failed to generate request nonce.', 'wondertax-labs-audita' ) ) );
    730694                }
    731695                // Build message for HMAC: site_url|mode|timestamp|nonce
    732696                $message = $site_url . '|' . $mode . '|' . $timestamp . '|' . $nonce;
    733                 $hmac = hash_hmac('sha256', $message, wondertax_get_install_secret());
     697                $hmac    = hash_hmac( 'sha256', $message, wondertax_get_install_secret() );
    734698
    735699                // Call the mode switch endpoint
    736                 $backend_url = $this->get_backend_url();
    737                 $headers = array('Content-Type' => 'application/json');
     700                $backend_url = WONDERTAX_BACKEND_URL;
     701                $headers     = array( 'Content-Type' => 'application/json' );
    738702
    739703                $response = wp_remote_post(
    … …  
    742706                                'timeout' => 30,
    743707                                'headers' => $headers,
    744                                 'body' => wp_json_encode(array(
    745                                         'site_url' => $site_url,
    746                                         'mode' => $mode,
    747                                         'timestamp' => $timestamp,
    748                                         'nonce' => $nonce,
    749                                         'hmac' => $hmac,
    750                                 )),
     708                                'body'    => wp_json_encode(
     709                                        array(
     710                                                'site_url'  => $site_url,
     711                                                'mode'      => $mode,
     712                                                'timestamp' => $timestamp,
     713                                                'nonce'     => $nonce,
     714                                                'hmac'      => $hmac,
     715                                        )
     716                                ),
    751717                        )
    752718                );
    753719
    754                 if (is_wp_error($response)) {
    755                         wp_send_json_error(array('message' => $response->get_error_message()));
    756                 }
    757 
    758                 $body = json_decode(wp_remote_retrieve_body($response), true);
    759                 $status_code = wp_remote_retrieve_response_code($response);
    760 
    761                 if ($status_code !== 200 || empty($body['success'])) {
    762                         $error_message = isset($body['message']) ? $body['message'] : __('Unknown error occurred.', 'wondertax-labs-audita');
    763                         wp_send_json_error(array('message' => $error_message));
    764                 }
    765 
    766                 wp_send_json_success(array(
    767                         'mode' => $mode,
    768                         'message' => $body['message'],
    769                 ));
     720                if ( is_wp_error( $response ) ) {
     721                        wp_send_json_error( array( 'message' => $response->get_error_message() ) );
     722                }
     723
     724                $body        = json_decode( wp_remote_retrieve_body( $response ), true );
     725                $status_code = wp_remote_retrieve_response_code( $response );
     726
     727                if ( $status_code !== 200 || empty( $body['success'] ) ) {
     728                        $error_message = isset( $body['message'] ) ? $body['message'] : __( 'Unknown error occurred.', 'wondertax-labs-audita' );
     729                        wp_send_json_error( array( 'message' => $error_message ) );
     730                }
     731
     732                wp_send_json_success(
     733                        array(
     734                                'mode'    => $mode,
     735                                'message' => $body['message'],
     736                        )
     737                );
    770738        }
    771739
    … …  
    775743         * @param array $status_data Status data from the API
    776744         */
    777         private function render_mode_selector($status_data)
    778         {
    779                 if (empty($status_data['dualKeyMode'])) {
     745        private function render_mode_selector( $status_data ) {
     746                if ( empty( $status_data['dualKeyMode'] ) ) {
    780747                        return;
    781748                }
    782749
    783                 $active_mode = isset($status_data['activeMode']) ? $status_data['activeMode'] : 'live';
    784                 $is_live = ($active_mode === 'live');
     750                $active_mode = isset( $status_data['activeMode'] ) ? $status_data['activeMode'] : 'live';
     751                $is_live     = ( $active_mode === 'live' );
    785752                ?>
    786753                <div class="wondertax-mode-selector">
    787                         <h3><?php esc_html_e('Transaction Mode', 'wondertax-labs-audita'); ?></h3>
     754                        <h3><?php esc_html_e( 'Transaction Mode', 'wondertax-labs-audita' ); ?></h3>
    788755                        <p class="wondertax-help-text">
    789                                 <?php esc_html_e('Choose how transactions from this store are recorded in WonderTax Labs.', 'wondertax-labs-audita'); ?>
     756                                <?php esc_html_e( 'Choose how transactions from this store are recorded in WonderTax Labs.', 'wondertax-labs-audita' ); ?>
    790757                        </p>
    791758
    … …  
    796763                                                name="wondertax_mode"
    797764                                                value="live"
    798                                                 <?php checked($is_live); ?>
     765                                                <?php checked( $is_live ); ?>
    799766                                                class="wondertax-mode-radio"
    800767                                        />
    801768                                        <div class="wondertax-mode-content">
    802769                                                <div class="wondertax-mode-header">
    803                                                         <span class="wondertax-mode-label"><?php esc_html_e('Live Mode', 'wondertax-labs-audita'); ?></span>
     770                                                        <span class="wondertax-mode-label"><?php esc_html_e( 'Live Mode', 'wondertax-labs-audita' ); ?></span>
    804771                                                        <span class="wondertax-badge wondertax-badge-success">
    805772                                                                <span class="dashicons dashicons-yes"></span>
    806                                                                 <?php esc_html_e('Production', 'wondertax-labs-audita'); ?>
     773                                                                <?php esc_html_e( 'Production', 'wondertax-labs-audita' ); ?>
    807774                                                        </span>
    808775                                                </div>
    809776                                                <p class="wondertax-mode-description">
    810                                                         <?php esc_html_e('Transactions are recorded as production data and count toward your tax compliance reports.', 'wondertax-labs-audita'); ?>
     777                                                        <?php esc_html_e( 'Transactions are recorded as production data and count toward your tax compliance reports.', 'wondertax-labs-audita' ); ?>
    811778                                                </p>
    812779                                        </div>
    813780                                </label>
    814781
    815                                 <label class="wondertax-mode-option <?php echo !$is_live ? 'wondertax-mode-active' : ''; ?>">
     782                                <label class="wondertax-mode-option <?php echo ! $is_live ? 'wondertax-mode-active' : ''; ?>">
    816783                                        <input
    817784                                                type="radio"
    818785                                                name="wondertax_mode"
    819786                                                value="test"
    820                                                 <?php checked(!$is_live); ?>
     787                                                <?php checked( ! $is_live ); ?>
    821788                                                class="wondertax-mode-radio"
    822789                                        />
    823790                                        <div class="wondertax-mode-content">
    824791                                                <div class="wondertax-mode-header">
    825                                                         <span class="wondertax-mode-label"><?php esc_html_e('Test Mode', 'wondertax-labs-audita'); ?></span>
     792                                                        <span class="wondertax-mode-label"><?php esc_html_e( 'Test Mode', 'wondertax-labs-audita' ); ?></span>
    826793                                                        <span class="wondertax-badge wondertax-badge-warning">
    827794                                                                <span class="dashicons dashicons-warning"></span>
    828                                                                 <?php esc_html_e('Development', 'wondertax-labs-audita'); ?>
     795                                                                <?php esc_html_e( 'Development', 'wondertax-labs-audita' ); ?>
    829796                                                        </span>
    830797                                                </div>
    831798                                                <p class="wondertax-mode-description">
    832                                                         <?php esc_html_e('Transactions are recorded as test data for staging and development. They do not affect compliance reports.', 'wondertax-labs-audita'); ?>
     799                                                        <?php esc_html_e( 'Transactions are recorded as test data for staging and development. They do not affect compliance reports.', 'wondertax-labs-audita' ); ?>
    833800                                                </p>
    834801                                        </div>
    … …  
    839806                                <button type="button" id="wondertax-switch-mode-btn" class="button button-primary" disabled>
    840807                                        <?php
    841                                         if ($is_live) {
    842                                                 esc_html_e('Switch to Test Mode', 'wondertax-labs-audita');
     808                                        if ( $is_live ) {
     809                                                esc_html_e( 'Switch to Test Mode', 'wondertax-labs-audita' );
    843810                                        } else {
    844                                                 esc_html_e('Switch to Live Mode', 'wondertax-labs-audita');
     811                                                esc_html_e( 'Switch to Live Mode', 'wondertax-labs-audita' );
    845812                                        }
    846813                                        ?>
    … …  
    851818                        <p class="wondertax-help-text wondertax-mode-note">
    852819                                <span class="dashicons dashicons-info"></span>
    853                                 <?php esc_html_e('Mode changes take effect immediately for all new transactions.', 'wondertax-labs-audita'); ?>
     820                                <?php esc_html_e( 'Mode changes take effect immediately for all new transactions.', 'wondertax-labs-audita' ); ?>
    854821                        </p>
    855822                </div>
    … …  
    858825
    859826        /**
    860          * Check if there's a pending OAuth confirmation for the current user
    861          *
    862          * @return array|false OAuth data if pending, false otherwise
    863          */
    864         private function get_pending_oauth_data()
    865         {
    866                 $user_id = get_current_user_id();
    867                 if (!$user_id) {
    868                         return false;
    869                 }
    870                 return get_transient('wondertax_pending_oauth_' . $user_id);
    871         }
    872 
    873         /**
    874          * Render OAuth confirmation form
    875          *
    876          * @param array $oauth_data Pending OAuth data
    877          */
    878         private function render_oauth_confirmation($oauth_data)
    879         {
    880                 ?>
    881                 <div class="wondertax-oauth-confirm">
    882                         <div class="wondertax-confirm-icon">
    883                                 <span class="dashicons dashicons-admin-links"></span>
    884                         </div>
    885                         <h2><?php esc_html_e('Connect to WonderTax Labs?', 'wondertax-labs-audita'); ?></h2>
    886                         <p>
    887                                 <?php esc_html_e('WonderTax Labs is requesting to connect to your WooCommerce store. This will:', 'wondertax-labs-audita'); ?>
    888                         </p>
    889                         <ul class="wondertax-confirm-list">
    890                                 <li><?php esc_html_e('Create WooCommerce API credentials for WonderTax Labs', 'wondertax-labs-audita'); ?></li>
    891                                 <li><?php esc_html_e('Allow WonderTax Labs to read your orders and products', 'wondertax-labs-audita'); ?></li>
    892                                 <li><?php esc_html_e('Enable automatic sales tax compliance auditing', 'wondertax-labs-audita'); ?></li>
    893                         </ul>
    894                         <form method="post" class="wondertax-confirm-form">
    895                                 <?php wp_nonce_field('wondertax_confirm_oauth', 'wondertax_nonce'); ?>
    896                                 <p class="wondertax-confirm-actions">
    897                                         <button type="submit" name="wondertax_confirm_oauth" value="1" class="button button-primary button-hero">
    898                                                 <?php esc_html_e('Confirm Connection', 'wondertax-labs-audita'); ?>
    899                                         </button>
    900                                 </p>
    901                                 <p class="wondertax-confirm-cancel">
    902                                         <a href="<?php echo esc_url(admin_url('admin.php?page=wondertax-labs-audita')); ?>">
    903                                                 <?php esc_html_e('Cancel', 'wondertax-labs-audita'); ?>
    904                                         </a>
    905                                 </p>
    906                         </form>
    907                 </div>
    908                 <?php
    909         }
    910 
    911         /**
    912827         * Render admin page
    913828         */
    914         public function render_admin_page()
    915         {
     829        public function render_admin_page() {
     830                // A connect in progress is confirmed on every visit, so a merchant who bound the store and came back later is connected.
     831                self::confirm_pending_connection();
    916832                $is_connected = $this->is_connected();
    917                 $tax_enabled = (bool) get_option('wondertax_tax_calculation_enabled', false);
    918                 $site_url = get_option('wondertax_site_url', '');
    919                 $status_data = $this->get_api_key_status();
    920 
    921                 // Check for pending OAuth confirmation
    922                 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Just checking for presence of flag to show UI, actual action requires nonce
    923                 $show_oauth_confirm = isset($_GET['confirm_oauth']) && '1' === sanitize_text_field(wp_unslash($_GET['confirm_oauth']));
    924                 $pending_oauth = $show_oauth_confirm ? $this->get_pending_oauth_data() : false;
     833                $site_url     = get_option( 'wondertax_site_url', '' );
     834                $status_data  = $this->get_api_key_status();
     835                $held         = class_exists( 'WonderTax_Tax_Service' ) && WonderTax_Tax_Service::is_taken_over();
    925836
    926837                ?>
    927838                <div class="wrap wondertax-admin">
    928839                        <h1>
    929                                 <?php esc_html_e('WonderTax Labs: Audita', 'wondertax-labs-audita'); ?>
     840                                <?php esc_html_e( 'WonderTax Labs: Audita™', 'wondertax-labs-audita' ); ?>
    930841                        </h1>
    931842
    932                         <?php settings_errors('wondertax'); ?>
    933 
    934                         <?php if ($pending_oauth) : ?>
    935                                 <!-- OAuth Confirmation Required -->
    936                                 <div class="wondertax-card">
    937                                         <?php $this->render_oauth_confirmation($pending_oauth); ?>
    938                                 </div>
    939                         <?php else : ?>
     843                        <?php settings_errors( 'wondertax' ); ?>
     844
    940845                        <div class="wondertax-card">
    941                                 <?php if ($is_connected) : ?>
     846                                <?php if ( $is_connected ) : ?>
    942847                                        <!-- Connected State -->
    943848                                        <div class="wondertax-status wondertax-status-connected">
    944849                                                <span class="dashicons dashicons-yes-alt"></span>
    945                                                 <?php esc_html_e('Connected to WonderTax Labs', 'wondertax-labs-audita'); ?>
     850                                                <?php esc_html_e( 'Connected to WonderTax Labs', 'wondertax-labs-audita' ); ?>
    946851                                        </div>
    947852
    948853                                        <!-- Open Dashboard Button -->
    949854                                        <?php $dashboard_url = $this->build_authenticated_dashboard_url(); ?>
    950                                         <?php if ($dashboard_url) : ?>
     855                                        <?php if ( $dashboard_url ) : ?>
    951856                                        <div class="wondertax-dashboard-action">
    952857                                                <a
    953                                                         href="<?php echo esc_url($dashboard_url); ?>"
     858                                                        href="<?php echo esc_url( $dashboard_url ); ?>"
    954859                                                        class="button wondertax-button-dashboard"
    955860                                                        target="_blank"
    … …  
    957862                                                >
    958863                                                        <span class="dashicons dashicons-external"></span>
    959                                                         <?php esc_html_e('Open WonderTax Labs', 'wondertax-labs-audita'); ?>
     864                                                        <?php esc_html_e( 'Open WonderTax Labs', 'wondertax-labs-audita' ); ?>
    960865                                                </a>
    961866                                                <p class="wondertax-dashboard-hint">
    962                                                         <?php esc_html_e('View your tax compliance dashboard, reports, and settings.', 'wondertax-labs-audita'); ?>
     867                                                        <?php esc_html_e( 'View your tax compliance dashboard, reports, and settings.', 'wondertax-labs-audita' ); ?>
    963868                                                </p>
    964869                                        </div>
    965870                                        <?php endif; ?>
    966871
    967                                         <?php if (!empty($site_url)) : ?>
     872                                        <?php if ( ! empty( $site_url ) ) : ?>
    968873                                                <p>
    969                                                         <strong><?php esc_html_e('Site URL:', 'wondertax-labs-audita'); ?></strong>
    970                                                         <?php echo esc_html($site_url); ?>
     874                                                        <strong><?php esc_html_e( 'Site URL:', 'wondertax-labs-audita' ); ?></strong>
     875                                                        <?php echo esc_html( $site_url ); ?>
    971876                                                </p>
    972877                                        <?php endif; ?>
    973878
    974879                                        <!-- Mode Selector for Dual-Key Installations -->
    975                                         <?php if ($status_data && !empty($status_data['dualKeyMode'])) : ?>
    976                                                 <?php $this->render_mode_selector($status_data); ?>
    977                                         <?php elseif ($status_data && isset($status_data['apiKey'])) : ?>
     880                                        <?php if ( $status_data && ! empty( $status_data['dualKeyMode'] ) ) : ?>
     881                                                <?php $this->render_mode_selector( $status_data ); ?>
     882                                        <?php elseif ( $status_data && isset( $status_data['apiKey'] ) ) : ?>
    978883                                                <!-- Legacy API Key Mode Status Badge (for single-key installations) -->
    979884                                                <?php
    980                                                 $api_key = $status_data['apiKey'];
    981                                                 $is_live = (bool) $api_key['live'];
     885                                                $api_key     = $status_data['apiKey'];
     886                                                $is_live     = (bool) $api_key['live'];
    982887                                                $is_disabled = (bool) $api_key['disabled'];
    983888                                                ?>
    984889                                                <div class="wondertax-api-key-status">
    985                                                         <?php if ($is_disabled) : ?>
     890                                                        <?php if ( $is_disabled ) : ?>
    986891                                                                <div class="wondertax-badge wondertax-badge-error">
    987892                                                                        <span class="dashicons dashicons-warning"></span>
    988                                                                         <?php esc_html_e('API Key Disabled', 'wondertax-labs-audita'); ?>
     893                                                                        <?php esc_html_e( 'API Key Disabled', 'wondertax-labs-audita' ); ?>
    989894                                                                </div>
    990895                                                                <p class="wondertax-help-text">
    991                                                                         <?php esc_html_e('Your API key has been disabled. Please contact service@wonder.tax.', 'wondertax-labs-audita'); ?>
     896                                                                        <?php esc_html_e( 'Your API key has been disabled. Please contact service@wonder.tax.', 'wondertax-labs-audita' ); ?>
    992897                                                                </p>
    993                                                         <?php elseif ($is_live) : ?>
     898                                                        <?php elseif ( $is_live ) : ?>
    994899                                                                <div class="wondertax-badge wondertax-badge-success">
    995900                                                                        <span class="dashicons dashicons-yes"></span>
    996                                                                         <?php esc_html_e('Live Mode', 'wondertax-labs-audita'); ?>
     901                                                                        <?php esc_html_e( 'Live Mode', 'wondertax-labs-audita' ); ?>
    997902                                                                </div>
    998903                                                                <p class="wondertax-help-text">
    999                                                                         <?php esc_html_e('Transactions are being recorded as live/production data and will be included in tax reports.', 'wondertax-labs-audita'); ?>
     904                                                                        <?php esc_html_e( 'Transactions are being recorded as live/production data and will be included in tax reports.', 'wondertax-labs-audita' ); ?>
    1000905                                                                </p>
    1001906                                                        <?php else : ?>
    1002907                                                                <div class="wondertax-badge wondertax-badge-warning">
    1003908                                                                        <span class="dashicons dashicons-warning"></span>
    1004                                                                         <?php esc_html_e('Test Mode', 'wondertax-labs-audita'); ?>
     909                                                                        <?php esc_html_e( 'Test Mode', 'wondertax-labs-audita' ); ?>
    1005910                                                                </div>
    1006911                                                                <p class="wondertax-help-text">
    1007                                                                         <?php esc_html_e('Transactions are being recorded as test data. Activate Live Mode when ready for production.', 'wondertax-labs-audita'); ?>
     912                                                                        <?php esc_html_e( 'Transactions are being recorded as test data. Activate Live Mode when ready for production.', 'wondertax-labs-audita' ); ?>
    1008913                                                                </p>
    1009914                                                                <p class="wondertax-help-text">
    1010915                                                                        <a href="https://app.wonder.tax" target="_blank" class="button button-secondary">
    1011                                                                                 <?php esc_html_e('Activate Live Mode', 'wondertax-labs-audita'); ?>
     916                                                                                <?php esc_html_e( 'Activate Live Mode', 'wondertax-labs-audita' ); ?>
    1012917                                                                        </a>
    1013918                                                                </p>
    … …  
    1017922
    1018923                                        <!-- Recent Activity Stats -->
    1019                                         <?php if ($status_data && isset($status_data['stats']['recentTransactionCount'])) : ?>
     924                                        <?php if ( $status_data && isset( $status_data['stats']['recentTransactionCount'] ) ) : ?>
    1020925                                                <div class="wondertax-api-key-status">
    1021926                                                        <p class="wondertax-stats">
    1022                                                                 <strong><?php esc_html_e('Recent Activity:', 'wondertax-labs-audita'); ?></strong>
     927                                                                <strong><?php esc_html_e( 'Recent Activity:', 'wondertax-labs-audita' ); ?></strong>
    1023928                                                                <?php
    1024929                                                                printf(
    1025930                                                                        /* translators: %d: number of transactions */
    1026                                                                         esc_html(_n('%d transaction in the last 30 days', '%d transactions in the last 30 days', absint($status_data['stats']['recentTransactionCount']), 'wondertax-labs-audita')),
    1027                                                                         absint($status_data['stats']['recentTransactionCount'])
     931                                                                        esc_html( _n( '%d transaction in the last 30 days', '%d transactions in the last 30 days', absint( $status_data['stats']['recentTransactionCount'] ), 'wondertax-labs-audita' ) ),
     932                                                                        absint( $status_data['stats']['recentTransactionCount'] )
    1028933                                                                );
    1029934                                                                ?>
    1030935                                                        </p>
    1031936                                                        <p class="wondertax-help-text">
    1032                                                                 <a href="<?php echo esc_url('https://app.wonder.tax/integrations/woocommerce/docs'); ?>" target="_blank">
    1033                                                                         <?php esc_html_e('Learn about Live vs Test Mode', 'wondertax-labs-audita'); ?>
     937                                                                <a href="<?php echo esc_url( 'https://app.wonder.tax/integrations/woocommerce/docs' ); ?>" target="_blank">
     938                                                                        <?php esc_html_e( 'Learn about Live vs Test Mode', 'wondertax-labs-audita' ); ?>
    1034939                                                                        <span class="dashicons dashicons-external" style="font-size: 14px; vertical-align: middle;"></span>
    1035940                                                                </a>
    … …  
    1038943                                        <?php endif; ?>
    1039944
    1040                                         <!-- Tax Calculation Status (Audit Only Mode) -->
     945                                        <!-- Checkout tax: who answers it -->
    1041946                                        <table class="form-table">
    1042947                                                <tr>
    1043948                                                        <th scope="row">
    1044                                                                 <?php esc_html_e('Real-Time Tax Auditing', 'wondertax-labs-audita'); ?>
     949                                                                <?php esc_html_e( 'Checkout Tax', 'wondertax-labs-audita' ); ?>
    1045950                                                        </th>
    1046951                                                        <td>
    1047                                                                 <h3><?php esc_html_e('Features', 'wondertax-labs-audita'); ?></h3>
     952                                                                <?php if ( $held ) : ?>
     953                                                                        <p>
     954                                                                                <?php esc_html_e( 'WonderTax Labs (Reporta™) answers your checkout tax: each cart\'s address and lines are sent to WonderTax Labs at checkout, and your store applies the tax it answers. Your own tax settings were recorded and are put back if you disconnect or deactivate this plugin.', 'wondertax-labs-audita' ); ?>
     955                                                                        </p>
     956                                                                <?php else : ?>
     957                                                                        <p>
     958                                                                                <?php esc_html_e( 'Your store calculates its own checkout tax. WonderTax Labs imports your orders and audits the sales tax they charged.', 'wondertax-labs-audita' ); ?>
     959                                                                        </p>
     960                                                                <?php endif; ?>
     961                                                                <h3><?php esc_html_e( 'Features', 'wondertax-labs-audita' ); ?></h3>
    1048962                                                                <ul>
    1049                                                                         <li><?php esc_html_e('✓ Automatic tax compliance tracking', 'wondertax-labs-audita'); ?></li>
    1050                                                                         <li><?php esc_html_e('✓ Real-time order import', 'wondertax-labs-audita'); ?></li>
    1051                                                                         <li><?php esc_html_e('✓ Multi-jurisdiction support', 'wondertax-labs-audita'); ?></li>
    1052                                                                         <li><?php esc_html_e('✓ Historical order import', 'wondertax-labs-audita'); ?></li>
     963                                                                        <li><?php esc_html_e( '✓ Automatic tax compliance tracking', 'wondertax-labs-audita' ); ?></li>
     964                                                                        <li><?php esc_html_e( '✓ Real-time order import', 'wondertax-labs-audita' ); ?></li>
     965                                                                        <li><?php esc_html_e( '✓ Multi-jurisdiction support', 'wondertax-labs-audita' ); ?></li>
     966                                                                        <li><?php esc_html_e( '✓ Historical order import', 'wondertax-labs-audita' ); ?></li>
    1053967                                                                </ul>
    1054968                                                        </td>
    … …  
    1059973                                        <hr />
    1060974                                        <form method="post" class="wondertax-form">
    1061                                                 <?php wp_nonce_field('wondertax_disconnect', 'wondertax_nonce'); ?>
     975                                                <?php wp_nonce_field( 'wondertax_disconnect', 'wondertax_nonce' ); ?>
    1062976                                                <p>
    1063977                                                        <button
    … …  
    1065979                                                                name="wondertax_disconnect"
    1066980                                                                class="button button-secondary"
    1067                                                                 onclick="return confirm('<?php echo esc_js(__('Are you sure you want to disconnect? This will disable your zero-cost, zero-risk sales tax audit agents.', 'wondertax-labs-audita')); ?>');"
     981                                                                onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to disconnect? WonderTax Labs will stop importing this store\'s orders, the API key it reads the store with will be removed, and your own tax settings are put back if WonderTax Labs answers your checkout tax.', 'wondertax-labs-audita' ) ); ?>');"
    1068982                                                        >
    1069                                                                 <?php esc_html_e('Disconnect Store', 'wondertax-labs-audita'); ?>
     983                                                                <?php esc_html_e( 'Disconnect Store', 'wondertax-labs-audita' ); ?>
    1070984                                                        </button>
    1071985                                                </p>
    … …  
    1076990                                        <div class="wondertax-status wondertax-status-disconnected">
    1077991                                                <span class="dashicons dashicons-warning"></span>
    1078                                                 <?php esc_html_e('Not Connected', 'wondertax-labs-audita'); ?>
     992                                                <?php esc_html_e( 'Not Connected', 'wondertax-labs-audita' ); ?>
    1079993                                        </div>
    1080994
    1081995                                        <p>
    1082                                                 <?php esc_html_e('Connect your WooCommerce store to WonderTax Labs for automated zero-cost and zero-risk sales tax auditing.', 'wondertax-labs-audita'); ?>
     996                                                <?php esc_html_e( 'Connect your WooCommerce store to WonderTax Labs: Audita™, which audits the sales tax your store charges at zero cost and zero risk.', 'wondertax-labs-audita' ); ?>
    1083997                                        </p>
    1084998
    … …  
    10881002                                                        add_query_arg(
    10891003                                                                array(
    1090                                                                         'page' => 'wondertax-labs-audita',
     1004                                                                        'page'   => 'wondertax-labs-audita',
    10911005                                                                        'action' => 'connect',
    10921006                                                                ),
    1093                                                                 admin_url('admin.php')
     1007                                                                admin_url( 'admin.php' )
    10941008                                                        ),
    10951009                                                        'wondertax_connect',
    … …  
    10981012                                                ?>
    10991013                                                <a
    1100                                                         href="<?php echo esc_url($connect_url); ?>"
     1014                                                        href="<?php echo esc_url( $connect_url ); ?>"
    11011015                                                        class="button button-primary"
    11021016                                                >
    1103                                                         <?php esc_html_e('Connect to WonderTax Labs', 'wondertax-labs-audita'); ?>
     1017                                                        <?php esc_html_e( 'Connect to WonderTax Labs', 'wondertax-labs-audita' ); ?>
    11041018                                                </a>
    11051019                                        </p>
    11061020
    11071021                                        <hr />
    1108                                         <h3><?php esc_html_e('Features', 'wondertax-labs-audita'); ?></h3>
     1022                                        <h3><?php esc_html_e( 'Features', 'wondertax-labs-audita' ); ?></h3>
    11091023                                        <ul>
    1110                                                 <li><?php esc_html_e('✓ Automatic tax compliance tracking', 'wondertax-labs-audita'); ?></li>
    1111                                                 <li><?php esc_html_e('✓ Multi-jurisdiction support', 'wondertax-labs-audita'); ?></li>
    1112                                                 <li><?php esc_html_e('✓ Historical order import', 'wondertax-labs-audita'); ?></li>
     1024                                                <li><?php esc_html_e( '✓ Automatic tax compliance tracking', 'wondertax-labs-audita' ); ?></li>
     1025                                                <li><?php esc_html_e( '✓ Multi-jurisdiction support', 'wondertax-labs-audita' ); ?></li>
     1026                                                <li><?php esc_html_e( '✓ Historical order import', 'wondertax-labs-audita' ); ?></li>
    11131027                                        </ul>
    11141028
    … …  
    11211035                                        printf(
    11221036                                                /* translators: 1: Link to documentation, 2: Link to support */
    1123                                                 esc_html__('Need help? Check out our %1$s or contact %2$s.', 'wondertax-labs-audita'),
    1124                                                 '<a href="https://app.wonder.tax/integrations/woocommerce/docs" target="_blank">' . esc_html__('documentation', 'wondertax-labs-audita') . '</a>',
    1125                                                 '<a href="mailto:service@wonder.tax">' . esc_html__('support', 'wondertax-labs-audita') . '</a>'
     1037                                                esc_html__( 'Need help? Check out our %1$s or contact %2$s.', 'wondertax-labs-audita' ),
     1038                                                '<a href="https://app.wonder.tax/integrations/woocommerce/docs" target="_blank">' . esc_html__( 'documentation', 'wondertax-labs-audita' ) . '</a>',
     1039                                                '<a href="mailto:service@wonder.tax">' . esc_html__( 'support', 'wondertax-labs-audita' ) . '</a>'
    11261040                                        );
    11271041                                        ?>
    … …  
    11311045                                </p>
    11321046                        </div>
    1133                         <?php endif; ?>
    11341047                </div>
    11351048                <?php
  • wondertax-labs-audita/tags/1.4.1/includes/class-wondertax-tax-calc.php

    r3556520 r3814612  
    33 * Tax Calculation Hook
    44 *
    5  * Hooks into WooCommerce tax calculation to provide real-time tax rates
    6  * from WonderTax Labs during checkout.
     5 * While WonderTax Labs answers the store's checkout tax (WonderTax_Tax_Service), asks it for each cart's tax and
     6 * applies the exact amounts it answers: each line's own tax, and each jurisdiction's item and shipping totals.
     7 * A refusal leaves the store's own rates in place.
     8 *
     9 * Only the buyer's exemption is kept: a customer WooCommerce flags tax-exempt is never asked, so WooCommerce's zero stands.
     10 * A product, fee or shipping method WooCommerce marks not taxable (tax status "None", a zero-rate or exempt tax class) is
     11 * sent and taxed like any other, as its import taxes it, because only a taxability code exempts a product
     12 * (📗 integration-import · I42); the order's line records a product's tax status "None" for the merchant's notice. While
     13 * WonderTax Labs holds the store, WooCommerce's taxes stay on whatever "Enable taxes" says (wc_tax_enabled), since turning
     14 * them off does not exempt a sale.
     15 *
     16 * Only the exact-amounts step asks WonderTax Labs; woocommerce_find_rates keeps WooCommerce's own rates as its starting
     17 * point, so a cart is sent once, as totaled: its lines, its fees and its shipping, in one request. Each fee takes the
     18 * taxes answered for it, as the order's import taxes its fee line; a negative fee (a discount) lowers the lines it falls
     19 * on as the import lowers them, and takes no tax of its own.
    720 *
    821 * Supports both Classic Checkout and Block Checkout (Store API).
    … …  
    1225
    1326// Exit if accessed directly
    14 if (!defined('ABSPATH')) {
     27if ( ! defined( 'ABSPATH' ) ) {
    1528        exit;
    1629}
    … …  
    1932 * Tax calculation class
    2033 */
    21 class WonderTax_Tax_Calc
    22 {
     34class WonderTax_Tax_Calc {
     35
    2336        /**
    2437         * Singleton instance
    … …  
    2942
    3043        /**
     44         * Door replies already fetched in this request, by request body.
     45         *
     46         * @var array
     47         */
     48        private $quotes = array();
     49
     50        /**
     51         * Seconds a call to the door may take.
     52         */
     53        const TIMEOUT = 5;
     54
     55        /**
     56         * Transient set when the door fails (no reply, or a 5xx): while it stands, the door is not asked and the store's own
     57         * rates apply.
     58         */
     59        const PAUSE_TRANSIENT = 'wondertax_tax_service_paused';
     60
     61        /**
     62         * Seconds the door is skipped after a failure.
     63         */
     64        const PAUSE_SECONDS = 60;
     65
     66        /**
     67         * The option counting the door's consecutive failures (a refusal, or no reply) and naming the last one's reason. It is
     68         * cleared by the next answered request, and by a takeover, a give-back and a disconnect
     69         * (WonderTax_Tax_Service::clear_door_failures).
     70         */
     71        const FAILURES_OPTION = 'wondertax_door_failures';
     72
     73        /**
     74         * How many failures in a row the store's managers are told of: one refusal can be a single bad address.
     75         */
     76        const FAILURES_NOTICE_AT = 3;
     77
     78        /**
     79         * The session key holding each rate label of the answer the cart carries now, by its rate id, for the order's tax lines:
     80         * empty while the store's own rates apply.
     81         */
     82        const RATE_LABELS_SESSION = 'wondertax_rate_labels';
     83
     84        /**
     85         * Line-item meta naming a product's own tax status ("none"), read by the order import (its REST line item carries no
     86         * tax status) as a fact for the merchant's notice, never an exemption (📗 integration-import · I42).
     87         */
     88        const TAX_STATUS_META = '_wondertax_tax_status';
     89
     90        /**
     91         * Session key holding the shipping taxes answered for the cart, by rate id: null when none was answered.
     92         */
     93        const SHIPPING_TAXES_SESSION = 'wondertax_exact_shipping_taxes';
     94
     95        /**
     96         * A line's tax data when it carries no tax.
     97         */
     98        const UNTAXED_LINE = array(
     99                'subtotal' => array(),
     100                'total'    => array(),
     101        );
     102
     103        /**
    31104         * Get singleton instance
    32105         *
    33106         * @return WonderTax_Tax_Calc
    34107         */
    35         public static function get_instance()
    36         {
    37                 if (null === self::$instance) {
     108        public static function get_instance() {
     109                if ( null === self::$instance ) {
    38110                        self::$instance = new self();
    39111                }
    … …  
    44116         * Constructor
    45117         */
    46         private function __construct()
    47         {
    48                 // Hook into WooCommerce tax calculation (Classic Checkout)
    49                 add_filter('woocommerce_find_rates', array($this, 'calculate_tax_rates'), 10, 2);
     118        private function __construct() {
     119                // Classic Checkout's rates step: WooCommerce's own rates are the starting point the exact amounts replace
     120                add_filter( 'woocommerce_find_rates', array( $this, 'calculate_tax_rates' ), 10, 2 );
     121
     122                // The order's line records a product's tax status "None", for the import's notice to the merchant
     123                add_action( 'woocommerce_checkout_create_order_line_item', array( $this, 'record_line_tax_status' ), 10, 4 );
     124
     125                // While WonderTax Labs holds the store, WooCommerce's taxes stay on whatever "Enable taxes" says
     126                add_filter( 'wc_tax_enabled', array( $this, 'keep_taxes_on_while_held' ), 10, 1 );
    50127
    51128                // Hook into Store API for Block Checkout compatibility
    52                 add_action('woocommerce_store_api_checkout_update_order_from_request', array($this, 'store_api_update_order_taxes'), 10, 2);
     129                add_action( 'woocommerce_store_api_checkout_update_order_from_request', array( $this, 'store_api_update_order_taxes' ), 10, 2 );
    53130
    54131                // Register Store API extension after blocks are loaded
    55                 add_action('woocommerce_blocks_loaded', array($this, 'register_store_api_hooks'));
     132                add_action( 'woocommerce_blocks_loaded', array( $this, 'register_store_api_hooks' ) );
     133
     134                // Apply the exact amounts answered, after WooCommerce has totaled the cart (both checkouts)
     135                add_action( 'woocommerce_after_calculate_totals', array( $this, 'apply_exact_cart_taxes' ), 20 );
     136
     137                // The order's shipping line carries the shipping tax answered
     138                add_action( 'woocommerce_checkout_create_order_shipping_item', array( $this, 'apply_exact_shipping_taxes' ), 10, 4 );
     139
     140                // Each tax line is named by the jurisdiction WonderTax Labs answered for it, not WooCommerce's generic "Tax".
     141                add_filter( 'woocommerce_rate_label', array( $this, 'answered_rate_label' ), 10, 2 );
     142        }
     143
     144        /**
     145         * Records on the order's line that its product's tax status is "None", so the import can tell the merchant: the line is
     146         * taxed all the same (📗 integration-import · I42).
     147         *
     148         * @param \WC_Order_Item_Product $item          Order line.
     149         * @param string                 $cart_item_key Cart item key.
     150         * @param array                  $values        Cart item.
     151         * @param \WC_Order              $order         Order.
     152         */
     153        public function record_line_tax_status( $item, $cart_item_key, $values, $order ) {
     154                if ( ! get_option( 'wondertax_connected', false ) || ! isset( $values['data'] ) || ! is_object( $values['data'] ) ) {
     155                        return;
     156                }
     157                if ( 'none' === $values['data']->get_tax_status() ) {
     158                        $item->update_meta_data( self::TAX_STATUS_META, 'none' );
     159                }
     160        }
     161
     162        /**
     163         * WooCommerce's taxes, as wc_tax_enabled() reads them: on while WonderTax Labs holds the store, whatever "Enable taxes"
     164         * says, since turning them off does not exempt a sale and WooCommerce runs no tax calculation while they are off
     165         * (📗 integration-import · I37 I42). Otherwise the merchant's own setting.
     166         *
     167         * @param bool $enabled Whether "Enable taxes" is on.
     168         * @return bool
     169         */
     170        public function keep_taxes_on_while_held( $enabled ) {
     171                return $enabled || $this->is_tax_calculation_enabled();
     172        }
     173
     174        /**
     175         * Does WonderTax Labs answer this cart's tax? Only while it holds the store, and never for a customer WooCommerce flags
     176         * tax-exempt (the buyer's exemption, 📗 integration-import · I36).
     177         *
     178         * @param \WC_Cart|null $cart Cart.
     179         * @return bool
     180         */
     181        private function answers_cart( $cart ) {
     182                if ( ! $this->is_tax_calculation_enabled() || ! $cart || $cart->is_empty() ) {
     183                        return false;
     184                }
     185                $customer = $cart->get_customer();
     186                return $customer && ! $customer->get_is_vat_exempt();
    56187        }
    57188
    … …  
    59190         * Register Store API specific hooks after blocks are loaded
    60191         */
    61         public function register_store_api_hooks()
    62         {
     192        public function register_store_api_hooks() {
    63193                // Hook into Store API cart updates for real-time tax calculation
    64                 add_action('woocommerce_store_api_cart_update_customer_from_request', array($this, 'store_api_calculate_taxes'), 10, 2);
     194                add_action( 'woocommerce_store_api_cart_update_customer_from_request', array( $this, 'store_api_calculate_taxes' ), 10, 2 );
    65195        }
    66196
    … …  
    71201         * @param \WP_REST_Request $request REST request object.
    72202         */
    73         public function store_api_calculate_taxes($customer, $request)
    74         {
    75                 if (!$this->is_tax_calculation_enabled()) {
     203        public function store_api_calculate_taxes( $customer, $request ) {
     204                if ( ! $this->is_tax_calculation_enabled() ) {
    76205                        return;
    77206                }
    … …  
    79208                // Get shipping address from customer (Block Checkout sends this)
    80209                $country = $customer->get_shipping_country();
    81                 $state = $customer->get_shipping_state();
     210                $state   = $customer->get_shipping_state();
    82211
    83212                // Only process US addresses
    84                 if ('US' !== $country || empty($state)) {
    85                         return;
    86                 }
    87 
    88                 // Force cart to recalculate totals (this triggers woocommerce_find_rates)
    89                 if (WC()->cart) {
     213                if ( 'US' !== $country || empty( $state ) ) {
     214                        return;
     215                }
     216
     217                // Force cart to recalculate totals (this triggers woocommerce_find_rates and apply_exact_cart_taxes)
     218                if ( WC()->cart ) {
    90219                        WC()->cart->calculate_totals();
    91220                }
    … …  
    93222
    94223        /**
    95          * Update order taxes when Store API checkout processes order
     224         * Puts the exact amounts answered onto the Store API's draft order. `OrderController::update_order_from_cart` ends with
     225         * `calculate_totals()`, which re-derives each line's and the shipping's tax from one rate per class; this action runs
     226         * after it, so each line takes its cart line's exact taxes, the first shipping line the shipping taxes answered (none on
     227         * any other, bug book B-281), the order's tax lines are rebuilt from them, and only the totals are summed again.
    96228         *
    97229         * @param \WC_Order $order Order object.
    98230         * @param \WP_REST_Request $request REST request object.
    99231         */
    100         public function store_api_update_order_taxes($order, $request)
    101         {
    102                 if (!$this->is_tax_calculation_enabled()) {
    103                         return;
    104                 }
    105 
    106                 // Get shipping address from order
    107                 $country = $order->get_shipping_country();
    108                 $state = $order->get_shipping_state();
    109 
    110                 // Only process US addresses
    111                 if ('US' !== $country || empty($state)) {
    112                         return;
    113                 }
    114 
    115                 // Recalculate order taxes (this triggers woocommerce_find_rates via order tax calculation)
    116                 $order->calculate_taxes();
    117                 $order->calculate_totals();
    118         }
    119 
    120         /**
    121          * Calculate tax rates using WonderTax Labs API
    122          *
    123          * @param array $rates Default tax rates.
    124          * @param array $args Tax calculation arguments.
    125          * @return array Modified tax rates.
    126          */
    127         public function calculate_tax_rates($rates, $args)
    128         {
    129                 // Check if WonderTax tax calculation is enabled
    130                 if (!$this->is_tax_calculation_enabled()) {
    131                         return $rates;
    132                 }
    133 
    134                 // Check if we have necessary address information
    135                 if (empty($args['country']) || empty($args['state'])) {
    136                         return $rates;
    137                 }
    138 
    139                 // Only process US addresses
    140                 if ('US' !== $args['country']) {
    141                         return $rates;
     232        public function store_api_update_order_taxes( $order, $request ) {
     233                if ( ! $this->is_tax_calculation_enabled() ) {
     234                        return;
     235                }
     236                $cart = WC()->cart;
     237                if ( ! $this->answers_cart( $cart ) || wc_prices_include_tax() ) {
     238                        return;
     239                }
     240                $shipping_taxes = $this->session_shipping_taxes();
     241                if ( ! is_array( $shipping_taxes ) ) {
     242                        // No exact answer for this cart (a refusal, or the door paused): WooCommerce's own figures stand.
     243                        return;
     244                }
     245                $this->apply_cart_taxes_to_order( $order, $cart, $shipping_taxes );
     246                $order->update_taxes();
     247                $order->calculate_totals( false );
     248        }
     249
     250        /**
     251         * Copies each cart line's exact taxes onto the order line built from it (matched by its cart key, else by product,
     252         * variation and quantity, each cart line used once), each cart fee's taxes onto the fee line built from it (matched by
     253         * its fee key, else by name and total, each cart fee used once; a negative fee carries none), and the shipping taxes
     254         * onto the first shipping line.
     255         *
     256         * @param \WC_Order $order          Order.
     257         * @param \WC_Cart  $cart           Cart, already carrying the exact amounts (apply_exact_cart_taxes).
     258         * @param array     $shipping_taxes The shipping taxes answered, by rate id.
     259         */
     260        private function apply_cart_taxes_to_order( $order, $cart, $shipping_taxes ) {
     261                $unused = $cart->get_cart();
     262                foreach ( $order->get_items( 'line_item' ) as $item ) {
     263                        $key = self::unused_key(
     264                                $unused,
     265                                isset( $item->legacy_cart_item_key ) ? $item->legacy_cart_item_key : null,
     266                                function ( $cart_item ) use ( $item ) {
     267                                        return (int) $cart_item['product_id'] === (int) $item->get_product_id()
     268                                                && (int) ( isset( $cart_item['variation_id'] ) ? $cart_item['variation_id'] : 0 ) === (int) $item->get_variation_id()
     269                                                && (float) $cart_item['quantity'] === (float) $item->get_quantity();
     270                                }
     271                        );
     272                        if ( null === $key ) {
     273                                continue;
     274                        }
     275                        $line_tax_data = isset( $unused[ $key ]['line_tax_data'] ) && is_array( $unused[ $key ]['line_tax_data'] )
     276                                ? $unused[ $key ]['line_tax_data']
     277                                : self::UNTAXED_LINE;
     278                        $item->set_taxes( $line_tax_data );
     279                        unset( $unused[ $key ] );
     280                }
     281                $unused_fees = $this->cart_fees( $cart );
     282                foreach ( $order->get_items( 'fee' ) as $fee_item ) {
     283                        $key = self::unused_key(
     284                                $unused_fees,
     285                                isset( $fee_item->legacy_fee_key ) ? $fee_item->legacy_fee_key : null,
     286                                function ( $fee ) use ( $fee_item ) {
     287                                        return is_object( $fee )
     288                                                && isset( $fee->name, $fee->total )
     289                                                && (string) $fee->name === (string) $fee_item->get_name()
     290                                                && abs( (float) $fee->total - (float) $fee_item->get_total() ) < 0.005;
     291                                }
     292                        );
     293                        if ( null === $key || ! is_object( $unused_fees[ $key ] ) ) {
     294                                continue;
     295                        }
     296                        $fee_tax_data = isset( $unused_fees[ $key ]->tax_data ) && is_array( $unused_fees[ $key ]->tax_data )
     297                                ? $unused_fees[ $key ]->tax_data
     298                                : array();
     299                        $fee_item->set_taxes( array( 'total' => $fee_tax_data ) );
     300                        unset( $unused_fees[ $key ] );
     301                }
     302                $first = true;
     303                foreach ( $order->get_items( 'shipping' ) as $shipping_item ) {
     304                        $shipping_item->set_taxes( self::shipping_line_taxes( $first, $shipping_taxes ) );
     305                        $first = false;
     306                }
     307        }
     308
     309        /**
     310         * The key of the cart entry an order line was built from, each entry used once: its own key while that entry is still
     311         * unused, else the first unused entry that matches it.
     312         *
     313         * @param array       $unused  The cart entries not yet used, by key.
     314         * @param string|null $own_key The key the order line carries, or null.
     315         * @param callable    $matches Whether an entry matches the order line.
     316         * @return string|null
     317         */
     318        private static function unused_key( $unused, $own_key, $matches ) {
     319                if ( null !== $own_key && isset( $unused[ $own_key ] ) ) {
     320                        return $own_key;
     321                }
     322                foreach ( $unused as $key => $entry ) {
     323                        if ( $matches( $entry ) ) {
     324                                return $key;
     325                        }
     326                }
     327                return null;
     328        }
     329
     330        /**
     331         * A shipping line's taxes: the shipping taxes answered on the first package's line, none on any other, so they are
     332         * never counted twice (bug book B-281).
     333         *
     334         * @param bool  $is_first       Whether this is the first package's line.
     335         * @param array $shipping_taxes The shipping taxes answered, by rate id.
     336         * @return array
     337         */
     338        private static function shipping_line_taxes( $is_first, $shipping_taxes ) {
     339                return array( 'total' => $is_first ? $shipping_taxes : array() );
     340        }
     341
     342        /**
     343         * The cart's fees, by fee key.
     344         *
     345         * @param \WC_Cart $cart Cart object.
     346         * @return array
     347         */
     348        private function cart_fees( $cart ) {
     349                return (array) $cart->get_fees();
     350        }
     351
     352        /**
     353         * The shipping taxes answered for the cart, kept in the session: null when none was answered or there is no session.
     354         *
     355         * @return array|null
     356         */
     357        private function session_shipping_taxes() {
     358                return WC()->session ? WC()->session->get( self::SHIPPING_TAXES_SESSION ) : null;
     359        }
     360
     361        /**
     362         * Keeps the shipping taxes answered for the cart in the session, when there is one.
     363         *
     364         * @param array|null $shipping_taxes The shipping taxes, by rate id, or null when none was answered.
     365         */
     366        private function set_session_shipping_taxes( $shipping_taxes ) {
     367                if ( WC()->session ) {
     368                        WC()->session->set( self::SHIPPING_TAXES_SESSION, $shipping_taxes );
     369                }
     370        }
     371
     372        /**
     373         * The cart's taxable address as both checkout steps send it, or null when it is not a US address with a state.
     374         *
     375         * @param \WC_Cart|null $cart Cart.
     376         * @return array|null
     377         */
     378        private function cart_address( $cart ) {
     379                $customer = $cart ? $cart->get_customer() : null;
     380                if ( ! $customer ) {
     381                        return null;
     382                }
     383                list($country, $state, $postcode, $city) = array_pad( $customer->get_taxable_address(), 4, '' );
     384                if ( 'US' !== $country || empty( $state ) ) {
     385                        return null;
     386                }
     387                return array(
     388                        'country'  => $country,
     389                        'state'    => $state,
     390                        'postcode' => $postcode,
     391                        'city'     => $city,
     392                        'address'  => $customer->get_shipping_address_1(),
     393                );
     394        }
     395
     396        /**
     397         * The rates WooCommerce totals a cart from. WonderTax Labs is never asked here: its exact amounts replace every figure
     398         * once the cart is totaled (apply_exact_cart_taxes), so WooCommerce's own rates are only the starting point.
     399         *
     400         * @param array $rates WooCommerce's own rates.
     401         * @param array $args  Tax calculation arguments.
     402         * @return array
     403         */
     404        public function calculate_tax_rates( $rates, $args ) {
     405                return $rates;
     406        }
     407
     408        /**
     409         * Replaces the cart's tax amounts with the exact amounts answered: each line's own tax, each fee's own tax, and each
     410         * jurisdiction's item, fee and shipping totals, on the lines' totals after coupons. A refusal leaves WooCommerce's own
     411         * figures, and its own rate labels: labels are kept only while an answer stands.
     412         *
     413         * @param \WC_Cart $cart Cart object.
     414         */
     415        public function apply_exact_cart_taxes( $cart ) {
     416                $this->set_session_shipping_taxes( null );
     417                $this->set_session_rate_labels( array() );
     418                if ( wc_prices_include_tax() ) {
     419                        return;
     420                }
     421                // The buyer's exemption (a tax-exempt customer) keeps WooCommerce's zero.
     422                if ( ! $this->answers_cart( $cart ) ) {
     423                        return;
     424                }
     425                $args = $this->cart_address( $cart );
     426                if ( null === $args ) {
     427                        return;
    142428                }
    143429
    144430                try {
    145                         // Build tax request
    146                         $tax_request = $this->build_tax_request($args);
    147 
    148                         // Call WonderTax Labs API
    149                         $tax_response = $this->call_tax_service($tax_request);
    150 
    151                         if (is_wp_error($tax_response)) {
    152                                 return $rates;
    153                         }
    154 
    155                         // Parse response and return tax rates
    156                         return $this->parse_tax_response($tax_response, $args);
    157 
    158                 } catch (Exception $e) {
    159                         return $rates;
    160                 }
    161         }
    162 
    163         /**
    164          * Check if tax calculation is enabled
     431                        $built = $this->build_tax_request( $args, $cart );
     432                        $reply = $this->quote( $built['request'] );
     433                        if ( is_wp_error( $reply ) || ! isset( $reply['lines'] ) || ! is_array( $reply['lines'] ) ) {
     434                                return;
     435                        }
     436
     437                        $this->remember_rate_labels( $reply );
     438                        $subtotal_tax = $this->apply_line_taxes( $cart, $built['keys'], self::taxes_by_index( $reply['lines'] ) );
     439                        list($item_taxes, $shipping_taxes, $answered_fee_taxes) = self::jurisdiction_totals( $reply );
     440                        $fee_taxes = $this->apply_fee_taxes( $cart, $built['fee_keys'], $reply, $answered_fee_taxes );
     441                        $this->set_cart_totals( $cart, $subtotal_tax, $item_taxes, $shipping_taxes, $fee_taxes );
     442                        $this->set_session_shipping_taxes( $shipping_taxes );
     443                } catch ( Exception $e ) {
     444                        return;
     445                }
     446        }
     447
     448        /**
     449         * Puts each line's answered taxes on its cart line (`line_tax_data`, `line_tax`, `line_subtotal_tax`), its subtotal
     450         * (before coupons) carrying the same taxes scaled to it so the coupon's own tax shows; returns the cart's subtotal tax.
     451         *
     452         * @param \WC_Cart $cart           Cart object.
     453         * @param string[] $keys           The cart item keys, in request order.
     454         * @param array    $lines_by_index The taxes answered for each line, by request index (taxes_by_index).
     455         * @return float
     456         */
     457        private function apply_line_taxes( $cart, $keys, $lines_by_index ) {
     458                $subtotal_tax = 0.0;
     459                foreach ( $keys as $index => $key ) {
     460                        $line_taxes = self::taxes_by_rate( isset( $lines_by_index[ $index ] ) ? $lines_by_index[ $index ] : array() );
     461
     462                        $item           = $cart->cart_contents[ $key ];
     463                        $line_total     = isset( $item['line_total'] ) ? (float) $item['line_total'] : 0.0;
     464                        $line_subtotal  = isset( $item['line_subtotal'] ) ? (float) $item['line_subtotal'] : $line_total;
     465                        $scale          = $line_total > 0 ? $line_subtotal / $line_total : 1.0;
     466                        $subtotal_taxes = array();
     467                        foreach ( $line_taxes as $rate_id => $amount ) {
     468                                $subtotal_taxes[ $rate_id ] = $amount * $scale;
     469                        }
     470
     471                        $cart->cart_contents[ $key ]['line_tax_data']     = array(
     472                                'subtotal' => $subtotal_taxes,
     473                                'total'    => $line_taxes,
     474                        );
     475                        $cart->cart_contents[ $key ]['line_tax']          = array_sum( $line_taxes );
     476                        $cart->cart_contents[ $key ]['line_subtotal_tax'] = array_sum( $subtotal_taxes );
     477                        $subtotal_tax                                    += array_sum( $subtotal_taxes );
     478                }
     479                return $subtotal_tax;
     480        }
     481
     482        /**
     483         * Each jurisdiction's item, shipping and fee totals answered, summed and rounded once by WonderTax Labs, each by rate id.
     484         *
     485         * @param array $reply The door's reply.
     486         * @return array { 0: item taxes, 1: shipping taxes, 2: fee taxes }
     487         */
     488        private static function jurisdiction_totals( $reply ) {
     489                $item_taxes     = array();
     490                $shipping_taxes = array();
     491                $fee_taxes      = array();
     492                if ( isset( $reply['taxes'] ) && is_array( $reply['taxes'] ) ) {
     493                        foreach ( $reply['taxes'] as $tax ) {
     494                                if ( ! isset( $tax['rate_id'] ) ) {
     495                                        continue;
     496                                }
     497                                $rate_id                    = (string) $tax['rate_id'];
     498                                $item_taxes[ $rate_id ]     = isset( $tax['tax_total'] ) ? (float) $tax['tax_total'] : 0.0;
     499                                $shipping_taxes[ $rate_id ] = isset( $tax['shipping_tax_total'] ) ? (float) $tax['shipping_tax_total'] : 0.0;
     500                                $fee_taxes[ $rate_id ]      = isset( $tax['fee_tax_total'] ) ? (float) $tax['fee_tax_total'] : 0.0;
     501                        }
     502                }
     503                return array( $item_taxes, $shipping_taxes, $fee_taxes );
     504        }
     505
     506        /**
     507         * Sets the cart's tax figures and its total from the exact amounts.
     508         *
     509         * @param \WC_Cart $cart           Cart object.
     510         * @param float    $subtotal_tax   The lines' subtotal tax.
     511         * @param array    $item_taxes     Each jurisdiction's item tax, by rate id.
     512         * @param array    $shipping_taxes Each jurisdiction's shipping tax, by rate id.
     513         * @param array    $fee_taxes      The cart's fee taxes, by rate id (apply_fee_taxes).
     514         */
     515        private function set_cart_totals( $cart, $subtotal_tax, $item_taxes, $shipping_taxes, $fee_taxes ) {
     516                $cart->set_subtotal_tax( $subtotal_tax );
     517                $cart->set_cart_contents_taxes( $item_taxes );
     518                $cart->set_cart_contents_tax( array_sum( $item_taxes ) );
     519                $cart->set_shipping_taxes( $shipping_taxes );
     520                $cart->set_shipping_tax( array_sum( $shipping_taxes ) );
     521                $cart->set_fee_taxes( $fee_taxes );
     522                $cart->set_fee_tax( array_sum( $fee_taxes ) );
     523                $total_tax = array_sum( $item_taxes ) + array_sum( $shipping_taxes ) + array_sum( $fee_taxes );
     524                $cart->set_total_tax( $total_tax );
     525                $total = (float) $cart->get_cart_contents_total() + (float) $cart->get_shipping_total() + (float) $cart->get_fee_total() + $total_tax;
     526                $cart->set_total( max( 0, round( $total, wc_get_price_decimals() ) ) );
     527        }
     528
     529        /**
     530         * The taxes answered for each sent line or fee, by its request index: the reply's `lines` or `fees` rows that carry an
     531         * `index` and a `taxes` list.
     532         *
     533         * @param array $rows The reply's rows.
     534         * @return array
     535         */
     536        private static function taxes_by_index( $rows ) {
     537                $by_index = array();
     538                foreach ( $rows as $row ) {
     539                        if ( isset( $row['index'] ) && isset( $row['taxes'] ) && is_array( $row['taxes'] ) ) {
     540                                $by_index[ (int) $row['index'] ] = $row['taxes'];
     541                        }
     542                }
     543                return $by_index;
     544        }
     545
     546        /**
     547         * One line's or fee's answered taxes as WooCommerce keeps them: each `tax_total` by its `rate_id`.
     548         *
     549         * @param array $taxes The taxes answered for it.
     550         * @return array
     551         */
     552        private static function taxes_by_rate( $taxes ) {
     553                $by_rate = array();
     554                foreach ( $taxes as $tax ) {
     555                        if ( isset( $tax['rate_id'], $tax['tax_total'] ) ) {
     556                                $by_rate[ (string) $tax['rate_id'] ] = (float) $tax['tax_total'];
     557                        }
     558                }
     559                return $by_rate;
     560        }
     561
     562        /**
     563         * Puts each sent fee's answered taxes on the cart's fee (its own `tax_data` and `tax`, which the order's fee line is built
     564         * from), and returns the cart's fee taxes by rate id: each jurisdiction's fee total answered, plus the taxes WooCommerce
     565         * gave a fee that was not sent (a fee of zero). A negative fee is sent and answered with no taxes, so it carries none of
     566         * its own: its discount is already off the lines' taxes. A reply with no fee answer keeps WooCommerce's own.
     567         *
     568         * @param \WC_Cart $cart               Cart object.
     569         * @param string[] $fee_keys           The sent fees' cart keys, in request order.
     570         * @param array    $reply              The door's reply.
     571         * @param array    $answered_fee_taxes Each jurisdiction's fee total answered, by rate id.
     572         * @return array
     573         */
     574        private function apply_fee_taxes( $cart, $fee_keys, $reply, $answered_fee_taxes ) {
     575                $cart_fees = $this->cart_fees( $cart );
     576                if ( ! empty( $fee_keys ) && ( ! isset( $reply['fees'] ) || ! is_array( $reply['fees'] ) ) ) {
     577                        return method_exists( $cart, 'get_fee_taxes' ) ? (array) $cart->get_fee_taxes() : array();
     578                }
     579                $fees_by_index = self::taxes_by_index( isset( $reply['fees'] ) && is_array( $reply['fees'] ) ? $reply['fees'] : array() );
     580                $fee_taxes     = empty( $fee_keys ) ? array() : $answered_fee_taxes;
     581                $sent          = array();
     582                foreach ( $fee_keys as $index => $fee_key ) {
     583                        if ( ! isset( $cart_fees[ $fee_key ] ) || ! is_object( $cart_fees[ $fee_key ] ) ) {
     584                                continue;
     585                        }
     586                        $taxes                           = self::taxes_by_rate( isset( $fees_by_index[ $index ] ) ? $fees_by_index[ $index ] : array() );
     587                        $cart_fees[ $fee_key ]->tax_data = $taxes;
     588                        $cart_fees[ $fee_key ]->tax      = array_sum( $taxes );
     589                        $sent[ $fee_key ]                = true;
     590                }
     591                foreach ( $cart_fees as $fee_key => $fee ) {
     592                        if ( isset( $sent[ $fee_key ] ) || ! is_object( $fee ) || empty( $fee->tax_data ) || ! is_array( $fee->tax_data ) ) {
     593                                continue;
     594                        }
     595                        foreach ( $fee->tax_data as $rate_id => $amount ) {
     596                                $fee_taxes[ $rate_id ] = ( isset( $fee_taxes[ $rate_id ] ) ? $fee_taxes[ $rate_id ] : 0.0 ) + (float) $amount;
     597                        }
     598                }
     599                return $fee_taxes;
     600        }
     601
     602        /**
     603         * Puts the shipping tax answered on the shipping line of the cart's first package, and none on any other, so it is
     604         * never counted twice (bug book B-281). Decided by the package, so a second pass over the same order decides the same way.
     605         *
     606         * @param \WC_Order_Item_Shipping $item        Shipping line.
     607         * @param string                  $package_key Package key.
     608         * @param array                   $package     Package.
     609         * @param \WC_Order               $order       Order.
     610         */
     611        public function apply_exact_shipping_taxes( $item, $package_key, $package, $order ) {
     612                if ( ! $this->is_tax_calculation_enabled() ) {
     613                        return;
     614                }
     615                $shipping_taxes = $this->session_shipping_taxes();
     616                if ( ! is_array( $shipping_taxes ) ) {
     617                        return;
     618                }
     619                $packages  = WC()->shipping() ? WC()->shipping()->get_packages() : array();
     620                $first_key = empty( $packages ) ? 0 : array_key_first( $packages );
     621                $item->set_taxes( self::shipping_line_taxes( (string) $package_key === (string) $first_key, $shipping_taxes ) );
     622        }
     623
     624        /**
     625         * Check if WonderTax Labs answers this store's checkout tax. Server-driven: on only while WonderTax_Tax_Service
     626         * holds the store's checkout tax.
    165627         *
    166628         * @return bool
    167629         */
    168         private function is_tax_calculation_enabled()
    169         {
    170                 $connected = (bool) get_option('wondertax_connected', false);
    171                 $enabled = (bool) get_option('wondertax_tax_calculation_enabled', false);
    172 
    173                 return $connected && $enabled;
    174         }
    175 
    176         /**
    177          * Build tax request payload
    178          *
    179          * @param array $args Tax calculation arguments.
    180          * @return array
    181          */
    182         private function build_tax_request($args)
    183         {
    184                 // Get cart data
    185                 $cart = WC()->cart;
     630        private function is_tax_calculation_enabled() {
     631                $connected = (bool) get_option( 'wondertax_connected', false );
     632
     633                return $connected && class_exists( 'WonderTax_Tax_Service' ) && WonderTax_Tax_Service::is_taken_over();
     634        }
     635
     636        /**
     637         * Build tax request payload: each line's product (the parent product id, as the order's line names it), its total after
     638         * coupons once WooCommerce has totaled the cart, its tax class and tax status; each fee that is not zero (a negative fee
     639         * is a discount), its total, tax class and tax status; the shipping, whether its method is taxed in WooCommerce (a fact:
     640         * WonderTax Labs taxes it either way, 📗 integration-import · I42), the chosen method of each package; and the store's
     641         * currency.
     642         *
     643         * @param array    $args Tax calculation arguments.
     644         * @param \WC_Cart $cart Cart object.
     645         * @return array { request: array, keys: string[], fee_keys: string[] } - the cart item keys and the sent fees' cart keys,
     646         *               in request order.
     647         */
     648        private function build_tax_request( $args, $cart ) {
    186649                $line_items = array();
    187 
    188                 if ($cart) {
    189                         foreach ($cart->get_cart() as $cart_item) {
    190                                 $product = $cart_item['data'];
    191                                 $line_items[] = array(
    192                                         'product_id' => $product->get_id(),
    193                                         'quantity' => $cart_item['quantity'],
    194                                         'price' => (float) $product->get_price(),
    195                                         'tax_class' => $product->get_tax_class(),
    196                                 );
    197                         }
    198                 }
     650                $keys       = array();
     651
     652                foreach ( $cart->get_cart() as $cart_key => $cart_item ) {
     653                        $product = $cart_item['data'];
     654                        $line    = array(
     655                                'product_id'   => isset( $cart_item['product_id'] ) ? (int) $cart_item['product_id'] : (int) $product->get_id(),
     656                                'variation_id' => isset( $cart_item['variation_id'] ) ? (int) $cart_item['variation_id'] : 0,
     657                                'quantity'     => $cart_item['quantity'],
     658                                'price'        => (float) $product->get_price(),
     659                                'tax_class'    => $product->get_tax_class(),
     660                                'tax_status'   => $product->get_tax_status(),
     661                        );
     662                        // The line's total after its coupons, which is what the order import taxes.
     663                        if ( isset( $cart_item['line_total'] ) ) {
     664                                $line['line_total'] = (float) $cart_item['line_total'];
     665                        }
     666                        $line_items[] = $line;
     667                        $keys[]       = $cart_key;
     668                }
     669
     670                // Each fee that is not zero: one above zero is taxed as the order's import taxes its fee line, and a negative fee (a
     671                // discount) lowers the lines, the charged fees and the shipping as the import lowers them.
     672                $fees      = array();
     673                $fee_keys  = array();
     674                $cart_fees = $this->cart_fees( $cart );
     675                foreach ( $cart_fees as $fee_key => $fee ) {
     676                        if ( ! is_object( $fee ) || ! isset( $fee->total ) || 0.0 === (float) $fee->total ) {
     677                                continue;
     678                        }
     679                        $fees[]     = array(
     680                                // The fee's name: WonderTax Labs classifies a fee by its name, as the order's import does.
     681                                'name'       => isset( $fee->name ) ? (string) $fee->name : '',
     682                                'total'      => (float) $fee->total,
     683                                'tax_class'  => isset( $fee->tax_class ) ? (string) $fee->tax_class : '',
     684                                'tax_status' => ! empty( $fee->taxable ) ? 'taxable' : 'none',
     685                        );
     686                        $fee_keys[] = $fee_key;
     687                }
     688
     689                $shipping = $this->chosen_shipping();
    199690
    200691                return array(
    201                         'country' => $args['country'],
    202                         'state' => $args['state'],
    203                         'postcode' => isset($args['postcode']) ? $args['postcode'] : '',
    204                         'city' => isset($args['city']) ? $args['city'] : '',
    205                         'address_1' => isset($args['address']) ? $args['address'] : '',
    206                         'line_items' => $line_items,
    207                         'shipping_cost' => $cart ? (float) $cart->get_shipping_total() : 0.0,
     692                        'request'  => array(
     693                                'country'          => $args['country'],
     694                                'state'            => $args['state'],
     695                                'postcode'         => isset( $args['postcode'] ) ? $args['postcode'] : '',
     696                                'city'             => isset( $args['city'] ) ? $args['city'] : '',
     697                                'address_1'        => isset( $args['address'] ) ? $args['address'] : '',
     698                                'line_items'       => $line_items,
     699                                'shipping_cost'    => (float) $cart->get_shipping_total(),
     700                                'shipping_taxable' => $shipping['taxable'],
     701                                'shipping_methods' => $shipping['methods'],
     702                                'currency'         => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD',
     703                                'fees'             => $fees,
     704                        ),
     705                        'keys'     => $keys,
     706                        'fee_keys' => $fee_keys,
    208707                );
    209708        }
    210709
    211710        /**
    212          * Call WonderTax Labs tax service
     711         * The chosen shipping rate of each package, as the order's shipping lines will name it (`method_id`, and the rate's
     712         * label as `method_title`), and whether WooCommerce taxes the shipping: not when a chosen method's tax status is "None".
     713         *
     714         * @return array { methods: array, taxable: bool }
     715         */
     716        private function chosen_shipping() {
     717                $methods  = array();
     718                $taxable  = true;
     719                $chosen   = WC()->session ? (array) WC()->session->get( 'chosen_shipping_methods', array() ) : array();
     720                $packages = WC()->shipping() ? WC()->shipping()->get_packages() : array();
     721                foreach ( $chosen as $package_key => $rate_id ) {
     722                        if ( ! isset( $packages[ $package_key ]['rates'][ $rate_id ] ) ) {
     723                                continue;
     724                        }
     725                        $rate      = $packages[ $package_key ]['rates'][ $rate_id ];
     726                        $methods[] = array(
     727                                'method_id'    => (string) $rate->get_method_id(),
     728                                'method_title' => (string) $rate->get_label(),
     729                        );
     730                        $instance  = $rate->get_instance_id() && class_exists( 'WC_Shipping_Zones' )
     731                                ? WC_Shipping_Zones::get_shipping_method( $rate->get_instance_id() )
     732                                : false;
     733                        if ( $instance && isset( $instance->tax_status ) && 'none' === $instance->tax_status ) {
     734                                $taxable = false;
     735                        }
     736                }
     737                return array(
     738                        'methods' => $methods,
     739                        'taxable' => $taxable,
     740                );
     741        }
     742
     743        /**
     744         * The door's reply for this request body, asked once per request.
    213745         *
    214746         * @param array $tax_request Tax request payload.
    215747         * @return array|WP_Error
    216748         */
    217         private function call_tax_service($tax_request)
    218         {
    219                 $backend_url = $this->get_backend_url();
    220                 $webhook_secret = get_option('wondertax_webhook_secret');
    221 
    222                 if (empty($webhook_secret)) {
    223                         return new WP_Error('no_secret', 'Webhook secret not configured');
     749        private function quote( $tax_request ) {
     750                $memo_key = md5( (string) wp_json_encode( $tax_request ) );
     751                if ( ! array_key_exists( $memo_key, $this->quotes ) ) {
     752                        // After a failure the door is skipped for a short while: the store's own rates apply, and no checkout waits.
     753                        if ( get_transient( self::PAUSE_TRANSIENT ) ) {
     754                                return new WP_Error( 'door_paused', 'WonderTax Labs did not answer a moment ago' );
     755                        }
     756                        $reply = $this->call_tax_service( $tax_request );
     757                        if ( is_wp_error( $reply ) && in_array( $reply->get_error_code(), array( 'http_request_failed', 'api_unavailable' ), true ) ) {
     758                                set_transient( self::PAUSE_TRANSIENT, 1, self::PAUSE_SECONDS );
     759                        }
     760                        self::record_door_outcome( $reply );
     761                        $this->quotes[ $memo_key ] = $reply;
     762                }
     763                return $this->quotes[ $memo_key ];
     764        }
     765
     766        /**
     767         * Call WonderTax Labs tax service
     768         *
     769         * @param array $tax_request Tax request payload.
     770         * @return array|WP_Error
     771         */
     772        private function call_tax_service( $tax_request ) {
     773                $backend_url    = WONDERTAX_BACKEND_URL;
     774                $webhook_secret = get_option( 'wondertax_webhook_secret' );
     775
     776                if ( empty( $webhook_secret ) ) {
     777                        return new WP_Error( 'no_secret', 'Webhook secret not configured' );
    224778                }
    225779
    226780                // Build request body
    227                 $body = wp_json_encode($tax_request);
     781                $body = wp_json_encode( $tax_request );
    228782
    229783                // Sign request with webhook secret
    230                 $signature = $this->generate_signature($body, $webhook_secret);
    231 
    232                 // Make API request
     784                $signature = $this->generate_signature( $body, $webhook_secret );
     785
     786                // Make API request. The server finds the store by its source and requires a topic beside the signature.
    233787                $response = wp_remote_post(
    234788                        $backend_url . '/api/woocommerce/tax-service',
    235789                        array(
    236790                                'headers' => array(
    237                                         'Content-Type' => 'application/json',
     791                                        'Content-Type'           => 'application/json',
     792                                        'X-WC-Webhook-Source'    => get_option( 'wondertax_site_url', get_site_url() ),
     793                                        'X-WC-Webhook-Topic'     => 'tax.calculate',
    238794                                        'X-WC-Webhook-Signature' => $signature,
    239795                                ),
    240                                 'body' => $body,
    241                                 'timeout' => 10,
     796                                'body'    => $body,
     797                                'timeout' => self::TIMEOUT,
    242798                        )
    243799                );
    244800
    245                 if (is_wp_error($response)) {
    246                         return $response;
    247                 }
    248 
    249                 $response_code = wp_remote_retrieve_response_code($response);
    250                 if (200 !== $response_code) {
    251                         return new WP_Error(
    252                                 'api_error',
    253                                 sprintf('API returned status %d', $response_code)
    254                         );
    255                 }
    256 
    257                 $response_body = wp_remote_retrieve_body($response);
    258                 return json_decode($response_body, true);
     801                if ( is_wp_error( $response ) ) {
     802                        // No reply (a timeout, a refused connection): a door failure.
     803                        return new WP_Error( 'http_request_failed', $response->get_error_message() );
     804                }
     805
     806                $response_code = (int) wp_remote_retrieve_response_code( $response );
     807                if ( $response_code >= 500 ) {
     808                        return new WP_Error( 'api_unavailable', sprintf( 'API returned status %d', $response_code ) );
     809                }
     810                if ( 200 !== $response_code ) {
     811                        // A refusal names its reason (`refused.message`): it is kept for the store managers' notice.
     812                        $refusal = json_decode( (string) wp_remote_retrieve_body( $response ), true );
     813                        $reason  = is_array( $refusal ) && isset( $refusal['refused']['message'] ) && is_string( $refusal['refused']['message'] )
     814                                ? $refusal['refused']['message']
     815                                : sprintf( 'API returned status %d', $response_code );
     816                        // A refusal of the store (401, 403, 404: its signature, its connection, the tax service off) holds for every
     817                        // checkout; any other is about this one cart (an address, a request it could not read), and is not the store's.
     818                        $store_wide = in_array( $response_code, array( 401, 403, 404 ), true );
     819                        return new WP_Error( $store_wide ? 'api_error' : 'cart_refused', $reason );
     820                }
     821
     822                $response_body = wp_remote_retrieve_body( $response );
     823                $decoded       = json_decode( $response_body, true );
     824                if ( ! is_array( $decoded ) ) {
     825                        return new WP_Error( 'api_error', 'API returned an unreadable answer' );
     826                }
     827                return $decoded;
    259828        }
    260829
    … …  
    266835         * @return string
    267836         */
    268         private function generate_signature($body, $secret)
    269         {
    270                 return base64_encode(hash_hmac('sha256', $body, $secret, true));
    271         }
    272 
    273         /**
    274          * Parse tax response from WonderTax Labs
    275          *
    276          * @param array $tax_response Tax response from API.
    277          * @param array $args Original tax calculation arguments.
    278          * @return array WooCommerce tax rates.
    279          */
    280         private function parse_tax_response($tax_response, $args)
    281         {
    282                 if (empty($tax_response['taxes']) || !is_array($tax_response['taxes'])) {
    283                         return array();
    284                 }
    285 
    286                 $rates = array();
    287 
    288                 foreach ($tax_response['taxes'] as $index => $tax) {
    289                         $rate_id = isset($tax['rate_id']) ? $tax['rate_id'] : 'wondertax_' . $index;
    290                         $label = isset($tax['label']) ? $tax['label'] : 'Sales Tax';
    291                         $rate_percent = isset($tax['rate']) ? (float) $tax['rate'] : 0.0;
    292 
    293                         // Convert to WooCommerce rate format
    294                         $rates[$rate_id] = array(
    295                                 'rate' => $rate_percent,
    296                                 'label' => $label,
    297                                 'shipping' => 'yes',
    298                                 'compound' => isset($tax['compound']) && $tax['compound'] ? 'yes' : 'no',
    299                         );
    300                 }
    301 
    302                 return $rates;
    303         }
    304 
    305         /**
    306          * Get backend URL
    307          *
     837        private function generate_signature( $body, $secret ) {
     838                return base64_encode( hash_hmac( 'sha256', $body, $secret, true ) );
     839        }
     840
     841        /**
     842         * Counts the door's consecutive failures — a refusal of the store or no reply, each leaving the store's own rates at
     843         * checkout — and clears the count on an answered checkout. ⭐ A refusal of one cart (`cart_refused`: one buyer's address)
     844         * is not the store's failure, and is not counted. ⛔ Never a give-back: what follows a run of failures is for people to
     845         * decide.
     846         *
     847         * @param array|WP_Error $reply The door's reply.
     848         */
     849        private static function record_door_outcome( $reply ) {
     850                if ( ! is_wp_error( $reply ) ) {
     851                        if ( is_array( $reply ) && isset( $reply['lines'] ) && false !== get_option( self::FAILURES_OPTION, false ) ) {
     852                                delete_option( self::FAILURES_OPTION );
     853                        }
     854                        return;
     855                }
     856                if ( in_array( $reply->get_error_code(), array( 'no_secret', 'cart_refused' ), true ) ) {
     857                        return;
     858                }
     859                $failures = get_option( self::FAILURES_OPTION, array() );
     860                $count    = is_array( $failures ) && isset( $failures['count'] ) ? (int) $failures['count'] : 0;
     861                update_option(
     862                        self::FAILURES_OPTION,
     863                        array(
     864                                'count'  => $count + 1,
     865                                'reason' => $reply->get_error_message(),
     866                                'at'     => time(),
     867                        ),
     868                        false
     869                );
     870        }
     871
     872        /**
     873         * ⭐ THE STORE'S MANAGERS ARE TOLD when WonderTax Labs has failed to answer several checkout tax requests in a row (a
     874         * request is any cart totaling the door is asked for, not only an order): the store's own WooCommerce rates applied to
     875         * them. WonderTax Labs is told too, by its own records of each refusal; nothing is switched back automatically.
     876         */
     877        public static function render_door_failure_notice() {
     878                if ( ! current_user_can( 'manage_woocommerce' ) ) {
     879                        return;
     880                }
     881                $failures = get_option( self::FAILURES_OPTION, array() );
     882                if ( ! is_array( $failures ) || (int) ( isset( $failures['count'] ) ? $failures['count'] : 0 ) < self::FAILURES_NOTICE_AT ) {
     883                        return;
     884                }
     885                ?>
     886                <div class="notice notice-warning">
     887                        <p>
     888                                <strong><?php esc_html_e( 'WonderTax Labs: Audita™', 'wondertax-labs-audita' ); ?></strong>
     889                                <?php
     890                                printf(
     891                                        /* translators: 1: number of checkout tax requests, 2: the last reason given */
     892                                        esc_html__( 'WonderTax Labs did not answer the last %1$d checkout tax requests, so your store\'s own WooCommerce tax rates applied to them. The last reason: %2$s', 'wondertax-labs-audita' ),
     893                                        absint( $failures['count'] ),
     894                                        esc_html( isset( $failures['reason'] ) ? (string) $failures['reason'] : '' )
     895                                );
     896                                ?>
     897                                <a href="mailto:service@wonder.tax"><?php esc_html_e( 'Contact WonderTax Labs', 'wondertax-labs-audita' ); ?></a>
     898                        </p>
     899                </div>
     900                <?php
     901        }
     902
     903        /**
     904         * Keeps the label of each rate this answer names, by its rate id, for the order's tax lines (answered_rate_label): only
     905         * this answer's, and never for a rate id that also names one of the store's own tax rates, whose label stays the store's.
     906         *
     907         * @param array $reply The door's reply.
     908         */
     909        private function remember_rate_labels( $reply ) {
     910                $labels = array();
     911                if ( isset( $reply['taxes'] ) && is_array( $reply['taxes'] ) ) {
     912                        foreach ( $reply['taxes'] as $tax ) {
     913                                if ( ! isset( $tax['rate_id'], $tax['label'] ) || ! is_string( $tax['label'] ) || '' === $tax['label'] ) {
     914                                        continue;
     915                                }
     916                                $rate_id = (string) $tax['rate_id'];
     917                                if ( ! self::names_store_rate( $rate_id ) ) {
     918                                        $labels[ $rate_id ] = $tax['label'];
     919                                }
     920                        }
     921                }
     922                $this->set_session_rate_labels( $labels );
     923        }
     924
     925        /**
     926         * Does this rate id also name one of the store's own WooCommerce tax rates? Those ids are whole numbers, and so are many
     927         * of the jurisdiction codes WonderTax Labs answers with.
     928         *
     929         * @param string $rate_id The rate id.
     930         * @return bool
     931         */
     932        private static function names_store_rate( $rate_id ) {
     933                if ( ! preg_match( '/^\d+$/', $rate_id ) ) {
     934                        return false;
     935                }
     936                if ( ! class_exists( 'WC_Tax' ) || ! method_exists( 'WC_Tax', '_get_tax_rate' ) ) {
     937                        // Unable to tell: never relabel a rate the store may own.
     938                        return true;
     939                }
     940                return ! empty( WC_Tax::_get_tax_rate( (int) $rate_id ) );
     941        }
     942
     943        /**
     944         * Keeps the rate labels of the answer the cart carries now in the session, when there is one; an empty set clears them.
     945         *
     946         * @param array $labels The labels, by rate id.
     947         */
     948        private function set_session_rate_labels( $labels ) {
     949                if ( ! WC()->session ) {
     950                        return;
     951                }
     952                if ( empty( $labels ) && empty( WC()->session->get( self::RATE_LABELS_SESSION ) ) ) {
     953                        return;
     954                }
     955                WC()->session->set( self::RATE_LABELS_SESSION, $labels );
     956        }
     957
     958        /**
     959         * The label of a rate WonderTax Labs answered — its jurisdiction — where WooCommerce, not knowing our rate ids, would
     960         * name it "Tax".
     961         *
     962         * @param string     $label   The label WooCommerce found.
     963         * @param string|int $rate_id The rate id.
    308964         * @return string
    309965         */
    310         private function get_backend_url()
    311         {
    312                 return 'https://app.wonder.tax';
     966        public function answered_rate_label( $label, $rate_id ) {
     967                if ( ! function_exists( 'WC' ) || ! WC()->session ) {
     968                        return $label;
     969                }
     970                $labels = (array) WC()->session->get( self::RATE_LABELS_SESSION, array() );
     971                return isset( $labels[ (string) $rate_id ] ) ? (string) $labels[ (string) $rate_id ] : $label;
    313972        }
    314973}
  • wondertax-labs-audita/tags/1.4.1/readme.txt

    r3713774 r3814612  
    1 === WonderTax Labs: Audita ===
     1=== WonderTax Labs: Audita™ ===
    22Contributors: wondertaxlabs
    33Tags: woocommerce, tax, sales tax, tax compliance, automation
    … …  
    55Tested up to: 7.0
    66Requires PHP: 8.0
    7 Stable tag: 1.3.7
     7Stable tag: 1.4.1
    88License: GPLv3 or later
    99License URI: https://www.gnu.org/licenses/gpl-3.0.html
    1010
    11 Connect your WooCommerce store to WonderTax Labs for automated zero-cost and zero-risk sales tax auditing.
     11Connect your WooCommerce store to WonderTax Labs: Audita™, which audits the sales tax your store charges at zero cost and zero risk.
    1212
    1313== Description ==
    1414
    15 **Automate Your Sales Tax Compliance**
    16 
    17 WonderTax Labs: Audita seamlessly integrates your WooCommerce store with WonderTax Labs for automated sales tax tracking, compliance, and real-time tax calculation at checkout.
     15**Audit the Sales Tax Your Store Charges**
     16
     17WonderTax Labs: Audita™ feeds your WooCommerce orders to WonderTax Labs Audita™, which audits the sales tax your store charges on every order against the tax each order owes.
    1818
    1919### Features
    2020
    21 * **Real-Time Tax Calculation** - Accurate sales tax rates calculated during checkout based on customer location
     21* **Sales Tax Auditing** - Every order is audited by Audita™: the tax your store charged against the tax the order owes
    2222* **Block Checkout Support** - Full compatibility with WooCommerce Cart and Checkout Blocks
    23 * **Automatic Order Sync** - All orders automatically synced to WonderTax Labs for tax compliance tracking
     23* **Automatic Order Sync** - All orders automatically synced to WonderTax Labs Audita™ for auditing
    2424* **Multi-Jurisdiction Support** - Handles complex tax scenarios across all US states and jurisdictions
    2525* **Historical Order Import** - Import and analyze past orders for comprehensive tax compliance
    2626* **Secure Integration** - Enterprise-grade encryption for all credentials and data transmission
    27 * **Easy Setup** - Simple OAuth connection process with minimal configuration
     27* **Easy Setup** - Connect from your WordPress admin in a few clicks
     28* **Checkout Tax with Reporta™** - With a Reporta™ account, WonderTax Labs answers your checkout tax (see External Services)
    2829
    2930### How It Works
    3031
    31321. **Install & Connect** - Install the plugin and connect your store to WonderTax Labs
    32 2. **Enable Tax Calculation** - Optionally enable real-time tax calculation at checkout
    33 3. **Automatic Tracking** - All orders are automatically tracked for tax compliance
    34 4. **Stay Compliant** - WonderTax Labs handles the complexity of multi-state tax compliance
     332. **Automatic Auditing** - All orders are automatically fed to Audita™, which audits the tax your store charges
     343. **Stay Compliant** - WonderTax Labs handles the complexity of multi-state tax compliance
    3535
    3636### Requirements
    … …  
    4444### Privacy & Security
    4545
    46 This plugin connects to WonderTax Labs (app.wonder.tax) to provide tax calculation and compliance services. When you connect your store:
     46This plugin connects to WonderTax Labs (app.wonder.tax) to provide sales tax auditing and compliance services. When you connect your store:
    4747
    4848* Order data (customer location, product details, amounts) is sent to WonderTax Labs
    … …  
    80802. Log in to your WonderTax Labs account (or create one)
    81813. Authorize the connection
    82 4. Optionally enable real-time tax calculation
    83 5. Done! Your orders will now sync automatically
     824. Done! Your orders will now sync automatically
    8483
    8584== Frequently Asked Questions ==
    … …  
    8988Yes, you need a WonderTax Labs account to use this plugin. You can sign up for free at [app.wonder.tax](https://app.wonder.tax).
    9089
    91 = Does this plugin calculate taxes at checkout? =
    92 
    93 Yes, when enabled, the plugin provides real-time tax calculation during checkout. This feature is optional and can be toggled in the settings.
     90= What does Audita™ audit? =
     91
     92The sales tax your store charges. Every order is compared with the tax it owes, so an error is found before an auditor finds it.
    9493
    9594= Will my historical orders be imported? =
    … …  
    105104Currently, WonderTax Labs focuses on US sales tax compliance. Support for additional countries may be added in the future.
    106105
    107 = Does this replace WooCommerce's built-in tax system? =
    108 
    109 When real-time tax calculation is enabled, WonderTax Labs provides tax rates instead of WooCommerce's built-in system. You can disable this feature at any time to revert to WooCommerce's tax settings.
    110 
    111106= How do I disconnect my store? =
    112107
    113 Navigate to WooCommerce > WonderTax Labs and click "Disconnect Store". This will remove all stored credentials and stop order syncing.
     108Navigate to WooCommerce > WonderTax Labs and click "Disconnect Store". This tells WonderTax Labs to stop importing your orders, removes the webhooks WonderTax Labs registered on your store, deletes the WooCommerce API key the plugin created and the stored credentials, and, if WonderTax Labs answers your checkout tax, puts your own tax settings back. Your transactions already recorded in WonderTax Labs are kept there.
    114109
    115110= Where can I get support? =
    … …  
    119114== Screenshots ==
    120115
    121 1. Settings page - Connected state with tax calculation toggle
     1161. Settings page - Connected state
    1221172. Settings page - Not connected state with features list
    123 3. Real-time tax calculation during checkout
    124118
    125119== Changelog ==
     120
     121= 1.4.1 - 2026-11-13 =
     122* Changed: Connecting no longer sends the site's admin email address to WonderTax Labs; you sign in to WonderTax Labs yourself
     123* Changed: Reconnecting keeps your working connection until WonderTax Labs confirms the new one
     124* Changed: Disconnecting removes the API key the plugin created and the webhooks WonderTax Labs or earlier versions registered, and WonderTax Labs stops importing your orders
     125* Changed: A disconnect that cannot put your own tax settings back right away changes nothing and asks you to try again
     126* Changed: The connection status is read with a signed request
     127* Changed: Each tax line shows the name of its jurisdiction
     128* Changed: Each fee's name is sent with the checkout, so WonderTax Labs can classify it
     129* Changed: The settings page says whether WonderTax Labs answers your checkout tax
     130* Added: A notice when WonderTax Labs has not answered several checkout tax requests in a row (a refusal of one cart, such as an address, does not count); it clears once WonderTax Labs answers again, starts or stops answering your checkout tax, or the store is disconnected
     131* Added: Vertex, Quaderno and Stripe Tax are recognized as other tax engines, checked while WonderTax Labs answers your checkout tax too
     132* Removed: The unused app-started connection flow and the plugin's own webhook registration
     133* Security: Every settings action requires the Manage WooCommerce capability
     134
     135= 1.4.0 - 2026-11-06 =
     136* Changed: Settings sync with your WonderTax Labs account
     137* Changed: Checkout requests carry the line details Audita™ needs
     138* Removed: The manual tax setting
    126139
    127140= 1.3.7 - 2026-09-25 =
    … …  
    191204
    192205= 1.2.4 - 2025-05-07 =
    193 * Changed: Plugin title changed to "WonderTax Labs: Audita" throughout admin UI
    194 * Changed: Menu item and page title updated to "WonderTax Labs: Audita"
     206* Changed: Plugin title changed to "WonderTax Labs: Audita™" throughout admin UI
     207* Changed: Menu item and page title updated to "WonderTax Labs: Audita™"
    195208
    196209= 1.2.3 - 2025-05-07 =
    … …  
    286299== Upgrade Notice ==
    287300
     301= 1.4.1 =
     302Reconnecting is safer, disconnecting stops order imports, and tax lines name their jurisdictions. Recommended for all users.
     303
     304= 1.4.0 =
     305WonderTax Labs: Audita™. Recommended for all users.
     306
    288307= 1.3.6 =
    289308Additional WordPress.org plugin review compliance fixes.
    … …  
    320339
    321340= 1.2.4 =
    322 Plugin title updated to "WonderTax Labs: Audita".
     341Plugin title updated to "WonderTax Labs: Audita™".
    323342
    324343= 1.2.3 =
    … …  
    375394== External Services ==
    376395
    377 This plugin connects to WonderTax Labs (app.wonder.tax) to provide tax calculation and compliance services.
     396This plugin connects to WonderTax Labs (app.wonder.tax) to provide sales tax auditing and compliance services. It contacts that service:
     397
     398* **When you connect your store** — WonderTax Labs fetches from this site, once, with a one-time token, the store's new API credentials and the store's name (offered as the name of a new business); you sign in to WonderTax Labs yourself, and no account is identified or created from this site. The plugin then reads the connection's status with a signed request.
     399* **Each time you open the plugin's settings page** — the plugin reads the connection's status with a signed request and, when it is answered, sends the same signed report as the hourly sync.
     400* **When an order is created, updated or deleted** — WooCommerce delivers the order to WonderTax Labs through the webhooks WonderTax Labs registers on connect.
     401* **Every hour** — the plugin reports its version and the store's tax settings, and reads whether WonderTax Labs answers the store's checkout tax.
     402* **At checkout, only while WonderTax Labs answers your checkout tax (Reporta™)** — the cart's address and its lines, fees and shipping are sent, and the tax answered is applied. While it does, the plugin records your own tax settings, sets the tax basis to the shipping address and keeps "Enable taxes" on; your settings are put back when you disconnect or deactivate the plugin.
     403* **When you open the WonderTax Labs dashboard or switch Live/Test Mode** — a signed link or request.
     404* **When you disconnect or deactivate the plugin** — a signed notice tells WonderTax Labs that the plugin gave your own tax settings back (after a disconnect it also stops importing your orders). A notice WonderTax Labs does not accept is sent again with the hourly sync until it is, after a disconnect as well as once a deactivated plugin is active again.
    378405
    379406**Service URL:** https://app.wonder.tax
    … …  
    388415* Order information (amounts, customer location, product details)
    389416* Store information (name, currency, timezone)
     417* The plugin's version and the store's tax settings (whether taxes are enabled, which address they are based on, whether standard tax rates exist, and whether prices are entered with tax), synced hourly
     418* At checkout, when your WonderTax Labs account requires them, the cart's line details (amounts, tax classes, shipping) and the customer's address
    390419* No payment or sensitive financial data is transmitted
    391420
  • wondertax-labs-audita/tags/1.4.1/uninstall.php

    r3556520 r3814612  
    99
    1010// Exit if accessed directly or if uninstall is not called from WordPress
    11 if (!defined('WP_UNINSTALL_PLUGIN')) {
     11if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    1212        exit;
    1313}
    … …  
    1515global $wpdb;
    1616
     17// The classes name the takeover's options, its cron hook and the door's pause; loading them runs nothing.
     18require_once __DIR__ . '/includes/class-wondertax-tax-service.php';
     19require_once __DIR__ . '/includes/class-wondertax-tax-calc.php';
     20require_once __DIR__ . '/includes/class-wondertax-not-taxable-notice.php';
     21
    1722/**
    1823 * Read values needed for cleanup BEFORE deleting options
    1924 */
    20 $wondertax_api_key_id = get_option('wondertax_api_key_id');
    21 $wondertax_webhook_ids = get_option('wondertax_webhook_ids', array());
     25$wondertax_api_key_id  = get_option( 'wondertax_api_key_id' );
     26$wondertax_webhook_ids = get_option( 'wondertax_webhook_ids', array() );
     27$wondertax_pending     = get_option( 'wondertax_pending_connection', null );
    2228
    2329/**
    2430 * Delete WooCommerce API key created by plugin
    2531 */
    26 if ($wondertax_api_key_id) {
     32if ( $wondertax_api_key_id ) {
    2733        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, uninstall cleanup
    2834        $wpdb->delete(
    2935                $wpdb->prefix . 'woocommerce_api_keys',
    30                 array('key_id' => $wondertax_api_key_id),
    31                 array('%d')
     36                array( 'key_id' => $wondertax_api_key_id ),
     37                array( '%d' )
    3238        );
    3339}
    3440
    3541/**
    36  * Delete all webhooks created by plugin
     42 * Delete the WooCommerce API key of a connect left in progress
    3743 */
    38 if (!empty($wondertax_webhook_ids) && class_exists('WC_Webhook')) {
    39         foreach ($wondertax_webhook_ids as $wondertax_webhook_id) {
    40                 $wondertax_webhook = new WC_Webhook($wondertax_webhook_id);
    41                 if ($wondertax_webhook->get_id()) {
    42                         $wondertax_webhook->delete(true);
     44if ( is_array( $wondertax_pending ) && ! empty( $wondertax_pending['api_key_id'] ) ) {
     45        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, uninstall cleanup
     46        $wpdb->delete(
     47                $wpdb->prefix . 'woocommerce_api_keys',
     48                array( 'key_id' => (int) $wondertax_pending['api_key_id'] ),
     49                array( '%d' )
     50        );
     51}
     52
     53/**
     54 * Delete all webhooks created by earlier versions of the plugin (it registers none now)
     55 */
     56if ( ! empty( $wondertax_webhook_ids ) && class_exists( 'WC_Webhook' ) ) {
     57        foreach ( $wondertax_webhook_ids as $wondertax_webhook_id ) {
     58                $wondertax_webhook = new WC_Webhook( $wondertax_webhook_id );
     59                if ( $wondertax_webhook->get_id() ) {
     60                        $wondertax_webhook->delete( true );
    4361                }
    4462        }
    … …  
    4866 * Clear any scheduled events
    4967 */
    50 wp_clear_scheduled_hook('wondertax_cleanup');
     68wp_clear_scheduled_hook( WonderTax_Tax_Service::CRON_HOOK );
    5169
    5270/**
    5371 * Delete all plugin options (after cleanup is complete)
    5472 */
    55 $wondertax_options = array(
    56         'wondertax_version',
    57         'wondertax_connected',
    58         'wondertax_consumer_key',
    59         'wondertax_consumer_secret',
    60         'wondertax_webhook_secret',
    61         'wondertax_site_url',
    62         'wondertax_tax_calculation_enabled',
    63         'wondertax_webhook_ids',
    64         'wondertax_api_key_id',
    65         'wondertax_dev_backend_url',
    66         'wondertax_install_secret',
     73$wondertax_options = array_merge(
     74        array(
     75                'wondertax_version',
     76                'wondertax_connected',
     77                'wondertax_consumer_key',
     78                'wondertax_consumer_secret',
     79                'wondertax_webhook_secret',
     80                'wondertax_site_url',
     81                // No longer read or written; a site upgraded from a release with the tax toggle can still hold the row.
     82                'wondertax_tax_calculation_enabled',
     83                'wondertax_webhook_ids',
     84                'wondertax_api_key_id',
     85                'wondertax_install_secret',
     86                'wondertax_pending_connection',
     87                'wondertax_door_failures',
     88        ),
     89        WonderTax_Tax_Service::OPTIONS
    6790);
    6891
    69 foreach ($wondertax_options as $wondertax_option) {
    70         delete_option($wondertax_option);
     92foreach ( $wondertax_options as $wondertax_option ) {
     93        delete_option( $wondertax_option );
    7194}
     95delete_transient( WonderTax_Tax_Calc::PAUSE_TRANSIENT );
     96delete_transient( WonderTax_Not_Taxable_Notice::CACHE_TRANSIENT );
    7297
    7398/**
  • wondertax-labs-audita/tags/1.4.1/wondertax-labs-audita.php

    r3713774 r3814612  
    11<?php
    22/**
    3  * Plugin Name: WonderTax Labs: Audita
     3 * Plugin Name: WonderTax Labs: Audita™
    44 * Plugin URI: https://app.wonder.tax/integrations/woocommerce
    5  * Description: Connect your WooCommerce store to WonderTax Labs for automated zero-cost and zero-risk sales tax auditing. Handles OAuth setup, webhook registration, and tax service integration with Live/Test Mode support. Includes easy access to WonderTax Labs App.
    6  * Version: 1.3.7
     5 * Description: Connect your WooCommerce store to WonderTax Labs: Audita™, which audits the sales tax your store charges at zero cost and zero risk. Imports your orders with Live/Test Mode support, and with Reporta™ answers your checkout tax. Includes easy access to the WonderTax Labs app.
     6 * Version: 1.4.1
    77 * Author: WonderTax Labs
    88 * Author URI: https://app.wonder.tax
    … …  
    2424
    2525// Define plugin constants
    26 define('WONDERTAX_VERSION', '1.3.7');
     26define('WONDERTAX_VERSION', '1.4.1');
     27define('WONDERTAX_BACKEND_URL', 'https://app.wonder.tax');
    2728define('WONDERTAX_PLUGIN_DIR', plugin_dir_path(__FILE__));
    2829define('WONDERTAX_PLUGIN_URL', plugin_dir_url(__FILE__));
    … …  
    6465        <div class="notice notice-error">
    6566                <p>
    66                         <strong><?php esc_html_e('WonderTax Labs: Audita', 'wondertax-labs-audita'); ?></strong>
     67                        <strong><?php esc_html_e('WonderTax Labs: Audita™', 'wondertax-labs-audita'); ?></strong>
    6768                        <?php esc_html_e('requires WooCommerce to be installed and active.', 'wondertax-labs-audita'); ?>
    6869                        <a href="<?php echo esc_url(admin_url('plugin-install.php?s=woocommerce&tab=search&type=term')); ?>">
    … …  
    8283        <div class="notice notice-error">
    8384                <p>
    84                         <strong><?php esc_html_e('WonderTax Labs: Audita', 'wondertax-labs-audita'); ?></strong>
     85                        <strong><?php esc_html_e('WonderTax Labs: Audita™', 'wondertax-labs-audita'); ?></strong>
    8586                        <?php
    8687                        printf(
    … …  
    219220        // Load plugin classes
    220221        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-admin.php';
    221         require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-oauth.php';
    222         require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-webhooks.php';
     222        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-tax-service.php';
    223223        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-tax-calc.php';
     224        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-not-taxable-notice.php';
    224225
    225226        // Initialize components
    226227        WonderTax_Admin::get_instance();
    227         WonderTax_OAuth::get_instance();
    228         WonderTax_Webhooks::get_instance();
    229228        WonderTax_Tax_Calc::get_instance();
     229
     230        // A checkout WonderTax Labs keeps failing to answer is named to the store's managers (the store charged its own rates).
     231        add_action('admin_notices', array('WonderTax_Tax_Calc', 'render_door_failure_notice'));
     232
     233        // The products WooCommerce marks not taxable, which WonderTax Labs taxes, named in the WordPress admin
     234        WonderTax_Not_Taxable_Notice::register_hooks();
    230235
    231236        // Register REST API endpoint for token exchange
    232237        add_action('rest_api_init', 'wondertax_register_token_exchange_endpoint');
     238
     239        // Hourly sync of the store's checkout tax setting with WonderTax Labs. Scheduled here as well as on activation,
     240        // because an update does not run the activation hook.
     241        add_action(WonderTax_Tax_Service::CRON_HOOK, 'wondertax_run_tax_service_sync');
     242        WonderTax_Tax_Service::register_hooks();
     243        if (!wp_next_scheduled(WonderTax_Tax_Service::CRON_HOOK)) {
     244                wp_schedule_event(time() + MINUTE_IN_SECONDS, 'hourly', WonderTax_Tax_Service::CRON_HOOK);
     245        }
    233246}
    234247add_action('plugins_loaded', 'wondertax_init');
     248
     249/**
     250 * Hourly WP-cron: reads the tax service WonderTax Labs asks for and moves the store to it.
     251 */
     252function wondertax_run_tax_service_sync()
     253{
     254        if (class_exists('WonderTax_Tax_Service')) {
     255                WonderTax_Tax_Service::sync();
     256        }
     257}
    235258
    236259/**
    … …  
    253276 *
    254277 * Security model:
    255  * - Token is one-time use, 5-minute expiry
     278 * - Token is one-time use, 15-minute expiry: WonderTax Labs redeems it as the browser lands (WonderTax_Admin::TOKEN_TTL)
    256279 * - Exchange happens server-to-server (not via browser)
    257  * - Install secret is returned so WonderTax can verify future webhooks
     280 * - The connection's install secret is returned so WonderTax Labs can verify the signed link and every later signed call.
     281 *   A connect in progress serves its PENDING secret: the store's working connection keeps its own until WonderTax Labs
     282 *   confirms the new one (WonderTax_Admin::confirm_pending_connection).
    258283 *
    259284 * @param WP_REST_Request $request The REST request
    … …  
    299324        delete_transient($transient_key);
    300325
    301         // Return credentials along with install secret for future HMAC verification
    302         // This is secure because:
     326        // Return credentials along with the connection's install secret for HMAC verification. This is secure because:
    303327        // 1. Exchange happens server-to-server over HTTPS
    304328        // 2. Token was one-time use and is now deleted
    305         // 3. Install secret allows WonderTax to verify future webhook signatures
     329        // 3. The install secret lets WonderTax Labs verify this connect link and every later signed call
     330        $install_secret = isset($credentials['install_secret']) ? (string) $credentials['install_secret'] : wondertax_get_install_secret();
     331        unset($credentials['install_secret']);
    306332        return new WP_REST_Response(array(
    307333                'success' => true,
    308334                'credentials' => $credentials,
    309                 'install_secret' => wondertax_get_install_secret(),
     335                'install_secret' => $install_secret,
    310336        ), 200);
    311337}
    … …  
    320346                deactivate_plugins(WONDERTAX_PLUGIN_BASENAME);
    321347                wp_die(
    322                         esc_html__('WonderTax Labs: Audita requires PHP 8.0 or higher.', 'wondertax-labs-audita'),
     348                        esc_html__('WonderTax Labs: Audita™ requires PHP 8.0 or higher.', 'wondertax-labs-audita'),
    323349                        esc_html__('Plugin Activation Error', 'wondertax-labs-audita'),
    324350                        array('back_link' => true)
    … …  
    329355                deactivate_plugins(WONDERTAX_PLUGIN_BASENAME);
    330356                wp_die(
    331                         esc_html__('WonderTax Labs: Audita requires WooCommerce to be installed and active.', 'wondertax-labs-audita'),
     357                        esc_html__('WonderTax Labs: Audita™ requires WooCommerce to be installed and active.', 'wondertax-labs-audita'),
    332358                        esc_html__('Plugin Activation Error', 'wondertax-labs-audita'),
    333359                        array('back_link' => true)
    … …  
    337363        // Set default options
    338364        add_option('wondertax_version', WONDERTAX_VERSION);
    339         add_option('wondertax_tax_calculation_enabled', false);
    340365
    341366        // Set flag to redirect to settings page after activation (store user ID for security)
    … …  
    393418function wondertax_deactivate()
    394419{
    395         // Clean up scheduled events if any
    396         wp_clear_scheduled_hook('wondertax_cleanup');
     420        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-tax-service.php';
     421
     422        // Clean up scheduled events
     423        wp_clear_scheduled_hook(WonderTax_Tax_Service::CRON_HOOK);
     424
     425        // A deactivated plugin answers no checkout, so the store's own tax setting is put back now, and WonderTax Labs is
     426        // told (it keeps its record of that setting until the plugin is back).
     427        WonderTax_Tax_Service::give_back('deactivated');
    397428}
    398429register_deactivation_hook(__FILE__, 'wondertax_deactivate');
  • wondertax-labs-audita/trunk/README.md

    r3713776 r3814612  
    1 # WonderTax Labs: Audita
    2 
    3 **Version:** 1.3.7
     1# WonderTax Labs: Audita™
     2
     3**Version:** 1.4.1
    44
    55Your zero-cost, zero-risk sales tax audit agent for every WooCommerce transaction. Connect your store to WonderTax Labs in minutes — your always-on tax auditor that catches errors before auditors do.
    … …  
    77## Features
    88
    9 - **OAuth Integration** - Secure connection between WooCommerce and WonderTax Labs
     9- **Secure Connection** - A token exchange and signed requests between WooCommerce and WonderTax Labs
    1010- **Open WonderTax Labs** - One-click access to your tax compliance dashboard directly from WordPress admin
    1111- **Auto-Update Support** - One-click plugin upgrades directly from WordPress admin when new versions are available
    12 - **Automatic Order Sync** - Webhooks for order.created, order.updated, order.deleted events
     12- **Automatic Order Sync** - Order webhooks (order.created, order.updated, order.deleted) that WonderTax Labs registers on connect
    1313- **Live/Test Mode Indicator** - Visual badges showing API key mode (Test or Live)
    1414- **Transaction Activity Stats** - View recent transaction counts right in WordPress admin
    … …  
    2929### For Users
    3030
    31 1. Download the plugin ZIP file [wondertax-labs-audita-v1.3.7.zip](https://app.wonder.tax/wondertax-labs-audita-v1.3.7.zip)
     311. Download the plugin ZIP file [wondertax-labs-audita-v1.4.1.zip](https://app.wonder.tax/wondertax-labs-audita-v1.4.1.zip)
    32322. In WordPress admin, go to Plugins > Add New > Upload Plugin
    33333. Upload the ZIP file and activate
    34 4. Navigate to WooCommerce > WonderTax Labs: Audita
     344. Navigate to WooCommerce > WonderTax Labs: Audita™
    35355. Click "Connect to WonderTax Labs"
    36 6. **That's it!** Your WonderTax Labs account is created automatically from your WordPress admin email
     366. **Sign in to WonderTax Labs** (or create an account) when asked: the store is bound only to a business you
     37   administer, and no account is identified or created from the WordPress site
    3738
    3839If you already have a WonderTax Labs account with multiple businesses, you'll be asked to choose which entity to connect, or create a new one.
    39 
    40 ### For Developers
    41 
    42 Clone this repository into your WordPress plugins directory:
    43 
    44 ```bash
    45 cd wp-content/plugins/
    46 git clone https://github.com/WonderTax-Labs-Red/diablo.git
    47 cd diablo/wondertax-labs-audita
    48 ```
    49 
    50 Or symlink during development:
    51 
    52 ```bash
    53 cd wp-content/plugins/
    54 ln -s /path/to/diablo/wondertax-labs-audita wondertax-labs-audita
    55 ```
    5640
    5741## Architecture
    … …  
    6448├── includes/
    6549│   ├── class-wondertax-admin.php    # Admin settings page UI
    66 │   ├── class-wondertax-oauth.php    # OAuth credential generation
    67 │   ├── class-wondertax-webhooks.php # Webhook registration
    68 │   ├── class-wondertax-tax-calc.php # Real-time tax calculation
    69 │   └── class-wondertax-updater.php  # Auto-update functionality
     50│   ├── class-wondertax-not-taxable-notice.php # Names the products WooCommerce marks not taxable
     51│   ├── class-wondertax-tax-service.php # Holds the checkout tax setting WonderTax Labs names (hourly sync + ack)
     52│   └── class-wondertax-tax-calc.php # Applies the checkout tax WonderTax Labs answers, when it holds the setting
    7053├── assets/
    7154│   └── css/admin.css                # Admin page styles
    … …  
    7760### Data Flow
    7861
    79 1. **OAuth Connection**
    80    - User clicks "Connect" in WordPress admin
    81    - Plugin generates WooCommerce REST API credentials
    82    - Credentials sent to SvelteKit backend via callback URL
    83    - Backend encrypts and stores credentials in database
    84 
    85 2. **Webhook Registration**
    86    - On successful connection, plugin creates WC_Webhook instances
    87    - Webhooks configured for: order.created, order.updated, order.deleted
    88    - Webhook secret shared with backend for signature verification
    89 
    90 3. **Real-Time Tax Calculation**
    91    - Classic Checkout: Hooks into `woocommerce_find_rates` filter
    92    - Block Checkout: Hooks into Store API via `woocommerce_store_api_cart_update_customer_from_request`
    93    - Builds tax request from cart data and customer address
    94    - Signs request with webhook secret
    95    - Calls SvelteKit `/api/woocommerce/tax-service` endpoint
    96    - Returns tax rates in WooCommerce format
     621. **Connection**
     63   - A store manager clicks "Connect" in WordPress admin
     64   - The plugin creates new WooCommerce REST API credentials, a webhook secret and an install secret, kept as a connect in
     65     progress (`wondertax_pending_connection`): the working connection and its API key are untouched
     66   - The browser goes to `/api/integrations/woocommerce/connect` with a one-time token, signed with the new install secret;
     67     WonderTax Labs fetches the credentials server to server from `/wp-json/wondertax/v1/credentials`
     68   - Once the store is bound in WonderTax Labs, the plugin promotes the connect in progress only when a status read signed
     69     with its new install secret is answered (on the return to WordPress, on the settings page, or on the hourly sync);
     70     then the previous API key is deleted. A connect not confirmed within an hour is discarded. ⚠️ Until it is promoted,
     71     checkout requests are still signed with the working connection's webhook secret, which WonderTax Labs replaced at the
     72     bind: a held store's checkouts are refused (its own rates apply) until then — at most until the hourly sync
     73
     742. **Webhooks**
     75   - WonderTax Labs registers the order webhooks itself on connect, through the REST API, with the stored webhook secret,
     76     and repairs and dedupes its own on a reconnect. The plugin registers none. A disconnect deletes, before it removes the
     77     API key, the ones WonderTax Labs registered (delivering to its order routes on `WONDERTAX_BACKEND_URL`), since WonderTax
     78     Labs' own cleanup reads the store with that key; a disconnect and an uninstall delete any that earlier versions
     79     registered (`wondertax_webhook_ids`)
     80
     813. **Checkout Tax Setting (server-driven)**
     82   - Hourly WP-cron (`wondertax_tax_service_sync`) and each admin page load post a signed `report` and read `taxService` from its signed reply (never from the status read). A refused or failed ack is read again and retried once
     83   - `desired: on`: records the store's own setting (`woocommerce_calc_taxes`, `woocommerce_tax_based_on`, whether standard rate tables exist) under a short lock, switches `woocommerce_tax_based_on` to `shipping`, sets `woocommerce_calc_taxes` ("Enable taxes") to `yes`, and acks `on` with that record. While the setting is held, WooCommerce's taxes stay on (`wc_tax_enabled`) even if the merchant turns "Enable taxes" off, since turning it off does not exempt a sale. An active WooCommerce Tax, TaxJar, Avalara, Vertex, Quaderno or Stripe Tax plugin (WooCommerce Shipping & Tax only while its taxes are on) is acked as a `conflict` instead, and nothing is switched — checked on every sync, so one found while the setting is held gives the store back first. A store whose prices are entered with tax is acked `unsupported` and never switched, and one that changes to it while held is given back once the save completes (flagged by `update_option_woocommerce_prices_include_tax`, run on `woocommerce_settings_saved` or `shutdown`, under the lock; `tax_based_on` is put back only while it is still `shipping`)
     84   - `desired: off` after a takeover: puts back the recorded setting and acks `off`
     85   - Deactivation and disconnect put back the recorded setting and ack `released` (`deactivated` or `disconnected`); one not accepted is acked again until it is (hourly after a disconnect, after a reactivation for a deactivation). A disconnect that cannot put the setting back (another request holds the lock) changes nothing and asks the store manager to try again. A confirmed connect drops a `released` ack WonderTax Labs never heard; until then it is kept
     86   - A release turns `woocommerce_calc_taxes` back to the recorded value only while it is still `yes` (the takeover's value). When it still differs from what was recorded at the takeover, a WordPress admin notice asks a store manager (`manage_woocommerce`) once whether to keep the current setting or turn it back ("Keep it on" / "Turn it off", or the reverse); the actions are nonce-checked admin-post requests. Dismissing keeps the current setting, deactivation keeps it and asks nothing, and a later takeover clears an unanswered question. The answer is sent in the next signed `report` (`release_taxes_answer`); WonderTax Labs records it and changes nothing
     87   - Acks are signed POSTs to `/api/integrations/woocommerce/tax-service/ack` (per-install secret, `site_url|state|timestamp|nonce|payload`)
     88   - While the setting is held, each cart is quoted by the signed `/api/woocommerce/tax-service` (with `X-WC-Webhook-Source`, `X-WC-Webhook-Topic` and `X-WC-Webhook-Signature`), on each line's total after coupons, with the cart's fees and shipping. A negative fee (a discount) is spread over the lines, the charged fees and the shipping exactly as the order's import spreads it, and is never taxed itself. The exact per-line, per-fee, shipping and per-jurisdiction amounts answered are applied (`woocommerce_after_calculate_totals`), and on Block Checkout put on the order's lines. A refusal leaves the store's own rates
    9789
    98904. **Order Webhooks**
    … …  
    116108- Backend performs timing-safe signature comparison
    117109
    118 ### OAuth Flow
    119 
    120 - State parameter uses cryptographically secure random bytes
    121 - One-time use state tokens (deleted after validation)
    122 - State expires after 10 minutes
     110### Signed Requests
     111
     112- The connect link, the dashboard link, the status read, the mode switch and every report are HMAC-SHA256 signed with the
     113  connection's install secret, with a timestamp and a nonce
     114- The connect token is one-time use and expires after an hour
    123115
    124116## Configuration
    … …  
    132124The plugin communicates with these SvelteKit endpoints:
    133125
    134 - `POST /api/woocommerce/auth/callback` - OAuth credential submission
    135 - `POST /api/woocommerce/tax-service` - Real-time tax calculation
    136 - `POST /api/woocommerce/webhooks/order-created` - New order webhook
    137 - `POST /api/woocommerce/webhooks/order-updated` - Updated order webhook
    138 - `POST /api/woocommerce/webhooks/order-deleted` - Deleted order webhook
     126- `GET /api/integrations/woocommerce/connect` - The connect link (signed, one-time token)
     127- `GET /api/integrations/woocommerce/status` - Connection status for the admin page (signed: `site_url|status|timestamp|nonce`)
     128- `GET /api/integrations/woocommerce/open` - The signed "Open WonderTax Labs" link
     129- `POST /api/integrations/woocommerce/mode` - The signed Live/Test Mode switch
     130- `POST /api/integrations/woocommerce/tax-service/ack` - Signed report of the checkout tax setting held; its reply is the setting to hold
     131- `POST /api/woocommerce/tax-service` - Checkout tax quote, while the setting is held
     132- `POST /api/integrations/woocommerce/webhooks/order-*` - The order webhooks WonderTax Labs registers (WooCommerce delivers
     133  them; `/api/woocommerce/webhooks/order-*` still serves webhooks registered by earlier versions)
    139134
    140135## Development
    … …  
    153148Manual testing checklist:
    154149
    155 - [ ] OAuth connection flow
    156 - [ ] Disconnect functionality
    157 - [ ] Real-time tax calculation toggle
    158 - [ ] Webhook registration
     150- [ ] Connect, and a reconnect abandoned midway (the working connection stays)
     151- [ ] Disconnect functionality (WonderTax Labs stops importing; the API key is removed)
     152- [ ] Checkout tax setting sync (takeover, conflict, release)
     153- [ ] The webhooks WonderTax Labs registered appear under WooCommerce > Settings > Advanced > Webhooks
    159154- [ ] Tax calculation during checkout
    160155- [ ] Webhook delivery on order events
    … …  
    1851804. Check error logs for specific error messages
    186181
    187 ### Tax Calculation Not Working
     182### Checkout Tax Not Applied
    188183
    1891841. Verify connection is active (WooCommerce > WonderTax Labs)
    190 2. Verify tax calculation is enabled in settings
     1852. Verify the store holds the setting (option `wondertax_tax_service_state` is `on`)
    1911863. Check address has all required fields (country, state, postcode)
    1921874. Only US addresses are currently supported
  • wondertax-labs-audita/trunk/changelog.txt

    r3713774 r3814612  
    1 *** WonderTax Labs Audita Changelog ***
     1*** WonderTax Labs Audita™ Changelog ***
     2
     32026-11-13 - version 1.4.1
     4* Changed - Connecting no longer sends the site's admin email address to WonderTax Labs; you sign in to WonderTax Labs yourself
     5* Changed - Reconnecting keeps your working connection until WonderTax Labs confirms the new one
     6* Changed - Disconnecting removes the API key the plugin created and the webhooks WonderTax Labs or earlier versions registered, and WonderTax Labs stops importing your orders
     7* Changed - A disconnect that cannot put your own tax settings back right away changes nothing and asks you to try again
     8* Changed - The connection status is read with a signed request
     9* Changed - Each tax line shows the name of its jurisdiction
     10* Changed - Each fee's name is sent with the checkout, so WonderTax Labs can classify it
     11* Changed - The settings page says whether WonderTax Labs answers your checkout tax
     12* Added - A notice when WonderTax Labs has not answered several checkout tax requests in a row (a refusal of one cart, such as an address, does not count); it clears once WonderTax Labs answers again, starts or stops answering your checkout tax, or the store is disconnected
     13* Added - Vertex, Quaderno and Stripe Tax are recognized as other tax engines, checked while WonderTax Labs answers your checkout tax too
     14* Removed - The unused app-started connection flow and the plugin's own webhook registration
     15* Security - Every settings action requires the Manage WooCommerce capability
     16
     172026-11-06 - version 1.4.0
     18* Changed - Settings sync with your WonderTax Labs account
     19* Changed - Checkout requests carry the line details Audita™ needs
     20* Removed - The manual tax setting
    221
    3222026-09-25 - version 1.3.7
    … …  
    6786
    68872025-05-07 - version 1.2.4
    69 * Update - Plugin title changed to "WonderTax Labs: Audita" throughout admin UI
    70 * Update - Menu item and page title updated to "WonderTax Labs: Audita"
     88* Update - Plugin title changed to "WonderTax Labs: Audita™" throughout admin UI
     89* Update - Menu item and page title updated to "WonderTax Labs: Audita™"
    7190
    72912025-05-07 - version 1.2.3
  • wondertax-labs-audita/trunk/includes/class-wondertax-admin.php

    r3713774 r3814612  
    1010
    1111// Exit if accessed directly
    12 if (!defined('ABSPATH')) {
     12if ( ! defined( 'ABSPATH' ) ) {
    1313        exit;
    1414}
    … …  
    1717 * Admin settings class
    1818 */
    19 class WonderTax_Admin
    20 {
     19class WonderTax_Admin {
     20
    2121        /**
    2222         * Singleton instance
    … …  
    2727
    2828        /**
     29         * The option holding a connect in progress: the new credentials, webhook secret, install secret and API key id, kept
     30         * apart from the working connection until WonderTax Labs confirms it (confirm_pending_connection).
     31         */
     32        const PENDING_OPTION = 'wondertax_pending_connection';
     33
     34        /**
     35         * Seconds a connect in progress waits for its confirmation: the connect link's signature window.
     36         */
     37        const PENDING_TTL = HOUR_IN_SECONDS;
     38
     39        /**
     40         * Seconds the one-time credential token can be redeemed: WonderTax Labs redeems it as the browser lands, before anyone
     41         * signs in, so it needs only the redirect's moment, never the connect's whole hour.
     42         */
     43        const TOKEN_TTL = 15 * MINUTE_IN_SECONDS;
     44
     45        /**
     46         * The install secret of the connect in progress whose status read went unanswered in this request, else '': it is read
     47         * once per request, however many steps of a page load ask (confirm_pending_connection).
     48         *
     49         * @var string
     50         */
     51        private static $unconfirmed_secret = '';
     52
     53        /**
    2954         * Get singleton instance
    3055         *
    3156         * @return WonderTax_Admin
    3257         */
    33         public static function get_instance()
    34         {
    35                 if (null === self::$instance) {
     58        public static function get_instance() {
     59                if ( null === self::$instance ) {
    3660                        self::$instance = new self();
    3761                }
    … …  
    4266         * Constructor
    4367         */
    44         private function __construct()
    45         {
    46                 add_action('admin_menu', array($this, 'add_admin_menu'));
    47                 add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    48                 add_action('admin_init', array($this, 'handle_settings_actions'));
    49                 add_action('wp_ajax_wondertax_switch_mode', array($this, 'ajax_switch_mode'));
     68        private function __construct() {
     69                add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
     70                add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
     71                add_action( 'admin_init', array( $this, 'handle_settings_actions' ) );
     72                add_action( 'wp_ajax_wondertax_switch_mode', array( $this, 'ajax_switch_mode' ) );
    5073        }
    5174
    … …  
    5376         * Add admin menu
    5477         */
    55         public function add_admin_menu()
    56         {
     78        public function add_admin_menu() {
    5779                add_submenu_page(
    5880                        'woocommerce',
    59                         __('WonderTax Labs: Audita', 'wondertax-labs-audita'),
    60                         __('WonderTax Labs: Audita', 'wondertax-labs-audita'),
     81                        __( 'WonderTax Labs: Audita™', 'wondertax-labs-audita' ),
     82                        __( 'WonderTax Labs: Audita™', 'wondertax-labs-audita' ),
    6183                        'manage_woocommerce',
    6284                        'wondertax-labs-audita',
    63                         array($this, 'render_admin_page')
     85                        array( $this, 'render_admin_page' )
    6486                );
    6587        }
    … …  
    7092         * @param string $hook Current admin page hook.
    7193         */
    72         public function enqueue_admin_assets($hook)
    73         {
     94        public function enqueue_admin_assets( $hook ) {
    7495                // Only load on our admin page
    75                 if ('woocommerce_page_wondertax-labs-audita' !== $hook) {
     96                if ( 'woocommerce_page_wondertax-labs-audita' !== $hook ) {
    7697                        return;
    7798                }
    … …  
    87108                        'wondertax-admin',
    88109                        WONDERTAX_PLUGIN_URL . 'assets/js/admin.js',
    89                         array('jquery'),
     110                        array( 'jquery' ),
    90111                        WONDERTAX_VERSION,
    91112                        true
    92113                );
    93114
    94                 wp_localize_script('wondertax-admin', 'wondertaxAdmin', array(
    95                         'ajaxUrl' => admin_url('admin-ajax.php'),
    96                         'nonce' => wp_create_nonce('wondertax_switch_mode'),
    97                         'strings' => array(
    98                                 'switching' => __('Switching...', 'wondertax-labs-audita'),
    99                                 'switchToLive' => __('Switch to Live Mode', 'wondertax-labs-audita'),
    100                                 'switchToTest' => __('Switch to Test Mode', 'wondertax-labs-audita'),
    101                                 'error' => __('Failed to switch mode. Please try again.', 'wondertax-labs-audita'),
    102                         ),
    103                 ));
    104         }
    105 
    106         /**
    107          * Handle settings page actions
    108          */
    109         public function handle_settings_actions()
    110         {
     115                wp_localize_script(
     116                        'wondertax-admin',
     117                        'wondertaxAdmin',
     118                        array(
     119                                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
     120                                'nonce'   => wp_create_nonce( 'wondertax_switch_mode' ),
     121                                'strings' => array(
     122                                        'switching'    => __( 'Switching...', 'wondertax-labs-audita' ),
     123                                        'switchToLive' => __( 'Switch to Live Mode', 'wondertax-labs-audita' ),
     124                                        'switchToTest' => __( 'Switch to Test Mode', 'wondertax-labs-audita' ),
     125                                        'error'        => __( 'Failed to switch mode. Please try again.', 'wondertax-labs-audita' ),
     126                                ),
     127                        )
     128                );
     129        }
     130
     131        /**
     132         * Handle settings page actions. ⛔ Every action needs a store manager (`manage_woocommerce`): admin_init runs for any
     133         * signed-in user, before WordPress checks the page's own capability.
     134         */
     135        public function handle_settings_actions() {
    111136                // Check if we're on the settings page
    112                 if (!isset($_GET['page']) || 'wondertax-labs-audita' !== $_GET['page']) {
     137                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The page slug only routes; each action below checks its own nonce.
     138                if ( ! isset( $_GET['page'] ) || 'wondertax-labs-audita' !== $_GET['page'] ) {
    113139                        return;
    114140                }
    115 
    116                 // Handle successful connection return from WonderTax Labs
    117                 if (isset($_GET['connected']) && '1' === $_GET['connected']) {
    118                         // Mark as connected (credentials were stored before redirect)
    119                         update_option('wondertax_connected', true);
    120                         add_settings_error(
    121                                 'wondertax',
    122                                 'connected',
    123                                 __('Successfully connected to WonderTax Labs!', 'wondertax-labs-audita'),
    124                                 'success'
    125                         );
    126                 }
    127 
    128                 // Handle connect action
    129                 if (isset($_GET['action']) && 'connect' === $_GET['action']) {
    130                         // Check if this is from WonderTax Labs app (has state and callback_url)
    131                         // or from the WordPress "Connect" button (has nonce)
    132                         if (isset($_GET['state']) && isset($_GET['callback_url'])) {
    133                                 // WonderTax-initiated flow: store params and show confirmation UI
    134                                 // This prevents CSRF by requiring user to confirm with a WordPress nonce
    135                                 $this->handle_oauth_initiation();
    136                         } else {
    137                                 // WordPress-initiated flow: check nonce and do signed redirect
    138                                 check_admin_referer('wondertax_connect', 'wondertax_nonce');
    139                                 $this->handle_connect();
     141                if ( ! current_user_can( 'manage_woocommerce' ) ) {
     142                        return;
     143                }
     144
     145                // The return from WonderTax Labs after the store was bound. ⛔ The query is never trusted: the connect in progress is
     146                // promoted only when WonderTax Labs answers a status read signed with its new install secret.
     147                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- A return flag only; the signed status read decides.
     148                if ( isset( $_GET['connected'] ) && '1' === $_GET['connected'] ) {
     149                        $confirmed = self::confirm_pending_connection();
     150                        if ( true === $confirmed ) {
     151                                add_settings_error(
     152                                        'wondertax',
     153                                        'connected',
     154                                        __( 'Successfully connected to WonderTax Labs!', 'wondertax-labs-audita' ),
     155                                        'success'
     156                                );
     157                        } elseif ( false === $confirmed ) {
     158                                add_settings_error(
     159                                        'wondertax',
     160                                        'connect_unconfirmed',
     161                                        __( 'WonderTax Labs has not confirmed the connection yet. If you finished connecting in WonderTax Labs, reload this page in a minute; otherwise, click Connect again.', 'wondertax-labs-audita' ),
     162                                        'warning'
     163                                );
    140164                        }
    141165                }
    142166
    143                 // Handle confirmed OAuth connection (after user clicks confirm button with nonce)
    144                 if (isset($_POST['wondertax_confirm_oauth'])) {
    145                         check_admin_referer('wondertax_confirm_oauth', 'wondertax_nonce');
    146                         $this->handle_confirmed_oauth();
     167                // Handle connect action (the Connect button, nonce-protected)
     168                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- check_admin_referer verifies the nonce before anything runs.
     169                if ( isset( $_GET['action'] ) && 'connect' === $_GET['action'] ) {
     170                        check_admin_referer( 'wondertax_connect', 'wondertax_nonce' );
     171                        $this->handle_connect();
    147172                }
    148173
    149174                // Handle disconnect
    150                 if (isset($_POST['wondertax_disconnect']) && check_admin_referer('wondertax_disconnect', 'wondertax_nonce')) {
     175                if ( isset( $_POST['wondertax_disconnect'] ) && check_admin_referer( 'wondertax_disconnect', 'wondertax_nonce' ) ) {
    151176                        $this->handle_disconnect();
    152177                }
    153 
    154                 // Tax calculation toggle disabled - audit only mode
    155                 // if (isset($_POST['wondertax_toggle_tax']) && check_admin_referer('wondertax_toggle_tax', 'wondertax_nonce')) {
    156                 //      $this->handle_tax_toggle();
    157                 // }
    158         }
    159 
    160         /**
    161          * Handle connect action - generates credentials and redirects to WonderTax Labs
    162          * Uses secure token exchange: credentials stored locally, only token sent in URL
    163          */
    164         private function handle_connect()
    165         {
     178        }
     179
     180        /**
     181         * Handle connect action - generates the new connection's credentials and redirects to WonderTax Labs.
     182         * Uses secure token exchange: credentials stored locally, only a token sent in the URL.
     183         *
     184         * ⭐ The new credentials, webhook secret and install secret are kept as a connect IN PROGRESS (PENDING_OPTION): the
     185         * store's working connection — its options and its WooCommerce API key — is untouched until WonderTax Labs confirms the
     186         * new one, so a connect abandoned midway never breaks a working store.
     187         */
     188        private function handle_connect() {
    166189                try {
     190                        // A connect left unfinished before is discarded first (its API key row with it).
     191                        self::discard_pending_connection();
     192
    167193                        // Generate WooCommerce REST API credentials
    168194                        $credentials = $this->generate_api_credentials();
    169195
    170                         // Generate webhook secret
     196                        // Generate webhook secret and this connection's install secret
    171197                        $webhook_secret = $this->generate_webhook_secret();
    172 
    173                         // Store credentials locally (permanent storage)
    174                         update_option('wondertax_consumer_key', $credentials['consumer_key']);
    175                         update_option('wondertax_consumer_secret', $credentials['consumer_secret']);
    176                         update_option('wondertax_webhook_secret', $webhook_secret);
    177                         update_option('wondertax_site_url', get_site_url());
    178 
    179                         // Get admin email and store name for user identification
    180                         $admin_email = get_option('admin_email');
    181                         $store_name = get_bloginfo('name');
     198                        $install_secret = 'wtl_' . bin2hex( random_bytes( 32 ) );
     199                        $site_url       = get_site_url();
     200
     201                        update_option(
     202                                self::PENDING_OPTION,
     203                                array(
     204                                        'consumer_key'    => $credentials['consumer_key'],
     205                                        'consumer_secret' => $credentials['consumer_secret'],
     206                                        'api_key_id'      => $credentials['key_id'],
     207                                        'webhook_secret'  => $webhook_secret,
     208                                        'install_secret'  => $install_secret,
     209                                        'site_url'        => $site_url,
     210                                        'created'         => time(),
     211                                ),
     212                                false
     213                        );
     214
     215                        // ⭐ An unheard released ack is kept until this connect is CONFIRMED (`confirm_pending_connection` deletes it): an
     216                        // abandoned connect must not drop a disconnect WonderTax Labs has yet to hear, and until the new install secret is
     217                        // written the retry is signed with the old one, which can only retire the old installation.
     218
     219                        // The store's name, offered as the name of a new business. No email is sent: a link proves only that the site signed
     220                        // it, so WonderTax Labs never identifies or creates an account from it — the person signs in themselves.
     221                        $store_name = get_bloginfo( 'name' );
    182222
    183223                        // Generate a one-time token for credential exchange
    184                         $connect_token = bin2hex(random_bytes(32));
    185 
    186                         // Store credentials in a transient for token exchange (5 minute expiry)
    187                         // WonderTax Labs backend will call our REST API to fetch these
     224                        $connect_token = bin2hex( random_bytes( 32 ) );
     225
     226                        // Store credentials in a transient for the token exchange. WonderTax Labs backend calls our REST API to fetch
     227                        // these; one hour, the connect link's signature window.
    188228                        $credential_data = array(
    189                                 'site_url' => get_site_url(),
    190                                 'consumer_key' => $credentials['consumer_key'],
     229                                'site_url'        => $site_url,
     230                                'consumer_key'    => $credentials['consumer_key'],
    191231                                'consumer_secret' => $credentials['consumer_secret'],
    192                                 'webhook_secret' => $webhook_secret,
    193                                 'admin_email' => $admin_email,
    194                                 'store_name' => $store_name,
     232                                'webhook_secret'  => $webhook_secret,
     233                                'install_secret'  => $install_secret,
     234                                'store_name'      => $store_name,
    195235                        );
    196                         set_transient('wondertax_connect_' . $connect_token, $credential_data, 3600); // 1 hour to match HMAC window
    197 
    198                         // Build signed redirect URL (only token in URL, not credentials)
    199                         $redirect_url = $this->build_secure_connect_url($connect_token);
     236                        set_transient( 'wondertax_connect_' . $connect_token, $credential_data, self::TOKEN_TTL );
     237
     238                        // Build signed redirect URL (only token in URL, not credentials), signed with the new install secret
     239                        $redirect_url = $this->build_secure_connect_url( $connect_token, $site_url, $install_secret );
    200240
    201241                        // Add WonderTax backend to allowed redirect hosts for wp_safe_redirect
    202                         add_filter('allowed_redirect_hosts', array($this, 'allow_wondertax_redirect'));
     242                        add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wondertax_redirect' ) );
    203243
    204244                        // Redirect to WonderTax Labs connect endpoint (use wp_safe_redirect for security)
    205                         wp_safe_redirect($redirect_url);
     245                        wp_safe_redirect( $redirect_url );
    206246                        exit;
    207247
    208                 } catch (Exception $e) {
    209                         // Clean up failed connection
    210                         $this->cleanup_failed_connection();
     248                } catch ( Exception $e ) {
     249                        // Clean up the failed connect only: the working connection stays as it was
     250                        self::discard_pending_connection();
    211251
    212252                        // Show error
    … …  
    216256                                sprintf(
    217257                                        /* translators: %s: error message */
    218                                         __('Failed to connect: %s', 'wondertax-labs-audita'),
     258                                        __( 'Failed to connect: %s', 'wondertax-labs-audita' ),
    219259                                        $e->getMessage()
    220260                                ),
    … …  
    225265
    226266        /**
    227          * Handle OAuth initiation from WonderTax Labs app
    228          * This is used when an existing WonderTax user initiates connection from their dashboard.
    229          * Stores OAuth parameters and redirects to confirmation page to prevent CSRF attacks.
    230          */
    231         private function handle_oauth_initiation()
    232         {
    233                 // Verify user has permission to manage WooCommerce before processing OAuth
    234                 if (!current_user_can('manage_woocommerce')) {
    235                         add_settings_error(
    236                                 'wondertax',
    237                                 'permission_denied',
    238                                 __('You do not have permission to connect this store.', 'wondertax-labs-audita'),
    239                                 'error'
     267         * ⭐ PROMOTES A CONNECT IN PROGRESS once WonderTax Labs confirms it: a status read signed with the connect's NEW install
     268         * secret verifies only when WonderTax Labs bound the new connection (it holds that secret only then). Promoting makes
     269         * the new credentials and secrets the working ones, deletes the previous WooCommerce API key, and marks the store
     270         * connected. Asked on the return from WonderTax Labs, on the settings page and on the hourly sync, so a merchant who
     271         * never comes back to WordPress is still promoted. A connect older than PENDING_TTL is discarded. A connect whose read
     272         * went unanswered is not read again in the same request. Promoting deletes any released ack still waiting to be heard,
     273         * so it is never retried against the new installation.
     274         *
     275         * @return bool|null True when promoted, false when not confirmed (yet), null when no connect is in progress.
     276         */
     277        public static function confirm_pending_connection() {
     278                $pending = get_option( self::PENDING_OPTION, null );
     279                if ( ! is_array( $pending ) || empty( $pending['install_secret'] ) || empty( $pending['site_url'] ) ) {
     280                        return null;
     281                }
     282                if ( time() - (int) ( isset( $pending['created'] ) ? $pending['created'] : 0 ) > self::PENDING_TTL ) {
     283                        self::discard_pending_connection();
     284                        return null;
     285                }
     286                if ( (string) $pending['install_secret'] === self::$unconfirmed_secret ) {
     287                        return false;
     288                }
     289                $status = self::signed_status_read( (string) $pending['site_url'], (string) $pending['install_secret'] );
     290                if ( null === $status ) {
     291                        self::$unconfirmed_secret = (string) $pending['install_secret'];
     292                        return false;
     293                }
     294
     295                // Before the new install secret becomes the working one: a request cut short never leaves the ack to be signed with it.
     296                delete_option( WonderTax_Tax_Service::RELEASE_UNACKED_OPTION );
     297
     298                global $wpdb;
     299                $previous_key_id = (int) get_option( 'wondertax_api_key_id', 0 );
     300                $new_key_id      = (int) $pending['api_key_id'];
     301                if ( $previous_key_id && $previous_key_id !== $new_key_id ) {
     302                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, write operation
     303                        $wpdb->delete(
     304                                $wpdb->prefix . 'woocommerce_api_keys',
     305                                array( 'key_id' => $previous_key_id ),
     306                                array( '%d' )
    240307                        );
    241                         return;
    242                 }
    243 
    244                 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initial OAuth request from external service, user confirmation with nonce required before processing
    245                 $state = isset($_GET['state']) ? sanitize_text_field(wp_unslash($_GET['state'])) : '';
    246                 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initial OAuth request from external service, user confirmation with nonce required before processing
    247                 $callback_url = isset($_GET['callback_url']) ? esc_url_raw(wp_unslash($_GET['callback_url'])) : '';
    248 
    249                 if (empty($state) || empty($callback_url)) {
    250                         add_settings_error(
    251                                 'wondertax',
    252                                 'invalid_oauth_params',
    253                                 __('Invalid OAuth parameters. Please try again.', 'wondertax-labs-audita'),
    254                                 'error'
     308                }
     309                update_option( 'wondertax_consumer_key', $pending['consumer_key'] );
     310                update_option( 'wondertax_consumer_secret', $pending['consumer_secret'] );
     311                update_option( 'wondertax_webhook_secret', $pending['webhook_secret'] );
     312                update_option( 'wondertax_site_url', $pending['site_url'] );
     313                update_option( 'wondertax_install_secret', $pending['install_secret'] );
     314                update_option( 'wondertax_api_key_id', $new_key_id );
     315                update_option( 'wondertax_connected', true );
     316                delete_option( self::PENDING_OPTION );
     317                return true;
     318        }
     319
     320        /**
     321         * Discards a connect in progress: its API key row (never the working one) and its record.
     322         */
     323        public static function discard_pending_connection() {
     324                $pending = get_option( self::PENDING_OPTION, null );
     325                if ( is_array( $pending ) && ! empty( $pending['api_key_id'] )
     326                        && (int) $pending['api_key_id'] !== (int) get_option( 'wondertax_api_key_id', 0 ) ) {
     327                        global $wpdb;
     328                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, cleanup operation
     329                        $wpdb->delete(
     330                                $wpdb->prefix . 'woocommerce_api_keys',
     331                                array( 'key_id' => (int) $pending['api_key_id'] ),
     332                                array( '%d' )
    255333                        );
    256                         return;
    257                 }
    258 
    259                 // Validate callback_url against allowed backend origin
    260                 if (!$this->is_allowed_backend_url($callback_url)) {
    261                         add_settings_error(
    262                                 'wondertax',
    263                                 'invalid_callback_url',
    264                                 __('Invalid callback URL. The URL does not match the expected WonderTax Labs backend.', 'wondertax-labs-audita'),
    265                                 'error'
    266                         );
    267                         return;
    268                 }
    269 
    270                 // Store OAuth parameters in a user-specific transient for confirmation
    271                 // This requires the user to explicitly confirm the connection with a nonce-protected form
    272                 $user_id = get_current_user_id();
    273                 $oauth_data = array(
    274                         'state' => $state,
    275                         'callback_url' => $callback_url,
    276                         'timestamp' => time(),
    277                 );
    278                 set_transient('wondertax_pending_oauth_' . $user_id, $oauth_data, 600); // 10 minute expiry
    279 
    280                 // Redirect to settings page with confirmation flag
    281                 // The render_admin_page() method will show a confirmation form
    282                 wp_safe_redirect(
     334                }
     335                delete_option( self::PENDING_OPTION );
     336        }
     337
     338        /**
     339         * ⭐ A STATUS READ SIGNED WITH AN INSTALL SECRET: `site_url|status|timestamp|nonce`, HMAC-SHA256 hex, as the mode switch
     340         * signs. WonderTax Labs answers the full status only to a good signature for a connected site.
     341         *
     342         * @param string $site_url       The site URL the connection is bound under.
     343         * @param string $install_secret The install secret to sign with.
     344         * @return array|null The status, or null when it was not answered.
     345         */
     346        public static function signed_status_read( $site_url, $install_secret ) {
     347                if ( '' === $site_url || '' === $install_secret ) {
     348                        return null;
     349                }
     350                try {
     351                        $nonce = bin2hex( random_bytes( 16 ) );
     352                } catch ( Exception $e ) {
     353                        return null;
     354                }
     355                $timestamp = time();
     356                $hmac      = hash_hmac( 'sha256', $site_url . '|status|' . $timestamp . '|' . $nonce, $install_secret );
     357                $response  = wp_remote_get(
    283358                        add_query_arg(
    284359                                array(
    285                                         'page' => 'wondertax-labs-audita',
    286                                         'confirm_oauth' => '1',
     360                                        'site_url'  => rawurlencode( $site_url ),
     361                                        'timestamp' => $timestamp,
     362                                        'nonce'     => $nonce,
     363                                        'hmac'      => $hmac,
    287364                                ),
    288                                 admin_url('admin.php')
    289                         )
     365                                WONDERTAX_BACKEND_URL . '/api/integrations/woocommerce/status'
     366                        ),
     367                        array( 'timeout' => 5 )
    290368                );
    291                 exit;
    292         }
    293 
    294         /**
    295          * Handle confirmed OAuth connection after user clicks confirm button.
    296          * This method is called after nonce verification in handle_settings_actions().
    297          */
    298         private function handle_confirmed_oauth()
    299         {
    300                 // Verify user has permission
    301                 if (!current_user_can('manage_woocommerce')) {
    302                         add_settings_error(
    303                                 'wondertax',
    304                                 'permission_denied',
    305                                 __('You do not have permission to connect this store.', 'wondertax-labs-audita'),
    306                                 'error'
    307                         );
    308                         return;
    309                 }
    310 
    311                 // Retrieve stored OAuth parameters
    312                 $user_id = get_current_user_id();
    313                 $oauth_data = get_transient('wondertax_pending_oauth_' . $user_id);
    314 
    315                 if (empty($oauth_data) || empty($oauth_data['state']) || empty($oauth_data['callback_url'])) {
    316                         add_settings_error(
    317                                 'wondertax',
    318                                 'oauth_expired',
    319                                 __('OAuth session expired. Please try connecting again from WonderTax Labs.', 'wondertax-labs-audita'),
    320                                 'error'
    321                         );
    322                         return;
    323                 }
    324 
    325                 // Delete the transient immediately (one-time use)
    326                 delete_transient('wondertax_pending_oauth_' . $user_id);
    327 
    328                 // Re-validate callback_url (defense in depth)
    329                 if (!$this->is_allowed_backend_url($oauth_data['callback_url'])) {
    330                         add_settings_error(
    331                                 'wondertax',
    332                                 'invalid_callback_url',
    333                                 __('Invalid callback URL. The URL does not match the expected WonderTax Labs backend.', 'wondertax-labs-audita'),
    334                                 'error'
    335                         );
    336                         return;
    337                 }
    338 
    339                 // Store validated OAuth data in a new transient for the OAuth handler
    340                 // Use a random token to prevent parameter tampering
    341                 try {
    342                         $oauth_token = bin2hex(random_bytes(16));
    343                 } catch (Exception $e) {
    344                         add_settings_error(
    345                                 'wondertax',
    346                                 'token_generation_failed',
    347                                 __('Failed to start OAuth connection. Please try again.', 'wondertax-labs-audita'),
    348                                 'error'
    349                         );
    350                         return;
    351                 }
    352                 set_transient('wondertax_oauth_verified_' . $oauth_token, $oauth_data, 300); // 5 minute expiry
    353 
    354                 // Redirect to OAuth handler with the verification token
    355                 wp_safe_redirect(
    356                         add_query_arg(
    357                                 array(
    358                                         'action' => 'wondertax_oauth',
    359                                         'oauth_token' => $oauth_token,
    360                                 ),
    361                                 admin_url('admin-post.php')
    362                         )
    363                 );
    364                 exit;
    365         }
    366 
    367         /**
    368          * Check if a URL matches the allowed backend origin
    369          *
    370          * @param string $url URL to validate
    371          * @return bool
    372          */
    373         private function is_allowed_backend_url($url)
    374         {
    375                 $parsed = wp_parse_url($url);
    376                 if (!$parsed || !isset($parsed['host'], $parsed['scheme'])) {
    377                         return false;
    378                 }
    379 
    380                 $allowed = $this->get_allowed_backend_origin();
    381                 $url_port = isset($parsed['port']) ? (int) $parsed['port'] : null;
    382                 return $parsed['host'] === $allowed['host']
    383                         && $parsed['scheme'] === $allowed['scheme']
    384                         && $url_port === $allowed['port'];
    385         }
    386 
    387         /**
    388          * Get the allowed backend origin
    389          *
    390          * @return array{host: string, scheme: string, port: int|null}
    391          */
    392         private function get_allowed_backend_origin()
    393         {
    394                 return array(
    395                         'host' => 'app.wonder.tax',
    396                         'scheme' => 'https',
    397                         'port' => null,
    398                 );
     369                if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
     370                        return null;
     371                }
     372                $data = json_decode( wp_remote_retrieve_body( $response ), true );
     373                return is_array( $data ) && ! empty( $data['success'] ) ? $data : null;
    399374        }
    400375
    … …  
    403378         * Only the token is sent in the URL - credentials are exchanged server-to-server.
    404379         *
    405          * @param string $connect_token One-time token for credential exchange
     380         * @param string $connect_token  One-time token for credential exchange
     381         * @param string $site_url       The site URL the connection is bound under.
     382         * @param string $install_secret The new connection's install secret, which signs the link.
    406383         * @return string Signed URL
    407384         */
    408         private function build_secure_connect_url($connect_token)
    409         {
     385        private function build_secure_connect_url( $connect_token, $site_url, $install_secret ) {
    410386                $timestamp = time();
    411                 $site_url = get_site_url();
    412387
    413388                // Parameters to include in URL (no credentials!)
    414389                $params = array(
    415                         'token' => $connect_token,
    416                         'site_url' => $site_url,
     390                        'token'     => $connect_token,
     391                        'site_url'  => $site_url,
    417392                        'timestamp' => $timestamp,
    418393                );
    … …  
    421396                $message = $connect_token . '|' . $site_url . '|' . $timestamp;
    422397
    423                 // Sign with per-install secret
    424                 $hmac = hash_hmac('sha256', $message, wondertax_get_install_secret());
     398                // Sign with the new connection's install secret (the exchange serves it)
     399                $hmac           = hash_hmac( 'sha256', $message, $install_secret );
    425400                $params['hmac'] = $hmac;
    426401
    427402                // Build URL
    428                 $backend_url = $this->get_backend_url();
    429                 return add_query_arg($params, $backend_url . '/api/integrations/woocommerce/connect');
     403                $backend_url = WONDERTAX_BACKEND_URL;
     404                return add_query_arg( $params, $backend_url . '/api/integrations/woocommerce/connect' );
    430405        }
    431406
    … …  
    436411         * @throws Exception If credential generation fails
    437412         */
    438         private function generate_api_credentials()
    439         {
     413        private function generate_api_credentials() {
    440414                global $wpdb;
    441415
    442416                // Verify WooCommerce functions are available
    443                 if (!function_exists('wc_rand_hash') || !function_exists('wc_api_hash')) {
    444                         throw new Exception('WooCommerce API functions not available. Please ensure WooCommerce is active.');
     417                if ( ! function_exists( 'wc_rand_hash' ) || ! function_exists( 'wc_api_hash' ) ) {
     418                        throw new Exception( 'WooCommerce API functions not available. Please ensure WooCommerce is active.' );
    445419                }
    446420
    447421                // Get current user
    448422                $user = wp_get_current_user();
    449                 if (!$user || !$user->ID) {
    450                         throw new Exception('No user logged in');
     423                if ( ! $user || ! $user->ID ) {
     424                        throw new Exception( 'No user logged in' );
    451425                }
    452426
    453427                // Verify user has manage_woocommerce capability
    454                 if (!current_user_can('manage_woocommerce')) {
    455                         throw new Exception('User does not have permission to manage WooCommerce');
     428                if ( ! current_user_can( 'manage_woocommerce' ) ) {
     429                        throw new Exception( 'User does not have permission to manage WooCommerce' );
    456430                }
    457431
    458432                // Check if the API keys table exists (must check before any delete/insert operations)
    459                 $table_name = $wpdb->prefix . 'woocommerce_api_keys';
    460                 $table_name_like = $wpdb->esc_like($table_name);
     433                $table_name      = $wpdb->prefix . 'woocommerce_api_keys';
     434                $table_name_like = $wpdb->esc_like( $table_name );
    461435                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Schema check, not cacheable
    462                 $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name_like));
    463                 if (!$table_exists) {
    464                         throw new Exception('WooCommerce API keys table not found. Please ensure WooCommerce REST API is enabled.');
     436                $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name_like ) );
     437                if ( ! $table_exists ) {
     438                        throw new Exception( 'WooCommerce API keys table not found. Please ensure WooCommerce REST API is enabled.' );
    465439                }
    466440
    467441                // Generate random credentials
    468                 $consumer_key = 'ck_' . wc_rand_hash();
     442                $consumer_key    = 'ck_' . wc_rand_hash();
    469443                $consumer_secret = 'cs_' . wc_rand_hash();
    470444
    471                 // Delete any existing WonderTax Labs API keys
    472                 // First, try to delete by tracked key ID
    473                 $existing_key_id = get_option('wondertax_api_key_id');
    474                 if ($existing_key_id) {
    475                         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, write operation
    476                         $wpdb->delete(
    477                                 $table_name,
    478                                 array('key_id' => $existing_key_id),
    479                                 array('%d')
    480                         );
    481                         delete_option('wondertax_api_key_id');
    482                 }
    483 
    484                 // Also delete any orphaned keys with the same description (in case option was lost)
    485                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, write operation
    486                 $wpdb->delete(
    487                         $table_name,
    488                         array(
    489                                 'user_id' => $user->ID,
    490                                 'description' => 'WonderTax Labs Connector'
    491                         ),
    492                         array('%d', '%s')
    493                 );
     445                // ⛔ The working connection's key is never deleted here: it is replaced only once WonderTax Labs confirms the new
     446                // connection (confirm_pending_connection), so a connect abandoned midway leaves the store working.
    494447
    495448                // Insert into woocommerce_api_keys table
    … …  
    498451                        $table_name,
    499452                        array(
    500                                 'user_id' => $user->ID,
    501                                 'description' => 'WonderTax Labs Connector',
    502                                 'permissions' => 'read_write',
    503                                 'consumer_key' => wc_api_hash($consumer_key),
     453                                'user_id'         => $user->ID,
     454                                'description'     => 'WonderTax Labs Connector',
     455                                'permissions'     => 'read_write',
     456                                'consumer_key'    => wc_api_hash( $consumer_key ),
    504457                                'consumer_secret' => $consumer_secret,
    505                                 'truncated_key' => substr($consumer_key, -7),
     458                                'truncated_key'   => substr( $consumer_key, -7 ),
    506459                        ),
    507                         array('%d', '%s', '%s', '%s', '%s', '%s')
     460                        array( '%d', '%s', '%s', '%s', '%s', '%s' )
    508461                );
    509462
    510                 if (false === $result) {
    511                         throw new Exception('Failed to create API credentials.');
    512                 }
    513 
    514                 // Store the key ID for later cleanup
    515                 update_option('wondertax_api_key_id', $wpdb->insert_id);
     463                if ( false === $result ) {
     464                        throw new Exception( 'Failed to create API credentials.' );
     465                }
    516466
    517467                return array(
    518                         'consumer_key' => $consumer_key,
     468                        'consumer_key'    => $consumer_key,
    519469                        'consumer_secret' => $consumer_secret,
     470                        'key_id'          => (int) $wpdb->insert_id,
    520471                );
    521472        }
    … …  
    526477         * @return string
    527478         */
    528         private function generate_webhook_secret()
    529         {
    530                 return 'whsec_' . bin2hex(random_bytes(32));
    531         }
    532 
    533         /**
    534          * Get the backend URL for WonderTax Labs
    535          *
    536          * @return string
    537          */
    538         private function get_backend_url()
    539         {
    540                 return 'https://app.wonder.tax';
     479        private function generate_webhook_secret() {
     480                return 'whsec_' . bin2hex( random_bytes( 32 ) );
    541481        }
    542482
    … …  
    547487         * @return array Modified allowed hosts.
    548488         */
    549         public function allow_wondertax_redirect($hosts)
    550         {
    551                 $backend_url = $this->get_backend_url();
    552                 $parsed = wp_parse_url($backend_url);
    553                 if (!empty($parsed['host'])) {
     489        public function allow_wondertax_redirect( $hosts ) {
     490                $backend_url = WONDERTAX_BACKEND_URL;
     491                $parsed      = wp_parse_url( $backend_url );
     492                if ( ! empty( $parsed['host'] ) ) {
    554493                        $hosts[] = $parsed['host'];
    555494                }
    … …  
    558497
    559498        /**
    560          * Clean up failed connection
    561          */
    562         private function cleanup_failed_connection()
    563         {
    564                 global $wpdb;
    565 
    566                 // Delete API key if created
    567                 $key_id = get_option('wondertax_api_key_id');
    568                 if ($key_id) {
     499         * Deletes the order webhooks WonderTax Labs registered on this store: those delivering to its order routes on
     500         * WONDERTAX_BACKEND_URL's origin. Every other webhook is the merchant's and is never touched (📗 integration-import ·
     501         * I28).
     502         */
     503        private static function delete_our_webhooks() {
     504                if ( ! class_exists( 'WC_Webhook' ) || ! class_exists( 'WC_Data_Store' ) ) {
     505                        return;
     506                }
     507                $ours = self::url_origin( WONDERTAX_BACKEND_URL );
     508                if ( '' === $ours ) {
     509                        return;
     510                }
     511                $ids = WC_Data_Store::load( 'webhook' )->search_webhooks( array( 'limit' => -1 ) );
     512                foreach ( (array) $ids as $id ) {
     513                        $webhook = new WC_Webhook( $id );
     514                        $url     = (string) $webhook->get_delivery_url();
     515                        $path    = untrailingslashit( (string) wp_parse_url( $url, PHP_URL_PATH ) );
     516                        // Our order routes (and their aliases): a match, never a call — so it is a pattern, not a path.
     517                        $route   = 1 === preg_match( '#^/api/(integrations/)?woocommerce/webhooks/[a-z-]+$#', $path );
     518                        if ( $webhook->get_id() && $route && self::url_origin( $url ) === $ours ) {
     519                                $webhook->delete( true );
     520                        }
     521                }
     522        }
     523
     524        /**
     525         * A URL's origin (scheme, host and any port), lowercased; '' when it has no host.
     526         *
     527         * @param string $url The URL.
     528         * @return string
     529         */
     530        private static function url_origin( $url ) {
     531                $parts = wp_parse_url( $url );
     532                if ( empty( $parts['host'] ) ) {
     533                        return '';
     534                }
     535                $port = isset( $parts['port'] ) ? ':' . $parts['port'] : '';
     536                return strtolower( ( $parts['scheme'] ?? 'https' ) . '://' . $parts['host'] . $port );
     537        }
     538
     539        /**
     540         * Handle store disconnect. ⛔ A store still held is never disconnected: when its own tax setting cannot be put back (the
     541         * lock stayed busy), nothing is deleted and the store manager is asked to try again.
     542         */
     543        private function handle_disconnect() {
     544                // A disconnected store answers no checkout through WonderTax Labs, so its own tax setting is put back first, and
     545                // WonderTax Labs is told while the store can still sign (before its connection options are deleted): it then stops
     546                // importing the store's orders and removes its webhooks.
     547                if ( ! WonderTax_Tax_Service::give_back( 'disconnected' ) ) {
     548                        add_settings_error(
     549                                'wondertax',
     550                                'disconnect_busy',
     551                                __( 'Your store was not disconnected: your own tax settings could not be put back just now, because another request was changing them. Please try again in a moment.', 'wondertax-labs-audita' ),
     552                                'error'
     553                        );
     554                        return;
     555                }
     556                self::discard_pending_connection();
     557                WonderTax_Tax_Service::clear_door_failures();
     558
     559                // The order webhooks earlier versions of the plugin registered are deleted, as uninstall deletes them.
     560                $webhook_ids = get_option( 'wondertax_webhook_ids', array() );
     561                if ( ! empty( $webhook_ids ) && is_array( $webhook_ids ) && class_exists( 'WC_Webhook' ) ) {
     562                        foreach ( $webhook_ids as $webhook_id ) {
     563                                $webhook = new WC_Webhook( $webhook_id );
     564                                if ( $webhook->get_id() ) {
     565                                        $webhook->delete( true );
     566                                }
     567                        }
     568                }
     569                delete_option( 'wondertax_webhook_ids' );
     570                // And the ones WonderTax Labs registered, here and now: its own cleanup reads the store with the key removed next,
     571                // and may run after it is gone.
     572                self::delete_our_webhooks();
     573
     574                // The WooCommerce API key WonderTax Labs read the store with is removed, so nothing can read it any more.
     575                $key_id = (int) get_option( 'wondertax_api_key_id', 0 );
     576                if ( $key_id ) {
     577                        global $wpdb;
    569578                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, cleanup operation
    570579                        $wpdb->delete(
    571580                                $wpdb->prefix . 'woocommerce_api_keys',
    572                                 array('key_id' => $key_id),
    573                                 array('%d')
     581                                array( 'key_id' => $key_id ),
     582                                array( '%d' )
    574583                        );
    575584                }
    576585
    577                 // Clean up options
    578                 delete_option('wondertax_consumer_key');
    579                 delete_option('wondertax_consumer_secret');
    580                 delete_option('wondertax_webhook_secret');
    581                 delete_option('wondertax_site_url');
    582                 delete_option('wondertax_api_key_id');
    583         }
    584 
    585         /**
    586          * Handle store disconnect
    587          */
    588         private function handle_disconnect()
    589         {
    590                 delete_option('wondertax_connected');
    591                 delete_option('wondertax_consumer_key');
    592                 delete_option('wondertax_consumer_secret');
    593                 delete_option('wondertax_webhook_secret');
    594                 delete_option('wondertax_site_url');
    595                 delete_option('wondertax_tax_calculation_enabled');
     586                delete_option( 'wondertax_connected' );
     587                delete_option( 'wondertax_consumer_key' );
     588                delete_option( 'wondertax_consumer_secret' );
     589                delete_option( 'wondertax_webhook_secret' );
     590                delete_option( 'wondertax_site_url' );
     591                delete_option( 'wondertax_api_key_id' );
     592                delete_option( 'wondertax_tax_calculation_enabled' );
    596593
    597594                add_settings_error(
    598595                        'wondertax',
    599596                        'disconnected',
    600                         __('Successfully disconnected from WonderTax Labs.', 'wondertax-labs-audita'),
     597                        __( 'Successfully disconnected from WonderTax Labs.', 'wondertax-labs-audita' ),
    601598                        'success'
    602599                );
    … …  
    604601
    605602        /**
    606          * Handle tax calculation toggle
    607          */
    608         private function handle_tax_toggle()
    609         {
    610                 // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in handle_settings_actions() before calling this method
    611                 $enabled = isset($_POST['tax_calculation_enabled']) ? true : false;
    612                 update_option('wondertax_tax_calculation_enabled', $enabled);
    613 
    614                 add_settings_error(
    615                         'wondertax',
    616                         'tax_toggled',
    617                         $enabled
    618                                 ? __('Real-time tax calculation enabled.', 'wondertax-labs-audita')
    619                                 : __('Real-time tax calculation disabled.', 'wondertax-labs-audita'),
    620                         'success'
    621                 );
    622         }
    623 
    624         /**
    625603         * Check if store is connected
    626604         *
    627605         * @return bool
    628606         */
    629         private function is_connected()
    630         {
    631                 return (bool) get_option('wondertax_connected', false);
     607        private function is_connected() {
     608                return (bool) get_option( 'wondertax_connected', false );
    632609        }
    633610
    … …  
    638615         * @return string|false Signed dashboard URL, or false on error
    639616         */
    640         private function build_authenticated_dashboard_url()
    641         {
     617        private function build_authenticated_dashboard_url() {
    642618                try {
    643619                        $timestamp = time();
    644                         $site_url = get_option('wondertax_site_url', get_site_url());
    645                         $nonce = bin2hex(random_bytes(16));
     620                        $site_url  = get_option( 'wondertax_site_url', get_site_url() );
     621                        $nonce     = bin2hex( random_bytes( 16 ) );
    646622
    647623                        // Build message for HMAC: site_url|timestamp|nonce
    … …  
    649625
    650626                        // Sign with per-install secret
    651                         $hmac = hash_hmac('sha256', $message, wondertax_get_install_secret());
     627                        $hmac = hash_hmac( 'sha256', $message, wondertax_get_install_secret() );
    652628
    653629                        // Build URL parameters
    654630                        $params = array(
    655                                 'site_url' => $site_url,
     631                                'site_url'  => $site_url,
    656632                                'timestamp' => $timestamp,
    657                                 'nonce' => $nonce,
    658                                 'hmac' => $hmac,
     633                                'nonce'     => $nonce,
     634                                'hmac'      => $hmac,
    659635                        );
    660636
    661                         $backend_url = $this->get_backend_url();
    662                         return add_query_arg($params, $backend_url . '/api/integrations/woocommerce/open');
    663                 } catch (Exception $e) {
     637                        $backend_url = WONDERTAX_BACKEND_URL;
     638                        return add_query_arg( $params, $backend_url . '/api/integrations/woocommerce/open' );
     639                } catch ( Exception $e ) {
    664640                        return false;
    665641                }
    … …  
    671647         * @return array|null
    672648         */
    673         private function get_api_key_status()
    674         {
    675                 $site_url = get_option('wondertax_site_url', '');
    676                 if (empty($site_url)) {
     649        private function get_api_key_status() {
     650                $site_url = get_option( 'wondertax_site_url', '' );
     651                if ( empty( $site_url ) ) {
    677652                        return null;
    678653                }
    679654
    680                 // Try to fetch status from backend
    681                 $backend_url = $this->get_backend_url();
    682                 $request_args = array('timeout' => 10);
    683                 $response = wp_remote_get(
    684                         add_query_arg('site_url', $site_url, $backend_url . '/api/integrations/woocommerce/status'),
    685                         $request_args
    686                 );
    687 
    688                 if (is_wp_error($response)) {
    689                         return null;
    690                 }
    691 
    692                 $body = wp_remote_retrieve_body($response);
    693                 $data = json_decode($body, true);
    694 
    695                 if (isset($data['success']) && $data['success']) {
     655                // A status read signed with the store's install secret (an unsigned read is answered with nothing about the store).
     656                $data = self::signed_status_read( $site_url, wondertax_get_install_secret() );
     657
     658                if ( null !== $data ) {
     659                        // Reads the tax service WonderTax Labs asks for from a signed report; the hourly sync does this too.
     660                        WonderTax_Tax_Service::sync();
    696661                        return $data;
    697662                }
    … …  
    703668         * Handle AJAX mode switch request
    704669         */
    705         public function ajax_switch_mode()
    706         {
     670        public function ajax_switch_mode() {
    707671                // Verify nonce
    708                 if (!check_ajax_referer('wondertax_switch_mode', 'nonce', false)) {
    709                         wp_send_json_error(array('message' => __('Security check failed.', 'wondertax-labs-audita')));
     672                if ( ! check_ajax_referer( 'wondertax_switch_mode', 'nonce', false ) ) {
     673                        wp_send_json_error( array( 'message' => __( 'Security check failed.', 'wondertax-labs-audita' ) ) );
    710674                }
    711675
    712676                // Verify user capabilities
    713                 if (!current_user_can('manage_woocommerce')) {
    714                         wp_send_json_error(array('message' => __('You do not have permission to perform this action.', 'wondertax-labs-audita')));
    715                 }
    716 
    717                 $mode = isset($_POST['mode']) ? sanitize_text_field(wp_unslash($_POST['mode'])) : '';
    718                 if (!in_array($mode, array('live', 'test'), true)) {
    719                         wp_send_json_error(array('message' => __('Invalid mode specified.', 'wondertax-labs-audita')));
     677                if ( ! current_user_can( 'manage_woocommerce' ) ) {
     678                        wp_send_json_error( array( 'message' => __( 'You do not have permission to perform this action.', 'wondertax-labs-audita' ) ) );
     679                }
     680
     681                $mode = isset( $_POST['mode'] ) ? sanitize_text_field( wp_unslash( $_POST['mode'] ) ) : '';
     682                if ( ! in_array( $mode, array( 'live', 'test' ), true ) ) {
     683                        wp_send_json_error( array( 'message' => __( 'Invalid mode specified.', 'wondertax-labs-audita' ) ) );
    720684                }
    721685
    722686                // Get site URL
    723                 $site_url = get_option('wondertax_site_url', get_site_url());
     687                $site_url  = get_option( 'wondertax_site_url', get_site_url() );
    724688                $timestamp = time();
    725689
    726690                try {
    727                         $nonce = bin2hex(random_bytes(16));
    728                 } catch (Exception $e) {
    729                         wp_send_json_error(array('message' => __('Failed to generate request nonce.', 'wondertax-labs-audita')));
     691                        $nonce = bin2hex( random_bytes( 16 ) );
     692                } catch ( Exception $e ) {
     693                        wp_send_json_error( array( 'message' => __( 'Failed to generate request nonce.', 'wondertax-labs-audita' ) ) );
    730694                }
    731695                // Build message for HMAC: site_url|mode|timestamp|nonce
    732696                $message = $site_url . '|' . $mode . '|' . $timestamp . '|' . $nonce;
    733                 $hmac = hash_hmac('sha256', $message, wondertax_get_install_secret());
     697                $hmac    = hash_hmac( 'sha256', $message, wondertax_get_install_secret() );
    734698
    735699                // Call the mode switch endpoint
    736                 $backend_url = $this->get_backend_url();
    737                 $headers = array('Content-Type' => 'application/json');
     700                $backend_url = WONDERTAX_BACKEND_URL;
     701                $headers     = array( 'Content-Type' => 'application/json' );
    738702
    739703                $response = wp_remote_post(
    … …  
    742706                                'timeout' => 30,
    743707                                'headers' => $headers,
    744                                 'body' => wp_json_encode(array(
    745                                         'site_url' => $site_url,
    746                                         'mode' => $mode,
    747                                         'timestamp' => $timestamp,
    748                                         'nonce' => $nonce,
    749                                         'hmac' => $hmac,
    750                                 )),
     708                                'body'    => wp_json_encode(
     709                                        array(
     710                                                'site_url'  => $site_url,
     711                                                'mode'      => $mode,
     712                                                'timestamp' => $timestamp,
     713                                                'nonce'     => $nonce,
     714                                                'hmac'      => $hmac,
     715                                        )
     716                                ),
    751717                        )
    752718                );
    753719
    754                 if (is_wp_error($response)) {
    755                         wp_send_json_error(array('message' => $response->get_error_message()));
    756                 }
    757 
    758                 $body = json_decode(wp_remote_retrieve_body($response), true);
    759                 $status_code = wp_remote_retrieve_response_code($response);
    760 
    761                 if ($status_code !== 200 || empty($body['success'])) {
    762                         $error_message = isset($body['message']) ? $body['message'] : __('Unknown error occurred.', 'wondertax-labs-audita');
    763                         wp_send_json_error(array('message' => $error_message));
    764                 }
    765 
    766                 wp_send_json_success(array(
    767                         'mode' => $mode,
    768                         'message' => $body['message'],
    769                 ));
     720                if ( is_wp_error( $response ) ) {
     721                        wp_send_json_error( array( 'message' => $response->get_error_message() ) );
     722                }
     723
     724                $body        = json_decode( wp_remote_retrieve_body( $response ), true );
     725                $status_code = wp_remote_retrieve_response_code( $response );
     726
     727                if ( $status_code !== 200 || empty( $body['success'] ) ) {
     728                        $error_message = isset( $body['message'] ) ? $body['message'] : __( 'Unknown error occurred.', 'wondertax-labs-audita' );
     729                        wp_send_json_error( array( 'message' => $error_message ) );
     730                }
     731
     732                wp_send_json_success(
     733                        array(
     734                                'mode'    => $mode,
     735                                'message' => $body['message'],
     736                        )
     737                );
    770738        }
    771739
    … …  
    775743         * @param array $status_data Status data from the API
    776744         */
    777         private function render_mode_selector($status_data)
    778         {
    779                 if (empty($status_data['dualKeyMode'])) {
     745        private function render_mode_selector( $status_data ) {
     746                if ( empty( $status_data['dualKeyMode'] ) ) {
    780747                        return;
    781748                }
    782749
    783                 $active_mode = isset($status_data['activeMode']) ? $status_data['activeMode'] : 'live';
    784                 $is_live = ($active_mode === 'live');
     750                $active_mode = isset( $status_data['activeMode'] ) ? $status_data['activeMode'] : 'live';
     751                $is_live     = ( $active_mode === 'live' );
    785752                ?>
    786753                <div class="wondertax-mode-selector">
    787                         <h3><?php esc_html_e('Transaction Mode', 'wondertax-labs-audita'); ?></h3>
     754                        <h3><?php esc_html_e( 'Transaction Mode', 'wondertax-labs-audita' ); ?></h3>
    788755                        <p class="wondertax-help-text">
    789                                 <?php esc_html_e('Choose how transactions from this store are recorded in WonderTax Labs.', 'wondertax-labs-audita'); ?>
     756                                <?php esc_html_e( 'Choose how transactions from this store are recorded in WonderTax Labs.', 'wondertax-labs-audita' ); ?>
    790757                        </p>
    791758
    … …  
    796763                                                name="wondertax_mode"
    797764                                                value="live"
    798                                                 <?php checked($is_live); ?>
     765                                                <?php checked( $is_live ); ?>
    799766                                                class="wondertax-mode-radio"
    800767                                        />
    801768                                        <div class="wondertax-mode-content">
    802769                                                <div class="wondertax-mode-header">
    803                                                         <span class="wondertax-mode-label"><?php esc_html_e('Live Mode', 'wondertax-labs-audita'); ?></span>
     770                                                        <span class="wondertax-mode-label"><?php esc_html_e( 'Live Mode', 'wondertax-labs-audita' ); ?></span>
    804771                                                        <span class="wondertax-badge wondertax-badge-success">
    805772                                                                <span class="dashicons dashicons-yes"></span>
    806                                                                 <?php esc_html_e('Production', 'wondertax-labs-audita'); ?>
     773                                                                <?php esc_html_e( 'Production', 'wondertax-labs-audita' ); ?>
    807774                                                        </span>
    808775                                                </div>
    809776                                                <p class="wondertax-mode-description">
    810                                                         <?php esc_html_e('Transactions are recorded as production data and count toward your tax compliance reports.', 'wondertax-labs-audita'); ?>
     777                                                        <?php esc_html_e( 'Transactions are recorded as production data and count toward your tax compliance reports.', 'wondertax-labs-audita' ); ?>
    811778                                                </p>
    812779                                        </div>
    813780                                </label>
    814781
    815                                 <label class="wondertax-mode-option <?php echo !$is_live ? 'wondertax-mode-active' : ''; ?>">
     782                                <label class="wondertax-mode-option <?php echo ! $is_live ? 'wondertax-mode-active' : ''; ?>">
    816783                                        <input
    817784                                                type="radio"
    818785                                                name="wondertax_mode"
    819786                                                value="test"
    820                                                 <?php checked(!$is_live); ?>
     787                                                <?php checked( ! $is_live ); ?>
    821788                                                class="wondertax-mode-radio"
    822789                                        />
    823790                                        <div class="wondertax-mode-content">
    824791                                                <div class="wondertax-mode-header">
    825                                                         <span class="wondertax-mode-label"><?php esc_html_e('Test Mode', 'wondertax-labs-audita'); ?></span>
     792                                                        <span class="wondertax-mode-label"><?php esc_html_e( 'Test Mode', 'wondertax-labs-audita' ); ?></span>
    826793                                                        <span class="wondertax-badge wondertax-badge-warning">
    827794                                                                <span class="dashicons dashicons-warning"></span>
    828                                                                 <?php esc_html_e('Development', 'wondertax-labs-audita'); ?>
     795                                                                <?php esc_html_e( 'Development', 'wondertax-labs-audita' ); ?>
    829796                                                        </span>
    830797                                                </div>
    831798                                                <p class="wondertax-mode-description">
    832                                                         <?php esc_html_e('Transactions are recorded as test data for staging and development. They do not affect compliance reports.', 'wondertax-labs-audita'); ?>
     799                                                        <?php esc_html_e( 'Transactions are recorded as test data for staging and development. They do not affect compliance reports.', 'wondertax-labs-audita' ); ?>
    833800                                                </p>
    834801                                        </div>
    … …  
    839806                                <button type="button" id="wondertax-switch-mode-btn" class="button button-primary" disabled>
    840807                                        <?php
    841                                         if ($is_live) {
    842                                                 esc_html_e('Switch to Test Mode', 'wondertax-labs-audita');
     808                                        if ( $is_live ) {
     809                                                esc_html_e( 'Switch to Test Mode', 'wondertax-labs-audita' );
    843810                                        } else {
    844                                                 esc_html_e('Switch to Live Mode', 'wondertax-labs-audita');
     811                                                esc_html_e( 'Switch to Live Mode', 'wondertax-labs-audita' );
    845812                                        }
    846813                                        ?>
    … …  
    851818                        <p class="wondertax-help-text wondertax-mode-note">
    852819                                <span class="dashicons dashicons-info"></span>
    853                                 <?php esc_html_e('Mode changes take effect immediately for all new transactions.', 'wondertax-labs-audita'); ?>
     820                                <?php esc_html_e( 'Mode changes take effect immediately for all new transactions.', 'wondertax-labs-audita' ); ?>
    854821                        </p>
    855822                </div>
    … …  
    858825
    859826        /**
    860          * Check if there's a pending OAuth confirmation for the current user
    861          *
    862          * @return array|false OAuth data if pending, false otherwise
    863          */
    864         private function get_pending_oauth_data()
    865         {
    866                 $user_id = get_current_user_id();
    867                 if (!$user_id) {
    868                         return false;
    869                 }
    870                 return get_transient('wondertax_pending_oauth_' . $user_id);
    871         }
    872 
    873         /**
    874          * Render OAuth confirmation form
    875          *
    876          * @param array $oauth_data Pending OAuth data
    877          */
    878         private function render_oauth_confirmation($oauth_data)
    879         {
    880                 ?>
    881                 <div class="wondertax-oauth-confirm">
    882                         <div class="wondertax-confirm-icon">
    883                                 <span class="dashicons dashicons-admin-links"></span>
    884                         </div>
    885                         <h2><?php esc_html_e('Connect to WonderTax Labs?', 'wondertax-labs-audita'); ?></h2>
    886                         <p>
    887                                 <?php esc_html_e('WonderTax Labs is requesting to connect to your WooCommerce store. This will:', 'wondertax-labs-audita'); ?>
    888                         </p>
    889                         <ul class="wondertax-confirm-list">
    890                                 <li><?php esc_html_e('Create WooCommerce API credentials for WonderTax Labs', 'wondertax-labs-audita'); ?></li>
    891                                 <li><?php esc_html_e('Allow WonderTax Labs to read your orders and products', 'wondertax-labs-audita'); ?></li>
    892                                 <li><?php esc_html_e('Enable automatic sales tax compliance auditing', 'wondertax-labs-audita'); ?></li>
    893                         </ul>
    894                         <form method="post" class="wondertax-confirm-form">
    895                                 <?php wp_nonce_field('wondertax_confirm_oauth', 'wondertax_nonce'); ?>
    896                                 <p class="wondertax-confirm-actions">
    897                                         <button type="submit" name="wondertax_confirm_oauth" value="1" class="button button-primary button-hero">
    898                                                 <?php esc_html_e('Confirm Connection', 'wondertax-labs-audita'); ?>
    899                                         </button>
    900                                 </p>
    901                                 <p class="wondertax-confirm-cancel">
    902                                         <a href="<?php echo esc_url(admin_url('admin.php?page=wondertax-labs-audita')); ?>">
    903                                                 <?php esc_html_e('Cancel', 'wondertax-labs-audita'); ?>
    904                                         </a>
    905                                 </p>
    906                         </form>
    907                 </div>
    908                 <?php
    909         }
    910 
    911         /**
    912827         * Render admin page
    913828         */
    914         public function render_admin_page()
    915         {
     829        public function render_admin_page() {
     830                // A connect in progress is confirmed on every visit, so a merchant who bound the store and came back later is connected.
     831                self::confirm_pending_connection();
    916832                $is_connected = $this->is_connected();
    917                 $tax_enabled = (bool) get_option('wondertax_tax_calculation_enabled', false);
    918                 $site_url = get_option('wondertax_site_url', '');
    919                 $status_data = $this->get_api_key_status();
    920 
    921                 // Check for pending OAuth confirmation
    922                 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Just checking for presence of flag to show UI, actual action requires nonce
    923                 $show_oauth_confirm = isset($_GET['confirm_oauth']) && '1' === sanitize_text_field(wp_unslash($_GET['confirm_oauth']));
    924                 $pending_oauth = $show_oauth_confirm ? $this->get_pending_oauth_data() : false;
     833                $site_url     = get_option( 'wondertax_site_url', '' );
     834                $status_data  = $this->get_api_key_status();
     835                $held         = class_exists( 'WonderTax_Tax_Service' ) && WonderTax_Tax_Service::is_taken_over();
    925836
    926837                ?>
    927838                <div class="wrap wondertax-admin">
    928839                        <h1>
    929                                 <?php esc_html_e('WonderTax Labs: Audita', 'wondertax-labs-audita'); ?>
     840                                <?php esc_html_e( 'WonderTax Labs: Audita™', 'wondertax-labs-audita' ); ?>
    930841                        </h1>
    931842
    932                         <?php settings_errors('wondertax'); ?>
    933 
    934                         <?php if ($pending_oauth) : ?>
    935                                 <!-- OAuth Confirmation Required -->
    936                                 <div class="wondertax-card">
    937                                         <?php $this->render_oauth_confirmation($pending_oauth); ?>
    938                                 </div>
    939                         <?php else : ?>
     843                        <?php settings_errors( 'wondertax' ); ?>
     844
    940845                        <div class="wondertax-card">
    941                                 <?php if ($is_connected) : ?>
     846                                <?php if ( $is_connected ) : ?>
    942847                                        <!-- Connected State -->
    943848                                        <div class="wondertax-status wondertax-status-connected">
    944849                                                <span class="dashicons dashicons-yes-alt"></span>
    945                                                 <?php esc_html_e('Connected to WonderTax Labs', 'wondertax-labs-audita'); ?>
     850                                                <?php esc_html_e( 'Connected to WonderTax Labs', 'wondertax-labs-audita' ); ?>
    946851                                        </div>
    947852
    948853                                        <!-- Open Dashboard Button -->
    949854                                        <?php $dashboard_url = $this->build_authenticated_dashboard_url(); ?>
    950                                         <?php if ($dashboard_url) : ?>
     855                                        <?php if ( $dashboard_url ) : ?>
    951856                                        <div class="wondertax-dashboard-action">
    952857                                                <a
    953                                                         href="<?php echo esc_url($dashboard_url); ?>"
     858                                                        href="<?php echo esc_url( $dashboard_url ); ?>"
    954859                                                        class="button wondertax-button-dashboard"
    955860                                                        target="_blank"
    … …  
    957862                                                >
    958863                                                        <span class="dashicons dashicons-external"></span>
    959                                                         <?php esc_html_e('Open WonderTax Labs', 'wondertax-labs-audita'); ?>
     864                                                        <?php esc_html_e( 'Open WonderTax Labs', 'wondertax-labs-audita' ); ?>
    960865                                                </a>
    961866                                                <p class="wondertax-dashboard-hint">
    962                                                         <?php esc_html_e('View your tax compliance dashboard, reports, and settings.', 'wondertax-labs-audita'); ?>
     867                                                        <?php esc_html_e( 'View your tax compliance dashboard, reports, and settings.', 'wondertax-labs-audita' ); ?>
    963868                                                </p>
    964869                                        </div>
    965870                                        <?php endif; ?>
    966871
    967                                         <?php if (!empty($site_url)) : ?>
     872                                        <?php if ( ! empty( $site_url ) ) : ?>
    968873                                                <p>
    969                                                         <strong><?php esc_html_e('Site URL:', 'wondertax-labs-audita'); ?></strong>
    970                                                         <?php echo esc_html($site_url); ?>
     874                                                        <strong><?php esc_html_e( 'Site URL:', 'wondertax-labs-audita' ); ?></strong>
     875                                                        <?php echo esc_html( $site_url ); ?>
    971876                                                </p>
    972877                                        <?php endif; ?>
    973878
    974879                                        <!-- Mode Selector for Dual-Key Installations -->
    975                                         <?php if ($status_data && !empty($status_data['dualKeyMode'])) : ?>
    976                                                 <?php $this->render_mode_selector($status_data); ?>
    977                                         <?php elseif ($status_data && isset($status_data['apiKey'])) : ?>
     880                                        <?php if ( $status_data && ! empty( $status_data['dualKeyMode'] ) ) : ?>
     881                                                <?php $this->render_mode_selector( $status_data ); ?>
     882                                        <?php elseif ( $status_data && isset( $status_data['apiKey'] ) ) : ?>
    978883                                                <!-- Legacy API Key Mode Status Badge (for single-key installations) -->
    979884                                                <?php
    980                                                 $api_key = $status_data['apiKey'];
    981                                                 $is_live = (bool) $api_key['live'];
     885                                                $api_key     = $status_data['apiKey'];
     886                                                $is_live     = (bool) $api_key['live'];
    982887                                                $is_disabled = (bool) $api_key['disabled'];
    983888                                                ?>
    984889                                                <div class="wondertax-api-key-status">
    985                                                         <?php if ($is_disabled) : ?>
     890                                                        <?php if ( $is_disabled ) : ?>
    986891                                                                <div class="wondertax-badge wondertax-badge-error">
    987892                                                                        <span class="dashicons dashicons-warning"></span>
    988                                                                         <?php esc_html_e('API Key Disabled', 'wondertax-labs-audita'); ?>
     893                                                                        <?php esc_html_e( 'API Key Disabled', 'wondertax-labs-audita' ); ?>
    989894                                                                </div>
    990895                                                                <p class="wondertax-help-text">
    991                                                                         <?php esc_html_e('Your API key has been disabled. Please contact service@wonder.tax.', 'wondertax-labs-audita'); ?>
     896                                                                        <?php esc_html_e( 'Your API key has been disabled. Please contact service@wonder.tax.', 'wondertax-labs-audita' ); ?>
    992897                                                                </p>
    993                                                         <?php elseif ($is_live) : ?>
     898                                                        <?php elseif ( $is_live ) : ?>
    994899                                                                <div class="wondertax-badge wondertax-badge-success">
    995900                                                                        <span class="dashicons dashicons-yes"></span>
    996                                                                         <?php esc_html_e('Live Mode', 'wondertax-labs-audita'); ?>
     901                                                                        <?php esc_html_e( 'Live Mode', 'wondertax-labs-audita' ); ?>
    997902                                                                </div>
    998903                                                                <p class="wondertax-help-text">
    999                                                                         <?php esc_html_e('Transactions are being recorded as live/production data and will be included in tax reports.', 'wondertax-labs-audita'); ?>
     904                                                                        <?php esc_html_e( 'Transactions are being recorded as live/production data and will be included in tax reports.', 'wondertax-labs-audita' ); ?>
    1000905                                                                </p>
    1001906                                                        <?php else : ?>
    1002907                                                                <div class="wondertax-badge wondertax-badge-warning">
    1003908                                                                        <span class="dashicons dashicons-warning"></span>
    1004                                                                         <?php esc_html_e('Test Mode', 'wondertax-labs-audita'); ?>
     909                                                                        <?php esc_html_e( 'Test Mode', 'wondertax-labs-audita' ); ?>
    1005910                                                                </div>
    1006911                                                                <p class="wondertax-help-text">
    1007                                                                         <?php esc_html_e('Transactions are being recorded as test data. Activate Live Mode when ready for production.', 'wondertax-labs-audita'); ?>
     912                                                                        <?php esc_html_e( 'Transactions are being recorded as test data. Activate Live Mode when ready for production.', 'wondertax-labs-audita' ); ?>
    1008913                                                                </p>
    1009914                                                                <p class="wondertax-help-text">
    1010915                                                                        <a href="https://app.wonder.tax" target="_blank" class="button button-secondary">
    1011                                                                                 <?php esc_html_e('Activate Live Mode', 'wondertax-labs-audita'); ?>
     916                                                                                <?php esc_html_e( 'Activate Live Mode', 'wondertax-labs-audita' ); ?>
    1012917                                                                        </a>
    1013918                                                                </p>
    … …  
    1017922
    1018923                                        <!-- Recent Activity Stats -->
    1019                                         <?php if ($status_data && isset($status_data['stats']['recentTransactionCount'])) : ?>
     924                                        <?php if ( $status_data && isset( $status_data['stats']['recentTransactionCount'] ) ) : ?>
    1020925                                                <div class="wondertax-api-key-status">
    1021926                                                        <p class="wondertax-stats">
    1022                                                                 <strong><?php esc_html_e('Recent Activity:', 'wondertax-labs-audita'); ?></strong>
     927                                                                <strong><?php esc_html_e( 'Recent Activity:', 'wondertax-labs-audita' ); ?></strong>
    1023928                                                                <?php
    1024929                                                                printf(
    1025930                                                                        /* translators: %d: number of transactions */
    1026                                                                         esc_html(_n('%d transaction in the last 30 days', '%d transactions in the last 30 days', absint($status_data['stats']['recentTransactionCount']), 'wondertax-labs-audita')),
    1027                                                                         absint($status_data['stats']['recentTransactionCount'])
     931                                                                        esc_html( _n( '%d transaction in the last 30 days', '%d transactions in the last 30 days', absint( $status_data['stats']['recentTransactionCount'] ), 'wondertax-labs-audita' ) ),
     932                                                                        absint( $status_data['stats']['recentTransactionCount'] )
    1028933                                                                );
    1029934                                                                ?>
    1030935                                                        </p>
    1031936                                                        <p class="wondertax-help-text">
    1032                                                                 <a href="<?php echo esc_url('https://app.wonder.tax/integrations/woocommerce/docs'); ?>" target="_blank">
    1033                                                                         <?php esc_html_e('Learn about Live vs Test Mode', 'wondertax-labs-audita'); ?>
     937                                                                <a href="<?php echo esc_url( 'https://app.wonder.tax/integrations/woocommerce/docs' ); ?>" target="_blank">
     938                                                                        <?php esc_html_e( 'Learn about Live vs Test Mode', 'wondertax-labs-audita' ); ?>
    1034939                                                                        <span class="dashicons dashicons-external" style="font-size: 14px; vertical-align: middle;"></span>
    1035940                                                                </a>
    … …  
    1038943                                        <?php endif; ?>
    1039944
    1040                                         <!-- Tax Calculation Status (Audit Only Mode) -->
     945                                        <!-- Checkout tax: who answers it -->
    1041946                                        <table class="form-table">
    1042947                                                <tr>
    1043948                                                        <th scope="row">
    1044                                                                 <?php esc_html_e('Real-Time Tax Auditing', 'wondertax-labs-audita'); ?>
     949                                                                <?php esc_html_e( 'Checkout Tax', 'wondertax-labs-audita' ); ?>
    1045950                                                        </th>
    1046951                                                        <td>
    1047                                                                 <h3><?php esc_html_e('Features', 'wondertax-labs-audita'); ?></h3>
     952                                                                <?php if ( $held ) : ?>
     953                                                                        <p>
     954                                                                                <?php esc_html_e( 'WonderTax Labs (Reporta™) answers your checkout tax: each cart\'s address and lines are sent to WonderTax Labs at checkout, and your store applies the tax it answers. Your own tax settings were recorded and are put back if you disconnect or deactivate this plugin.', 'wondertax-labs-audita' ); ?>
     955                                                                        </p>
     956                                                                <?php else : ?>
     957                                                                        <p>
     958                                                                                <?php esc_html_e( 'Your store calculates its own checkout tax. WonderTax Labs imports your orders and audits the sales tax they charged.', 'wondertax-labs-audita' ); ?>
     959                                                                        </p>
     960                                                                <?php endif; ?>
     961                                                                <h3><?php esc_html_e( 'Features', 'wondertax-labs-audita' ); ?></h3>
    1048962                                                                <ul>
    1049                                                                         <li><?php esc_html_e('✓ Automatic tax compliance tracking', 'wondertax-labs-audita'); ?></li>
    1050                                                                         <li><?php esc_html_e('✓ Real-time order import', 'wondertax-labs-audita'); ?></li>
    1051                                                                         <li><?php esc_html_e('✓ Multi-jurisdiction support', 'wondertax-labs-audita'); ?></li>
    1052                                                                         <li><?php esc_html_e('✓ Historical order import', 'wondertax-labs-audita'); ?></li>
     963                                                                        <li><?php esc_html_e( '✓ Automatic tax compliance tracking', 'wondertax-labs-audita' ); ?></li>
     964                                                                        <li><?php esc_html_e( '✓ Real-time order import', 'wondertax-labs-audita' ); ?></li>
     965                                                                        <li><?php esc_html_e( '✓ Multi-jurisdiction support', 'wondertax-labs-audita' ); ?></li>
     966                                                                        <li><?php esc_html_e( '✓ Historical order import', 'wondertax-labs-audita' ); ?></li>
    1053967                                                                </ul>
    1054968                                                        </td>
    … …  
    1059973                                        <hr />
    1060974                                        <form method="post" class="wondertax-form">
    1061                                                 <?php wp_nonce_field('wondertax_disconnect', 'wondertax_nonce'); ?>
     975                                                <?php wp_nonce_field( 'wondertax_disconnect', 'wondertax_nonce' ); ?>
    1062976                                                <p>
    1063977                                                        <button
    … …  
    1065979                                                                name="wondertax_disconnect"
    1066980                                                                class="button button-secondary"
    1067                                                                 onclick="return confirm('<?php echo esc_js(__('Are you sure you want to disconnect? This will disable your zero-cost, zero-risk sales tax audit agents.', 'wondertax-labs-audita')); ?>');"
     981                                                                onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to disconnect? WonderTax Labs will stop importing this store\'s orders, the API key it reads the store with will be removed, and your own tax settings are put back if WonderTax Labs answers your checkout tax.', 'wondertax-labs-audita' ) ); ?>');"
    1068982                                                        >
    1069                                                                 <?php esc_html_e('Disconnect Store', 'wondertax-labs-audita'); ?>
     983                                                                <?php esc_html_e( 'Disconnect Store', 'wondertax-labs-audita' ); ?>
    1070984                                                        </button>
    1071985                                                </p>
    … …  
    1076990                                        <div class="wondertax-status wondertax-status-disconnected">
    1077991                                                <span class="dashicons dashicons-warning"></span>
    1078                                                 <?php esc_html_e('Not Connected', 'wondertax-labs-audita'); ?>
     992                                                <?php esc_html_e( 'Not Connected', 'wondertax-labs-audita' ); ?>
    1079993                                        </div>
    1080994
    1081995                                        <p>
    1082                                                 <?php esc_html_e('Connect your WooCommerce store to WonderTax Labs for automated zero-cost and zero-risk sales tax auditing.', 'wondertax-labs-audita'); ?>
     996                                                <?php esc_html_e( 'Connect your WooCommerce store to WonderTax Labs: Audita™, which audits the sales tax your store charges at zero cost and zero risk.', 'wondertax-labs-audita' ); ?>
    1083997                                        </p>
    1084998
    … …  
    10881002                                                        add_query_arg(
    10891003                                                                array(
    1090                                                                         'page' => 'wondertax-labs-audita',
     1004                                                                        'page'   => 'wondertax-labs-audita',
    10911005                                                                        'action' => 'connect',
    10921006                                                                ),
    1093                                                                 admin_url('admin.php')
     1007                                                                admin_url( 'admin.php' )
    10941008                                                        ),
    10951009                                                        'wondertax_connect',
    … …  
    10981012                                                ?>
    10991013                                                <a
    1100                                                         href="<?php echo esc_url($connect_url); ?>"
     1014                                                        href="<?php echo esc_url( $connect_url ); ?>"
    11011015                                                        class="button button-primary"
    11021016                                                >
    1103                                                         <?php esc_html_e('Connect to WonderTax Labs', 'wondertax-labs-audita'); ?>
     1017                                                        <?php esc_html_e( 'Connect to WonderTax Labs', 'wondertax-labs-audita' ); ?>
    11041018                                                </a>
    11051019                                        </p>
    11061020
    11071021                                        <hr />
    1108                                         <h3><?php esc_html_e('Features', 'wondertax-labs-audita'); ?></h3>
     1022                                        <h3><?php esc_html_e( 'Features', 'wondertax-labs-audita' ); ?></h3>
    11091023                                        <ul>
    1110                                                 <li><?php esc_html_e('✓ Automatic tax compliance tracking', 'wondertax-labs-audita'); ?></li>
    1111                                                 <li><?php esc_html_e('✓ Multi-jurisdiction support', 'wondertax-labs-audita'); ?></li>
    1112                                                 <li><?php esc_html_e('✓ Historical order import', 'wondertax-labs-audita'); ?></li>
     1024                                                <li><?php esc_html_e( '✓ Automatic tax compliance tracking', 'wondertax-labs-audita' ); ?></li>
     1025                                                <li><?php esc_html_e( '✓ Multi-jurisdiction support', 'wondertax-labs-audita' ); ?></li>
     1026                                                <li><?php esc_html_e( '✓ Historical order import', 'wondertax-labs-audita' ); ?></li>
    11131027                                        </ul>
    11141028
    … …  
    11211035                                        printf(
    11221036                                                /* translators: 1: Link to documentation, 2: Link to support */
    1123                                                 esc_html__('Need help? Check out our %1$s or contact %2$s.', 'wondertax-labs-audita'),
    1124                                                 '<a href="https://app.wonder.tax/integrations/woocommerce/docs" target="_blank">' . esc_html__('documentation', 'wondertax-labs-audita') . '</a>',
    1125                                                 '<a href="mailto:service@wonder.tax">' . esc_html__('support', 'wondertax-labs-audita') . '</a>'
     1037                                                esc_html__( 'Need help? Check out our %1$s or contact %2$s.', 'wondertax-labs-audita' ),
     1038                                                '<a href="https://app.wonder.tax/integrations/woocommerce/docs" target="_blank">' . esc_html__( 'documentation', 'wondertax-labs-audita' ) . '</a>',
     1039                                                '<a href="mailto:service@wonder.tax">' . esc_html__( 'support', 'wondertax-labs-audita' ) . '</a>'
    11261040                                        );
    11271041                                        ?>
    … …  
    11311045                                </p>
    11321046                        </div>
    1133                         <?php endif; ?>
    11341047                </div>
    11351048                <?php
  • wondertax-labs-audita/trunk/includes/class-wondertax-tax-calc.php

    r3556520 r3814612  
    33 * Tax Calculation Hook
    44 *
    5  * Hooks into WooCommerce tax calculation to provide real-time tax rates
    6  * from WonderTax Labs during checkout.
     5 * While WonderTax Labs answers the store's checkout tax (WonderTax_Tax_Service), asks it for each cart's tax and
     6 * applies the exact amounts it answers: each line's own tax, and each jurisdiction's item and shipping totals.
     7 * A refusal leaves the store's own rates in place.
     8 *
     9 * Only the buyer's exemption is kept: a customer WooCommerce flags tax-exempt is never asked, so WooCommerce's zero stands.
     10 * A product, fee or shipping method WooCommerce marks not taxable (tax status "None", a zero-rate or exempt tax class) is
     11 * sent and taxed like any other, as its import taxes it, because only a taxability code exempts a product
     12 * (📗 integration-import · I42); the order's line records a product's tax status "None" for the merchant's notice. While
     13 * WonderTax Labs holds the store, WooCommerce's taxes stay on whatever "Enable taxes" says (wc_tax_enabled), since turning
     14 * them off does not exempt a sale.
     15 *
     16 * Only the exact-amounts step asks WonderTax Labs; woocommerce_find_rates keeps WooCommerce's own rates as its starting
     17 * point, so a cart is sent once, as totaled: its lines, its fees and its shipping, in one request. Each fee takes the
     18 * taxes answered for it, as the order's import taxes its fee line; a negative fee (a discount) lowers the lines it falls
     19 * on as the import lowers them, and takes no tax of its own.
    720 *
    821 * Supports both Classic Checkout and Block Checkout (Store API).
    … …  
    1225
    1326// Exit if accessed directly
    14 if (!defined('ABSPATH')) {
     27if ( ! defined( 'ABSPATH' ) ) {
    1528        exit;
    1629}
    … …  
    1932 * Tax calculation class
    2033 */
    21 class WonderTax_Tax_Calc
    22 {
     34class WonderTax_Tax_Calc {
     35
    2336        /**
    2437         * Singleton instance
    … …  
    2942
    3043        /**
     44         * Door replies already fetched in this request, by request body.
     45         *
     46         * @var array
     47         */
     48        private $quotes = array();
     49
     50        /**
     51         * Seconds a call to the door may take.
     52         */
     53        const TIMEOUT = 5;
     54
     55        /**
     56         * Transient set when the door fails (no reply, or a 5xx): while it stands, the door is not asked and the store's own
     57         * rates apply.
     58         */
     59        const PAUSE_TRANSIENT = 'wondertax_tax_service_paused';
     60
     61        /**
     62         * Seconds the door is skipped after a failure.
     63         */
     64        const PAUSE_SECONDS = 60;
     65
     66        /**
     67         * The option counting the door's consecutive failures (a refusal, or no reply) and naming the last one's reason. It is
     68         * cleared by the next answered request, and by a takeover, a give-back and a disconnect
     69         * (WonderTax_Tax_Service::clear_door_failures).
     70         */
     71        const FAILURES_OPTION = 'wondertax_door_failures';
     72
     73        /**
     74         * How many failures in a row the store's managers are told of: one refusal can be a single bad address.
     75         */
     76        const FAILURES_NOTICE_AT = 3;
     77
     78        /**
     79         * The session key holding each rate label of the answer the cart carries now, by its rate id, for the order's tax lines:
     80         * empty while the store's own rates apply.
     81         */
     82        const RATE_LABELS_SESSION = 'wondertax_rate_labels';
     83
     84        /**
     85         * Line-item meta naming a product's own tax status ("none"), read by the order import (its REST line item carries no
     86         * tax status) as a fact for the merchant's notice, never an exemption (📗 integration-import · I42).
     87         */
     88        const TAX_STATUS_META = '_wondertax_tax_status';
     89
     90        /**
     91         * Session key holding the shipping taxes answered for the cart, by rate id: null when none was answered.
     92         */
     93        const SHIPPING_TAXES_SESSION = 'wondertax_exact_shipping_taxes';
     94
     95        /**
     96         * A line's tax data when it carries no tax.
     97         */
     98        const UNTAXED_LINE = array(
     99                'subtotal' => array(),
     100                'total'    => array(),
     101        );
     102
     103        /**
    31104         * Get singleton instance
    32105         *
    33106         * @return WonderTax_Tax_Calc
    34107         */
    35         public static function get_instance()
    36         {
    37                 if (null === self::$instance) {
     108        public static function get_instance() {
     109                if ( null === self::$instance ) {
    38110                        self::$instance = new self();
    39111                }
    … …  
    44116         * Constructor
    45117         */
    46         private function __construct()
    47         {
    48                 // Hook into WooCommerce tax calculation (Classic Checkout)
    49                 add_filter('woocommerce_find_rates', array($this, 'calculate_tax_rates'), 10, 2);
     118        private function __construct() {
     119                // Classic Checkout's rates step: WooCommerce's own rates are the starting point the exact amounts replace
     120                add_filter( 'woocommerce_find_rates', array( $this, 'calculate_tax_rates' ), 10, 2 );
     121
     122                // The order's line records a product's tax status "None", for the import's notice to the merchant
     123                add_action( 'woocommerce_checkout_create_order_line_item', array( $this, 'record_line_tax_status' ), 10, 4 );
     124
     125                // While WonderTax Labs holds the store, WooCommerce's taxes stay on whatever "Enable taxes" says
     126                add_filter( 'wc_tax_enabled', array( $this, 'keep_taxes_on_while_held' ), 10, 1 );
    50127
    51128                // Hook into Store API for Block Checkout compatibility
    52                 add_action('woocommerce_store_api_checkout_update_order_from_request', array($this, 'store_api_update_order_taxes'), 10, 2);
     129                add_action( 'woocommerce_store_api_checkout_update_order_from_request', array( $this, 'store_api_update_order_taxes' ), 10, 2 );
    53130
    54131                // Register Store API extension after blocks are loaded
    55                 add_action('woocommerce_blocks_loaded', array($this, 'register_store_api_hooks'));
     132                add_action( 'woocommerce_blocks_loaded', array( $this, 'register_store_api_hooks' ) );
     133
     134                // Apply the exact amounts answered, after WooCommerce has totaled the cart (both checkouts)
     135                add_action( 'woocommerce_after_calculate_totals', array( $this, 'apply_exact_cart_taxes' ), 20 );
     136
     137                // The order's shipping line carries the shipping tax answered
     138                add_action( 'woocommerce_checkout_create_order_shipping_item', array( $this, 'apply_exact_shipping_taxes' ), 10, 4 );
     139
     140                // Each tax line is named by the jurisdiction WonderTax Labs answered for it, not WooCommerce's generic "Tax".
     141                add_filter( 'woocommerce_rate_label', array( $this, 'answered_rate_label' ), 10, 2 );
     142        }
     143
     144        /**
     145         * Records on the order's line that its product's tax status is "None", so the import can tell the merchant: the line is
     146         * taxed all the same (📗 integration-import · I42).
     147         *
     148         * @param \WC_Order_Item_Product $item          Order line.
     149         * @param string                 $cart_item_key Cart item key.
     150         * @param array                  $values        Cart item.
     151         * @param \WC_Order              $order         Order.
     152         */
     153        public function record_line_tax_status( $item, $cart_item_key, $values, $order ) {
     154                if ( ! get_option( 'wondertax_connected', false ) || ! isset( $values['data'] ) || ! is_object( $values['data'] ) ) {
     155                        return;
     156                }
     157                if ( 'none' === $values['data']->get_tax_status() ) {
     158                        $item->update_meta_data( self::TAX_STATUS_META, 'none' );
     159                }
     160        }
     161
     162        /**
     163         * WooCommerce's taxes, as wc_tax_enabled() reads them: on while WonderTax Labs holds the store, whatever "Enable taxes"
     164         * says, since turning them off does not exempt a sale and WooCommerce runs no tax calculation while they are off
     165         * (📗 integration-import · I37 I42). Otherwise the merchant's own setting.
     166         *
     167         * @param bool $enabled Whether "Enable taxes" is on.
     168         * @return bool
     169         */
     170        public function keep_taxes_on_while_held( $enabled ) {
     171                return $enabled || $this->is_tax_calculation_enabled();
     172        }
     173
     174        /**
     175         * Does WonderTax Labs answer this cart's tax? Only while it holds the store, and never for a customer WooCommerce flags
     176         * tax-exempt (the buyer's exemption, 📗 integration-import · I36).
     177         *
     178         * @param \WC_Cart|null $cart Cart.
     179         * @return bool
     180         */
     181        private function answers_cart( $cart ) {
     182                if ( ! $this->is_tax_calculation_enabled() || ! $cart || $cart->is_empty() ) {
     183                        return false;
     184                }
     185                $customer = $cart->get_customer();
     186                return $customer && ! $customer->get_is_vat_exempt();
    56187        }
    57188
    … …  
    59190         * Register Store API specific hooks after blocks are loaded
    60191         */
    61         public function register_store_api_hooks()
    62         {
     192        public function register_store_api_hooks() {
    63193                // Hook into Store API cart updates for real-time tax calculation
    64                 add_action('woocommerce_store_api_cart_update_customer_from_request', array($this, 'store_api_calculate_taxes'), 10, 2);
     194                add_action( 'woocommerce_store_api_cart_update_customer_from_request', array( $this, 'store_api_calculate_taxes' ), 10, 2 );
    65195        }
    66196
    … …  
    71201         * @param \WP_REST_Request $request REST request object.
    72202         */
    73         public function store_api_calculate_taxes($customer, $request)
    74         {
    75                 if (!$this->is_tax_calculation_enabled()) {
     203        public function store_api_calculate_taxes( $customer, $request ) {
     204                if ( ! $this->is_tax_calculation_enabled() ) {
    76205                        return;
    77206                }
    … …  
    79208                // Get shipping address from customer (Block Checkout sends this)
    80209                $country = $customer->get_shipping_country();
    81                 $state = $customer->get_shipping_state();
     210                $state   = $customer->get_shipping_state();
    82211
    83212                // Only process US addresses
    84                 if ('US' !== $country || empty($state)) {
    85                         return;
    86                 }
    87 
    88                 // Force cart to recalculate totals (this triggers woocommerce_find_rates)
    89                 if (WC()->cart) {
     213                if ( 'US' !== $country || empty( $state ) ) {
     214                        return;
     215                }
     216
     217                // Force cart to recalculate totals (this triggers woocommerce_find_rates and apply_exact_cart_taxes)
     218                if ( WC()->cart ) {
    90219                        WC()->cart->calculate_totals();
    91220                }
    … …  
    93222
    94223        /**
    95          * Update order taxes when Store API checkout processes order
     224         * Puts the exact amounts answered onto the Store API's draft order. `OrderController::update_order_from_cart` ends with
     225         * `calculate_totals()`, which re-derives each line's and the shipping's tax from one rate per class; this action runs
     226         * after it, so each line takes its cart line's exact taxes, the first shipping line the shipping taxes answered (none on
     227         * any other, bug book B-281), the order's tax lines are rebuilt from them, and only the totals are summed again.
    96228         *
    97229         * @param \WC_Order $order Order object.
    98230         * @param \WP_REST_Request $request REST request object.
    99231         */
    100         public function store_api_update_order_taxes($order, $request)
    101         {
    102                 if (!$this->is_tax_calculation_enabled()) {
    103                         return;
    104                 }
    105 
    106                 // Get shipping address from order
    107                 $country = $order->get_shipping_country();
    108                 $state = $order->get_shipping_state();
    109 
    110                 // Only process US addresses
    111                 if ('US' !== $country || empty($state)) {
    112                         return;
    113                 }
    114 
    115                 // Recalculate order taxes (this triggers woocommerce_find_rates via order tax calculation)
    116                 $order->calculate_taxes();
    117                 $order->calculate_totals();
    118         }
    119 
    120         /**
    121          * Calculate tax rates using WonderTax Labs API
    122          *
    123          * @param array $rates Default tax rates.
    124          * @param array $args Tax calculation arguments.
    125          * @return array Modified tax rates.
    126          */
    127         public function calculate_tax_rates($rates, $args)
    128         {
    129                 // Check if WonderTax tax calculation is enabled
    130                 if (!$this->is_tax_calculation_enabled()) {
    131                         return $rates;
    132                 }
    133 
    134                 // Check if we have necessary address information
    135                 if (empty($args['country']) || empty($args['state'])) {
    136                         return $rates;
    137                 }
    138 
    139                 // Only process US addresses
    140                 if ('US' !== $args['country']) {
    141                         return $rates;
     232        public function store_api_update_order_taxes( $order, $request ) {
     233                if ( ! $this->is_tax_calculation_enabled() ) {
     234                        return;
     235                }
     236                $cart = WC()->cart;
     237                if ( ! $this->answers_cart( $cart ) || wc_prices_include_tax() ) {
     238                        return;
     239                }
     240                $shipping_taxes = $this->session_shipping_taxes();
     241                if ( ! is_array( $shipping_taxes ) ) {
     242                        // No exact answer for this cart (a refusal, or the door paused): WooCommerce's own figures stand.
     243                        return;
     244                }
     245                $this->apply_cart_taxes_to_order( $order, $cart, $shipping_taxes );
     246                $order->update_taxes();
     247                $order->calculate_totals( false );
     248        }
     249
     250        /**
     251         * Copies each cart line's exact taxes onto the order line built from it (matched by its cart key, else by product,
     252         * variation and quantity, each cart line used once), each cart fee's taxes onto the fee line built from it (matched by
     253         * its fee key, else by name and total, each cart fee used once; a negative fee carries none), and the shipping taxes
     254         * onto the first shipping line.
     255         *
     256         * @param \WC_Order $order          Order.
     257         * @param \WC_Cart  $cart           Cart, already carrying the exact amounts (apply_exact_cart_taxes).
     258         * @param array     $shipping_taxes The shipping taxes answered, by rate id.
     259         */
     260        private function apply_cart_taxes_to_order( $order, $cart, $shipping_taxes ) {
     261                $unused = $cart->get_cart();
     262                foreach ( $order->get_items( 'line_item' ) as $item ) {
     263                        $key = self::unused_key(
     264                                $unused,
     265                                isset( $item->legacy_cart_item_key ) ? $item->legacy_cart_item_key : null,
     266                                function ( $cart_item ) use ( $item ) {
     267                                        return (int) $cart_item['product_id'] === (int) $item->get_product_id()
     268                                                && (int) ( isset( $cart_item['variation_id'] ) ? $cart_item['variation_id'] : 0 ) === (int) $item->get_variation_id()
     269                                                && (float) $cart_item['quantity'] === (float) $item->get_quantity();
     270                                }
     271                        );
     272                        if ( null === $key ) {
     273                                continue;
     274                        }
     275                        $line_tax_data = isset( $unused[ $key ]['line_tax_data'] ) && is_array( $unused[ $key ]['line_tax_data'] )
     276                                ? $unused[ $key ]['line_tax_data']
     277                                : self::UNTAXED_LINE;
     278                        $item->set_taxes( $line_tax_data );
     279                        unset( $unused[ $key ] );
     280                }
     281                $unused_fees = $this->cart_fees( $cart );
     282                foreach ( $order->get_items( 'fee' ) as $fee_item ) {
     283                        $key = self::unused_key(
     284                                $unused_fees,
     285                                isset( $fee_item->legacy_fee_key ) ? $fee_item->legacy_fee_key : null,
     286                                function ( $fee ) use ( $fee_item ) {
     287                                        return is_object( $fee )
     288                                                && isset( $fee->name, $fee->total )
     289                                                && (string) $fee->name === (string) $fee_item->get_name()
     290                                                && abs( (float) $fee->total - (float) $fee_item->get_total() ) < 0.005;
     291                                }
     292                        );
     293                        if ( null === $key || ! is_object( $unused_fees[ $key ] ) ) {
     294                                continue;
     295                        }
     296                        $fee_tax_data = isset( $unused_fees[ $key ]->tax_data ) && is_array( $unused_fees[ $key ]->tax_data )
     297                                ? $unused_fees[ $key ]->tax_data
     298                                : array();
     299                        $fee_item->set_taxes( array( 'total' => $fee_tax_data ) );
     300                        unset( $unused_fees[ $key ] );
     301                }
     302                $first = true;
     303                foreach ( $order->get_items( 'shipping' ) as $shipping_item ) {
     304                        $shipping_item->set_taxes( self::shipping_line_taxes( $first, $shipping_taxes ) );
     305                        $first = false;
     306                }
     307        }
     308
     309        /**
     310         * The key of the cart entry an order line was built from, each entry used once: its own key while that entry is still
     311         * unused, else the first unused entry that matches it.
     312         *
     313         * @param array       $unused  The cart entries not yet used, by key.
     314         * @param string|null $own_key The key the order line carries, or null.
     315         * @param callable    $matches Whether an entry matches the order line.
     316         * @return string|null
     317         */
     318        private static function unused_key( $unused, $own_key, $matches ) {
     319                if ( null !== $own_key && isset( $unused[ $own_key ] ) ) {
     320                        return $own_key;
     321                }
     322                foreach ( $unused as $key => $entry ) {
     323                        if ( $matches( $entry ) ) {
     324                                return $key;
     325                        }
     326                }
     327                return null;
     328        }
     329
     330        /**
     331         * A shipping line's taxes: the shipping taxes answered on the first package's line, none on any other, so they are
     332         * never counted twice (bug book B-281).
     333         *
     334         * @param bool  $is_first       Whether this is the first package's line.
     335         * @param array $shipping_taxes The shipping taxes answered, by rate id.
     336         * @return array
     337         */
     338        private static function shipping_line_taxes( $is_first, $shipping_taxes ) {
     339                return array( 'total' => $is_first ? $shipping_taxes : array() );
     340        }
     341
     342        /**
     343         * The cart's fees, by fee key.
     344         *
     345         * @param \WC_Cart $cart Cart object.
     346         * @return array
     347         */
     348        private function cart_fees( $cart ) {
     349                return (array) $cart->get_fees();
     350        }
     351
     352        /**
     353         * The shipping taxes answered for the cart, kept in the session: null when none was answered or there is no session.
     354         *
     355         * @return array|null
     356         */
     357        private function session_shipping_taxes() {
     358                return WC()->session ? WC()->session->get( self::SHIPPING_TAXES_SESSION ) : null;
     359        }
     360
     361        /**
     362         * Keeps the shipping taxes answered for the cart in the session, when there is one.
     363         *
     364         * @param array|null $shipping_taxes The shipping taxes, by rate id, or null when none was answered.
     365         */
     366        private function set_session_shipping_taxes( $shipping_taxes ) {
     367                if ( WC()->session ) {
     368                        WC()->session->set( self::SHIPPING_TAXES_SESSION, $shipping_taxes );
     369                }
     370        }
     371
     372        /**
     373         * The cart's taxable address as both checkout steps send it, or null when it is not a US address with a state.
     374         *
     375         * @param \WC_Cart|null $cart Cart.
     376         * @return array|null
     377         */
     378        private function cart_address( $cart ) {
     379                $customer = $cart ? $cart->get_customer() : null;
     380                if ( ! $customer ) {
     381                        return null;
     382                }
     383                list($country, $state, $postcode, $city) = array_pad( $customer->get_taxable_address(), 4, '' );
     384                if ( 'US' !== $country || empty( $state ) ) {
     385                        return null;
     386                }
     387                return array(
     388                        'country'  => $country,
     389                        'state'    => $state,
     390                        'postcode' => $postcode,
     391                        'city'     => $city,
     392                        'address'  => $customer->get_shipping_address_1(),
     393                );
     394        }
     395
     396        /**
     397         * The rates WooCommerce totals a cart from. WonderTax Labs is never asked here: its exact amounts replace every figure
     398         * once the cart is totaled (apply_exact_cart_taxes), so WooCommerce's own rates are only the starting point.
     399         *
     400         * @param array $rates WooCommerce's own rates.
     401         * @param array $args  Tax calculation arguments.
     402         * @return array
     403         */
     404        public function calculate_tax_rates( $rates, $args ) {
     405                return $rates;
     406        }
     407
     408        /**
     409         * Replaces the cart's tax amounts with the exact amounts answered: each line's own tax, each fee's own tax, and each
     410         * jurisdiction's item, fee and shipping totals, on the lines' totals after coupons. A refusal leaves WooCommerce's own
     411         * figures, and its own rate labels: labels are kept only while an answer stands.
     412         *
     413         * @param \WC_Cart $cart Cart object.
     414         */
     415        public function apply_exact_cart_taxes( $cart ) {
     416                $this->set_session_shipping_taxes( null );
     417                $this->set_session_rate_labels( array() );
     418                if ( wc_prices_include_tax() ) {
     419                        return;
     420                }
     421                // The buyer's exemption (a tax-exempt customer) keeps WooCommerce's zero.
     422                if ( ! $this->answers_cart( $cart ) ) {
     423                        return;
     424                }
     425                $args = $this->cart_address( $cart );
     426                if ( null === $args ) {
     427                        return;
    142428                }
    143429
    144430                try {
    145                         // Build tax request
    146                         $tax_request = $this->build_tax_request($args);
    147 
    148                         // Call WonderTax Labs API
    149                         $tax_response = $this->call_tax_service($tax_request);
    150 
    151                         if (is_wp_error($tax_response)) {
    152                                 return $rates;
    153                         }
    154 
    155                         // Parse response and return tax rates
    156                         return $this->parse_tax_response($tax_response, $args);
    157 
    158                 } catch (Exception $e) {
    159                         return $rates;
    160                 }
    161         }
    162 
    163         /**
    164          * Check if tax calculation is enabled
     431                        $built = $this->build_tax_request( $args, $cart );
     432                        $reply = $this->quote( $built['request'] );
     433                        if ( is_wp_error( $reply ) || ! isset( $reply['lines'] ) || ! is_array( $reply['lines'] ) ) {
     434                                return;
     435                        }
     436
     437                        $this->remember_rate_labels( $reply );
     438                        $subtotal_tax = $this->apply_line_taxes( $cart, $built['keys'], self::taxes_by_index( $reply['lines'] ) );
     439                        list($item_taxes, $shipping_taxes, $answered_fee_taxes) = self::jurisdiction_totals( $reply );
     440                        $fee_taxes = $this->apply_fee_taxes( $cart, $built['fee_keys'], $reply, $answered_fee_taxes );
     441                        $this->set_cart_totals( $cart, $subtotal_tax, $item_taxes, $shipping_taxes, $fee_taxes );
     442                        $this->set_session_shipping_taxes( $shipping_taxes );
     443                } catch ( Exception $e ) {
     444                        return;
     445                }
     446        }
     447
     448        /**
     449         * Puts each line's answered taxes on its cart line (`line_tax_data`, `line_tax`, `line_subtotal_tax`), its subtotal
     450         * (before coupons) carrying the same taxes scaled to it so the coupon's own tax shows; returns the cart's subtotal tax.
     451         *
     452         * @param \WC_Cart $cart           Cart object.
     453         * @param string[] $keys           The cart item keys, in request order.
     454         * @param array    $lines_by_index The taxes answered for each line, by request index (taxes_by_index).
     455         * @return float
     456         */
     457        private function apply_line_taxes( $cart, $keys, $lines_by_index ) {
     458                $subtotal_tax = 0.0;
     459                foreach ( $keys as $index => $key ) {
     460                        $line_taxes = self::taxes_by_rate( isset( $lines_by_index[ $index ] ) ? $lines_by_index[ $index ] : array() );
     461
     462                        $item           = $cart->cart_contents[ $key ];
     463                        $line_total     = isset( $item['line_total'] ) ? (float) $item['line_total'] : 0.0;
     464                        $line_subtotal  = isset( $item['line_subtotal'] ) ? (float) $item['line_subtotal'] : $line_total;
     465                        $scale          = $line_total > 0 ? $line_subtotal / $line_total : 1.0;
     466                        $subtotal_taxes = array();
     467                        foreach ( $line_taxes as $rate_id => $amount ) {
     468                                $subtotal_taxes[ $rate_id ] = $amount * $scale;
     469                        }
     470
     471                        $cart->cart_contents[ $key ]['line_tax_data']     = array(
     472                                'subtotal' => $subtotal_taxes,
     473                                'total'    => $line_taxes,
     474                        );
     475                        $cart->cart_contents[ $key ]['line_tax']          = array_sum( $line_taxes );
     476                        $cart->cart_contents[ $key ]['line_subtotal_tax'] = array_sum( $subtotal_taxes );
     477                        $subtotal_tax                                    += array_sum( $subtotal_taxes );
     478                }
     479                return $subtotal_tax;
     480        }
     481
     482        /**
     483         * Each jurisdiction's item, shipping and fee totals answered, summed and rounded once by WonderTax Labs, each by rate id.
     484         *
     485         * @param array $reply The door's reply.
     486         * @return array { 0: item taxes, 1: shipping taxes, 2: fee taxes }
     487         */
     488        private static function jurisdiction_totals( $reply ) {
     489                $item_taxes     = array();
     490                $shipping_taxes = array();
     491                $fee_taxes      = array();
     492                if ( isset( $reply['taxes'] ) && is_array( $reply['taxes'] ) ) {
     493                        foreach ( $reply['taxes'] as $tax ) {
     494                                if ( ! isset( $tax['rate_id'] ) ) {
     495                                        continue;
     496                                }
     497                                $rate_id                    = (string) $tax['rate_id'];
     498                                $item_taxes[ $rate_id ]     = isset( $tax['tax_total'] ) ? (float) $tax['tax_total'] : 0.0;
     499                                $shipping_taxes[ $rate_id ] = isset( $tax['shipping_tax_total'] ) ? (float) $tax['shipping_tax_total'] : 0.0;
     500                                $fee_taxes[ $rate_id ]      = isset( $tax['fee_tax_total'] ) ? (float) $tax['fee_tax_total'] : 0.0;
     501                        }
     502                }
     503                return array( $item_taxes, $shipping_taxes, $fee_taxes );
     504        }
     505
     506        /**
     507         * Sets the cart's tax figures and its total from the exact amounts.
     508         *
     509         * @param \WC_Cart $cart           Cart object.
     510         * @param float    $subtotal_tax   The lines' subtotal tax.
     511         * @param array    $item_taxes     Each jurisdiction's item tax, by rate id.
     512         * @param array    $shipping_taxes Each jurisdiction's shipping tax, by rate id.
     513         * @param array    $fee_taxes      The cart's fee taxes, by rate id (apply_fee_taxes).
     514         */
     515        private function set_cart_totals( $cart, $subtotal_tax, $item_taxes, $shipping_taxes, $fee_taxes ) {
     516                $cart->set_subtotal_tax( $subtotal_tax );
     517                $cart->set_cart_contents_taxes( $item_taxes );
     518                $cart->set_cart_contents_tax( array_sum( $item_taxes ) );
     519                $cart->set_shipping_taxes( $shipping_taxes );
     520                $cart->set_shipping_tax( array_sum( $shipping_taxes ) );
     521                $cart->set_fee_taxes( $fee_taxes );
     522                $cart->set_fee_tax( array_sum( $fee_taxes ) );
     523                $total_tax = array_sum( $item_taxes ) + array_sum( $shipping_taxes ) + array_sum( $fee_taxes );
     524                $cart->set_total_tax( $total_tax );
     525                $total = (float) $cart->get_cart_contents_total() + (float) $cart->get_shipping_total() + (float) $cart->get_fee_total() + $total_tax;
     526                $cart->set_total( max( 0, round( $total, wc_get_price_decimals() ) ) );
     527        }
     528
     529        /**
     530         * The taxes answered for each sent line or fee, by its request index: the reply's `lines` or `fees` rows that carry an
     531         * `index` and a `taxes` list.
     532         *
     533         * @param array $rows The reply's rows.
     534         * @return array
     535         */
     536        private static function taxes_by_index( $rows ) {
     537                $by_index = array();
     538                foreach ( $rows as $row ) {
     539                        if ( isset( $row['index'] ) && isset( $row['taxes'] ) && is_array( $row['taxes'] ) ) {
     540                                $by_index[ (int) $row['index'] ] = $row['taxes'];
     541                        }
     542                }
     543                return $by_index;
     544        }
     545
     546        /**
     547         * One line's or fee's answered taxes as WooCommerce keeps them: each `tax_total` by its `rate_id`.
     548         *
     549         * @param array $taxes The taxes answered for it.
     550         * @return array
     551         */
     552        private static function taxes_by_rate( $taxes ) {
     553                $by_rate = array();
     554                foreach ( $taxes as $tax ) {
     555                        if ( isset( $tax['rate_id'], $tax['tax_total'] ) ) {
     556                                $by_rate[ (string) $tax['rate_id'] ] = (float) $tax['tax_total'];
     557                        }
     558                }
     559                return $by_rate;
     560        }
     561
     562        /**
     563         * Puts each sent fee's answered taxes on the cart's fee (its own `tax_data` and `tax`, which the order's fee line is built
     564         * from), and returns the cart's fee taxes by rate id: each jurisdiction's fee total answered, plus the taxes WooCommerce
     565         * gave a fee that was not sent (a fee of zero). A negative fee is sent and answered with no taxes, so it carries none of
     566         * its own: its discount is already off the lines' taxes. A reply with no fee answer keeps WooCommerce's own.
     567         *
     568         * @param \WC_Cart $cart               Cart object.
     569         * @param string[] $fee_keys           The sent fees' cart keys, in request order.
     570         * @param array    $reply              The door's reply.
     571         * @param array    $answered_fee_taxes Each jurisdiction's fee total answered, by rate id.
     572         * @return array
     573         */
     574        private function apply_fee_taxes( $cart, $fee_keys, $reply, $answered_fee_taxes ) {
     575                $cart_fees = $this->cart_fees( $cart );
     576                if ( ! empty( $fee_keys ) && ( ! isset( $reply['fees'] ) || ! is_array( $reply['fees'] ) ) ) {
     577                        return method_exists( $cart, 'get_fee_taxes' ) ? (array) $cart->get_fee_taxes() : array();
     578                }
     579                $fees_by_index = self::taxes_by_index( isset( $reply['fees'] ) && is_array( $reply['fees'] ) ? $reply['fees'] : array() );
     580                $fee_taxes     = empty( $fee_keys ) ? array() : $answered_fee_taxes;
     581                $sent          = array();
     582                foreach ( $fee_keys as $index => $fee_key ) {
     583                        if ( ! isset( $cart_fees[ $fee_key ] ) || ! is_object( $cart_fees[ $fee_key ] ) ) {
     584                                continue;
     585                        }
     586                        $taxes                           = self::taxes_by_rate( isset( $fees_by_index[ $index ] ) ? $fees_by_index[ $index ] : array() );
     587                        $cart_fees[ $fee_key ]->tax_data = $taxes;
     588                        $cart_fees[ $fee_key ]->tax      = array_sum( $taxes );
     589                        $sent[ $fee_key ]                = true;
     590                }
     591                foreach ( $cart_fees as $fee_key => $fee ) {
     592                        if ( isset( $sent[ $fee_key ] ) || ! is_object( $fee ) || empty( $fee->tax_data ) || ! is_array( $fee->tax_data ) ) {
     593                                continue;
     594                        }
     595                        foreach ( $fee->tax_data as $rate_id => $amount ) {
     596                                $fee_taxes[ $rate_id ] = ( isset( $fee_taxes[ $rate_id ] ) ? $fee_taxes[ $rate_id ] : 0.0 ) + (float) $amount;
     597                        }
     598                }
     599                return $fee_taxes;
     600        }
     601
     602        /**
     603         * Puts the shipping tax answered on the shipping line of the cart's first package, and none on any other, so it is
     604         * never counted twice (bug book B-281). Decided by the package, so a second pass over the same order decides the same way.
     605         *
     606         * @param \WC_Order_Item_Shipping $item        Shipping line.
     607         * @param string                  $package_key Package key.
     608         * @param array                   $package     Package.
     609         * @param \WC_Order               $order       Order.
     610         */
     611        public function apply_exact_shipping_taxes( $item, $package_key, $package, $order ) {
     612                if ( ! $this->is_tax_calculation_enabled() ) {
     613                        return;
     614                }
     615                $shipping_taxes = $this->session_shipping_taxes();
     616                if ( ! is_array( $shipping_taxes ) ) {
     617                        return;
     618                }
     619                $packages  = WC()->shipping() ? WC()->shipping()->get_packages() : array();
     620                $first_key = empty( $packages ) ? 0 : array_key_first( $packages );
     621                $item->set_taxes( self::shipping_line_taxes( (string) $package_key === (string) $first_key, $shipping_taxes ) );
     622        }
     623
     624        /**
     625         * Check if WonderTax Labs answers this store's checkout tax. Server-driven: on only while WonderTax_Tax_Service
     626         * holds the store's checkout tax.
    165627         *
    166628         * @return bool
    167629         */
    168         private function is_tax_calculation_enabled()
    169         {
    170                 $connected = (bool) get_option('wondertax_connected', false);
    171                 $enabled = (bool) get_option('wondertax_tax_calculation_enabled', false);
    172 
    173                 return $connected && $enabled;
    174         }
    175 
    176         /**
    177          * Build tax request payload
    178          *
    179          * @param array $args Tax calculation arguments.
    180          * @return array
    181          */
    182         private function build_tax_request($args)
    183         {
    184                 // Get cart data
    185                 $cart = WC()->cart;
     630        private function is_tax_calculation_enabled() {
     631                $connected = (bool) get_option( 'wondertax_connected', false );
     632
     633                return $connected && class_exists( 'WonderTax_Tax_Service' ) && WonderTax_Tax_Service::is_taken_over();
     634        }
     635
     636        /**
     637         * Build tax request payload: each line's product (the parent product id, as the order's line names it), its total after
     638         * coupons once WooCommerce has totaled the cart, its tax class and tax status; each fee that is not zero (a negative fee
     639         * is a discount), its total, tax class and tax status; the shipping, whether its method is taxed in WooCommerce (a fact:
     640         * WonderTax Labs taxes it either way, 📗 integration-import · I42), the chosen method of each package; and the store's
     641         * currency.
     642         *
     643         * @param array    $args Tax calculation arguments.
     644         * @param \WC_Cart $cart Cart object.
     645         * @return array { request: array, keys: string[], fee_keys: string[] } - the cart item keys and the sent fees' cart keys,
     646         *               in request order.
     647         */
     648        private function build_tax_request( $args, $cart ) {
    186649                $line_items = array();
    187 
    188                 if ($cart) {
    189                         foreach ($cart->get_cart() as $cart_item) {
    190                                 $product = $cart_item['data'];
    191                                 $line_items[] = array(
    192                                         'product_id' => $product->get_id(),
    193                                         'quantity' => $cart_item['quantity'],
    194                                         'price' => (float) $product->get_price(),
    195                                         'tax_class' => $product->get_tax_class(),
    196                                 );
    197                         }
    198                 }
     650                $keys       = array();
     651
     652                foreach ( $cart->get_cart() as $cart_key => $cart_item ) {
     653                        $product = $cart_item['data'];
     654                        $line    = array(
     655                                'product_id'   => isset( $cart_item['product_id'] ) ? (int) $cart_item['product_id'] : (int) $product->get_id(),
     656                                'variation_id' => isset( $cart_item['variation_id'] ) ? (int) $cart_item['variation_id'] : 0,
     657                                'quantity'     => $cart_item['quantity'],
     658                                'price'        => (float) $product->get_price(),
     659                                'tax_class'    => $product->get_tax_class(),
     660                                'tax_status'   => $product->get_tax_status(),
     661                        );
     662                        // The line's total after its coupons, which is what the order import taxes.
     663                        if ( isset( $cart_item['line_total'] ) ) {
     664                                $line['line_total'] = (float) $cart_item['line_total'];
     665                        }
     666                        $line_items[] = $line;
     667                        $keys[]       = $cart_key;
     668                }
     669
     670                // Each fee that is not zero: one above zero is taxed as the order's import taxes its fee line, and a negative fee (a
     671                // discount) lowers the lines, the charged fees and the shipping as the import lowers them.
     672                $fees      = array();
     673                $fee_keys  = array();
     674                $cart_fees = $this->cart_fees( $cart );
     675                foreach ( $cart_fees as $fee_key => $fee ) {
     676                        if ( ! is_object( $fee ) || ! isset( $fee->total ) || 0.0 === (float) $fee->total ) {
     677                                continue;
     678                        }
     679                        $fees[]     = array(
     680                                // The fee's name: WonderTax Labs classifies a fee by its name, as the order's import does.
     681                                'name'       => isset( $fee->name ) ? (string) $fee->name : '',
     682                                'total'      => (float) $fee->total,
     683                                'tax_class'  => isset( $fee->tax_class ) ? (string) $fee->tax_class : '',
     684                                'tax_status' => ! empty( $fee->taxable ) ? 'taxable' : 'none',
     685                        );
     686                        $fee_keys[] = $fee_key;
     687                }
     688
     689                $shipping = $this->chosen_shipping();
    199690
    200691                return array(
    201                         'country' => $args['country'],
    202                         'state' => $args['state'],
    203                         'postcode' => isset($args['postcode']) ? $args['postcode'] : '',
    204                         'city' => isset($args['city']) ? $args['city'] : '',
    205                         'address_1' => isset($args['address']) ? $args['address'] : '',
    206                         'line_items' => $line_items,
    207                         'shipping_cost' => $cart ? (float) $cart->get_shipping_total() : 0.0,
     692                        'request'  => array(
     693                                'country'          => $args['country'],
     694                                'state'            => $args['state'],
     695                                'postcode'         => isset( $args['postcode'] ) ? $args['postcode'] : '',
     696                                'city'             => isset( $args['city'] ) ? $args['city'] : '',
     697                                'address_1'        => isset( $args['address'] ) ? $args['address'] : '',
     698                                'line_items'       => $line_items,
     699                                'shipping_cost'    => (float) $cart->get_shipping_total(),
     700                                'shipping_taxable' => $shipping['taxable'],
     701                                'shipping_methods' => $shipping['methods'],
     702                                'currency'         => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD',
     703                                'fees'             => $fees,
     704                        ),
     705                        'keys'     => $keys,
     706                        'fee_keys' => $fee_keys,
    208707                );
    209708        }
    210709
    211710        /**
    212          * Call WonderTax Labs tax service
     711         * The chosen shipping rate of each package, as the order's shipping lines will name it (`method_id`, and the rate's
     712         * label as `method_title`), and whether WooCommerce taxes the shipping: not when a chosen method's tax status is "None".
     713         *
     714         * @return array { methods: array, taxable: bool }
     715         */
     716        private function chosen_shipping() {
     717                $methods  = array();
     718                $taxable  = true;
     719                $chosen   = WC()->session ? (array) WC()->session->get( 'chosen_shipping_methods', array() ) : array();
     720                $packages = WC()->shipping() ? WC()->shipping()->get_packages() : array();
     721                foreach ( $chosen as $package_key => $rate_id ) {
     722                        if ( ! isset( $packages[ $package_key ]['rates'][ $rate_id ] ) ) {
     723                                continue;
     724                        }
     725                        $rate      = $packages[ $package_key ]['rates'][ $rate_id ];
     726                        $methods[] = array(
     727                                'method_id'    => (string) $rate->get_method_id(),
     728                                'method_title' => (string) $rate->get_label(),
     729                        );
     730                        $instance  = $rate->get_instance_id() && class_exists( 'WC_Shipping_Zones' )
     731                                ? WC_Shipping_Zones::get_shipping_method( $rate->get_instance_id() )
     732                                : false;
     733                        if ( $instance && isset( $instance->tax_status ) && 'none' === $instance->tax_status ) {
     734                                $taxable = false;
     735                        }
     736                }
     737                return array(
     738                        'methods' => $methods,
     739                        'taxable' => $taxable,
     740                );
     741        }
     742
     743        /**
     744         * The door's reply for this request body, asked once per request.
    213745         *
    214746         * @param array $tax_request Tax request payload.
    215747         * @return array|WP_Error
    216748         */
    217         private function call_tax_service($tax_request)
    218         {
    219                 $backend_url = $this->get_backend_url();
    220                 $webhook_secret = get_option('wondertax_webhook_secret');
    221 
    222                 if (empty($webhook_secret)) {
    223                         return new WP_Error('no_secret', 'Webhook secret not configured');
     749        private function quote( $tax_request ) {
     750                $memo_key = md5( (string) wp_json_encode( $tax_request ) );
     751                if ( ! array_key_exists( $memo_key, $this->quotes ) ) {
     752                        // After a failure the door is skipped for a short while: the store's own rates apply, and no checkout waits.
     753                        if ( get_transient( self::PAUSE_TRANSIENT ) ) {
     754                                return new WP_Error( 'door_paused', 'WonderTax Labs did not answer a moment ago' );
     755                        }
     756                        $reply = $this->call_tax_service( $tax_request );
     757                        if ( is_wp_error( $reply ) && in_array( $reply->get_error_code(), array( 'http_request_failed', 'api_unavailable' ), true ) ) {
     758                                set_transient( self::PAUSE_TRANSIENT, 1, self::PAUSE_SECONDS );
     759                        }
     760                        self::record_door_outcome( $reply );
     761                        $this->quotes[ $memo_key ] = $reply;
     762                }
     763                return $this->quotes[ $memo_key ];
     764        }
     765
     766        /**
     767         * Call WonderTax Labs tax service
     768         *
     769         * @param array $tax_request Tax request payload.
     770         * @return array|WP_Error
     771         */
     772        private function call_tax_service( $tax_request ) {
     773                $backend_url    = WONDERTAX_BACKEND_URL;
     774                $webhook_secret = get_option( 'wondertax_webhook_secret' );
     775
     776                if ( empty( $webhook_secret ) ) {
     777                        return new WP_Error( 'no_secret', 'Webhook secret not configured' );
    224778                }
    225779
    226780                // Build request body
    227                 $body = wp_json_encode($tax_request);
     781                $body = wp_json_encode( $tax_request );
    228782
    229783                // Sign request with webhook secret
    230                 $signature = $this->generate_signature($body, $webhook_secret);
    231 
    232                 // Make API request
     784                $signature = $this->generate_signature( $body, $webhook_secret );
     785
     786                // Make API request. The server finds the store by its source and requires a topic beside the signature.
    233787                $response = wp_remote_post(
    234788                        $backend_url . '/api/woocommerce/tax-service',
    235789                        array(
    236790                                'headers' => array(
    237                                         'Content-Type' => 'application/json',
     791                                        'Content-Type'           => 'application/json',
     792                                        'X-WC-Webhook-Source'    => get_option( 'wondertax_site_url', get_site_url() ),
     793                                        'X-WC-Webhook-Topic'     => 'tax.calculate',
    238794                                        'X-WC-Webhook-Signature' => $signature,
    239795                                ),
    240                                 'body' => $body,
    241                                 'timeout' => 10,
     796                                'body'    => $body,
     797                                'timeout' => self::TIMEOUT,
    242798                        )
    243799                );
    244800
    245                 if (is_wp_error($response)) {
    246                         return $response;
    247                 }
    248 
    249                 $response_code = wp_remote_retrieve_response_code($response);
    250                 if (200 !== $response_code) {
    251                         return new WP_Error(
    252                                 'api_error',
    253                                 sprintf('API returned status %d', $response_code)
    254                         );
    255                 }
    256 
    257                 $response_body = wp_remote_retrieve_body($response);
    258                 return json_decode($response_body, true);
     801                if ( is_wp_error( $response ) ) {
     802                        // No reply (a timeout, a refused connection): a door failure.
     803                        return new WP_Error( 'http_request_failed', $response->get_error_message() );
     804                }
     805
     806                $response_code = (int) wp_remote_retrieve_response_code( $response );
     807                if ( $response_code >= 500 ) {
     808                        return new WP_Error( 'api_unavailable', sprintf( 'API returned status %d', $response_code ) );
     809                }
     810                if ( 200 !== $response_code ) {
     811                        // A refusal names its reason (`refused.message`): it is kept for the store managers' notice.
     812                        $refusal = json_decode( (string) wp_remote_retrieve_body( $response ), true );
     813                        $reason  = is_array( $refusal ) && isset( $refusal['refused']['message'] ) && is_string( $refusal['refused']['message'] )
     814                                ? $refusal['refused']['message']
     815                                : sprintf( 'API returned status %d', $response_code );
     816                        // A refusal of the store (401, 403, 404: its signature, its connection, the tax service off) holds for every
     817                        // checkout; any other is about this one cart (an address, a request it could not read), and is not the store's.
     818                        $store_wide = in_array( $response_code, array( 401, 403, 404 ), true );
     819                        return new WP_Error( $store_wide ? 'api_error' : 'cart_refused', $reason );
     820                }
     821
     822                $response_body = wp_remote_retrieve_body( $response );
     823                $decoded       = json_decode( $response_body, true );
     824                if ( ! is_array( $decoded ) ) {
     825                        return new WP_Error( 'api_error', 'API returned an unreadable answer' );
     826                }
     827                return $decoded;
    259828        }
    260829
    … …  
    266835         * @return string
    267836         */
    268         private function generate_signature($body, $secret)
    269         {
    270                 return base64_encode(hash_hmac('sha256', $body, $secret, true));
    271         }
    272 
    273         /**
    274          * Parse tax response from WonderTax Labs
    275          *
    276          * @param array $tax_response Tax response from API.
    277          * @param array $args Original tax calculation arguments.
    278          * @return array WooCommerce tax rates.
    279          */
    280         private function parse_tax_response($tax_response, $args)
    281         {
    282                 if (empty($tax_response['taxes']) || !is_array($tax_response['taxes'])) {
    283                         return array();
    284                 }
    285 
    286                 $rates = array();
    287 
    288                 foreach ($tax_response['taxes'] as $index => $tax) {
    289                         $rate_id = isset($tax['rate_id']) ? $tax['rate_id'] : 'wondertax_' . $index;
    290                         $label = isset($tax['label']) ? $tax['label'] : 'Sales Tax';
    291                         $rate_percent = isset($tax['rate']) ? (float) $tax['rate'] : 0.0;
    292 
    293                         // Convert to WooCommerce rate format
    294                         $rates[$rate_id] = array(
    295                                 'rate' => $rate_percent,
    296                                 'label' => $label,
    297                                 'shipping' => 'yes',
    298                                 'compound' => isset($tax['compound']) && $tax['compound'] ? 'yes' : 'no',
    299                         );
    300                 }
    301 
    302                 return $rates;
    303         }
    304 
    305         /**
    306          * Get backend URL
    307          *
     837        private function generate_signature( $body, $secret ) {
     838                return base64_encode( hash_hmac( 'sha256', $body, $secret, true ) );
     839        }
     840
     841        /**
     842         * Counts the door's consecutive failures — a refusal of the store or no reply, each leaving the store's own rates at
     843         * checkout — and clears the count on an answered checkout. ⭐ A refusal of one cart (`cart_refused`: one buyer's address)
     844         * is not the store's failure, and is not counted. ⛔ Never a give-back: what follows a run of failures is for people to
     845         * decide.
     846         *
     847         * @param array|WP_Error $reply The door's reply.
     848         */
     849        private static function record_door_outcome( $reply ) {
     850                if ( ! is_wp_error( $reply ) ) {
     851                        if ( is_array( $reply ) && isset( $reply['lines'] ) && false !== get_option( self::FAILURES_OPTION, false ) ) {
     852                                delete_option( self::FAILURES_OPTION );
     853                        }
     854                        return;
     855                }
     856                if ( in_array( $reply->get_error_code(), array( 'no_secret', 'cart_refused' ), true ) ) {
     857                        return;
     858                }
     859                $failures = get_option( self::FAILURES_OPTION, array() );
     860                $count    = is_array( $failures ) && isset( $failures['count'] ) ? (int) $failures['count'] : 0;
     861                update_option(
     862                        self::FAILURES_OPTION,
     863                        array(
     864                                'count'  => $count + 1,
     865                                'reason' => $reply->get_error_message(),
     866                                'at'     => time(),
     867                        ),
     868                        false
     869                );
     870        }
     871
     872        /**
     873         * ⭐ THE STORE'S MANAGERS ARE TOLD when WonderTax Labs has failed to answer several checkout tax requests in a row (a
     874         * request is any cart totaling the door is asked for, not only an order): the store's own WooCommerce rates applied to
     875         * them. WonderTax Labs is told too, by its own records of each refusal; nothing is switched back automatically.
     876         */
     877        public static function render_door_failure_notice() {
     878                if ( ! current_user_can( 'manage_woocommerce' ) ) {
     879                        return;
     880                }
     881                $failures = get_option( self::FAILURES_OPTION, array() );
     882                if ( ! is_array( $failures ) || (int) ( isset( $failures['count'] ) ? $failures['count'] : 0 ) < self::FAILURES_NOTICE_AT ) {
     883                        return;
     884                }
     885                ?>
     886                <div class="notice notice-warning">
     887                        <p>
     888                                <strong><?php esc_html_e( 'WonderTax Labs: Audita™', 'wondertax-labs-audita' ); ?></strong>
     889                                <?php
     890                                printf(
     891                                        /* translators: 1: number of checkout tax requests, 2: the last reason given */
     892                                        esc_html__( 'WonderTax Labs did not answer the last %1$d checkout tax requests, so your store\'s own WooCommerce tax rates applied to them. The last reason: %2$s', 'wondertax-labs-audita' ),
     893                                        absint( $failures['count'] ),
     894                                        esc_html( isset( $failures['reason'] ) ? (string) $failures['reason'] : '' )
     895                                );
     896                                ?>
     897                                <a href="mailto:service@wonder.tax"><?php esc_html_e( 'Contact WonderTax Labs', 'wondertax-labs-audita' ); ?></a>
     898                        </p>
     899                </div>
     900                <?php
     901        }
     902
     903        /**
     904         * Keeps the label of each rate this answer names, by its rate id, for the order's tax lines (answered_rate_label): only
     905         * this answer's, and never for a rate id that also names one of the store's own tax rates, whose label stays the store's.
     906         *
     907         * @param array $reply The door's reply.
     908         */
     909        private function remember_rate_labels( $reply ) {
     910                $labels = array();
     911                if ( isset( $reply['taxes'] ) && is_array( $reply['taxes'] ) ) {
     912                        foreach ( $reply['taxes'] as $tax ) {
     913                                if ( ! isset( $tax['rate_id'], $tax['label'] ) || ! is_string( $tax['label'] ) || '' === $tax['label'] ) {
     914                                        continue;
     915                                }
     916                                $rate_id = (string) $tax['rate_id'];
     917                                if ( ! self::names_store_rate( $rate_id ) ) {
     918                                        $labels[ $rate_id ] = $tax['label'];
     919                                }
     920                        }
     921                }
     922                $this->set_session_rate_labels( $labels );
     923        }
     924
     925        /**
     926         * Does this rate id also name one of the store's own WooCommerce tax rates? Those ids are whole numbers, and so are many
     927         * of the jurisdiction codes WonderTax Labs answers with.
     928         *
     929         * @param string $rate_id The rate id.
     930         * @return bool
     931         */
     932        private static function names_store_rate( $rate_id ) {
     933                if ( ! preg_match( '/^\d+$/', $rate_id ) ) {
     934                        return false;
     935                }
     936                if ( ! class_exists( 'WC_Tax' ) || ! method_exists( 'WC_Tax', '_get_tax_rate' ) ) {
     937                        // Unable to tell: never relabel a rate the store may own.
     938                        return true;
     939                }
     940                return ! empty( WC_Tax::_get_tax_rate( (int) $rate_id ) );
     941        }
     942
     943        /**
     944         * Keeps the rate labels of the answer the cart carries now in the session, when there is one; an empty set clears them.
     945         *
     946         * @param array $labels The labels, by rate id.
     947         */
     948        private function set_session_rate_labels( $labels ) {
     949                if ( ! WC()->session ) {
     950                        return;
     951                }
     952                if ( empty( $labels ) && empty( WC()->session->get( self::RATE_LABELS_SESSION ) ) ) {
     953                        return;
     954                }
     955                WC()->session->set( self::RATE_LABELS_SESSION, $labels );
     956        }
     957
     958        /**
     959         * The label of a rate WonderTax Labs answered — its jurisdiction — where WooCommerce, not knowing our rate ids, would
     960         * name it "Tax".
     961         *
     962         * @param string     $label   The label WooCommerce found.
     963         * @param string|int $rate_id The rate id.
    308964         * @return string
    309965         */
    310         private function get_backend_url()
    311         {
    312                 return 'https://app.wonder.tax';
     966        public function answered_rate_label( $label, $rate_id ) {
     967                if ( ! function_exists( 'WC' ) || ! WC()->session ) {
     968                        return $label;
     969                }
     970                $labels = (array) WC()->session->get( self::RATE_LABELS_SESSION, array() );
     971                return isset( $labels[ (string) $rate_id ] ) ? (string) $labels[ (string) $rate_id ] : $label;
    313972        }
    314973}
  • wondertax-labs-audita/trunk/readme.txt

    r3713774 r3814612  
    1 === WonderTax Labs: Audita ===
     1=== WonderTax Labs: Audita™ ===
    22Contributors: wondertaxlabs
    33Tags: woocommerce, tax, sales tax, tax compliance, automation
    … …  
    55Tested up to: 7.0
    66Requires PHP: 8.0
    7 Stable tag: 1.3.7
     7Stable tag: 1.4.1
    88License: GPLv3 or later
    99License URI: https://www.gnu.org/licenses/gpl-3.0.html
    1010
    11 Connect your WooCommerce store to WonderTax Labs for automated zero-cost and zero-risk sales tax auditing.
     11Connect your WooCommerce store to WonderTax Labs: Audita™, which audits the sales tax your store charges at zero cost and zero risk.
    1212
    1313== Description ==
    1414
    15 **Automate Your Sales Tax Compliance**
    16 
    17 WonderTax Labs: Audita seamlessly integrates your WooCommerce store with WonderTax Labs for automated sales tax tracking, compliance, and real-time tax calculation at checkout.
     15**Audit the Sales Tax Your Store Charges**
     16
     17WonderTax Labs: Audita™ feeds your WooCommerce orders to WonderTax Labs Audita™, which audits the sales tax your store charges on every order against the tax each order owes.
    1818
    1919### Features
    2020
    21 * **Real-Time Tax Calculation** - Accurate sales tax rates calculated during checkout based on customer location
     21* **Sales Tax Auditing** - Every order is audited by Audita™: the tax your store charged against the tax the order owes
    2222* **Block Checkout Support** - Full compatibility with WooCommerce Cart and Checkout Blocks
    23 * **Automatic Order Sync** - All orders automatically synced to WonderTax Labs for tax compliance tracking
     23* **Automatic Order Sync** - All orders automatically synced to WonderTax Labs Audita™ for auditing
    2424* **Multi-Jurisdiction Support** - Handles complex tax scenarios across all US states and jurisdictions
    2525* **Historical Order Import** - Import and analyze past orders for comprehensive tax compliance
    2626* **Secure Integration** - Enterprise-grade encryption for all credentials and data transmission
    27 * **Easy Setup** - Simple OAuth connection process with minimal configuration
     27* **Easy Setup** - Connect from your WordPress admin in a few clicks
     28* **Checkout Tax with Reporta™** - With a Reporta™ account, WonderTax Labs answers your checkout tax (see External Services)
    2829
    2930### How It Works
    3031
    31321. **Install & Connect** - Install the plugin and connect your store to WonderTax Labs
    32 2. **Enable Tax Calculation** - Optionally enable real-time tax calculation at checkout
    33 3. **Automatic Tracking** - All orders are automatically tracked for tax compliance
    34 4. **Stay Compliant** - WonderTax Labs handles the complexity of multi-state tax compliance
     332. **Automatic Auditing** - All orders are automatically fed to Audita™, which audits the tax your store charges
     343. **Stay Compliant** - WonderTax Labs handles the complexity of multi-state tax compliance
    3535
    3636### Requirements
    … …  
    4444### Privacy & Security
    4545
    46 This plugin connects to WonderTax Labs (app.wonder.tax) to provide tax calculation and compliance services. When you connect your store:
     46This plugin connects to WonderTax Labs (app.wonder.tax) to provide sales tax auditing and compliance services. When you connect your store:
    4747
    4848* Order data (customer location, product details, amounts) is sent to WonderTax Labs
    … …  
    80802. Log in to your WonderTax Labs account (or create one)
    81813. Authorize the connection
    82 4. Optionally enable real-time tax calculation
    83 5. Done! Your orders will now sync automatically
     824. Done! Your orders will now sync automatically
    8483
    8584== Frequently Asked Questions ==
    … …  
    8988Yes, you need a WonderTax Labs account to use this plugin. You can sign up for free at [app.wonder.tax](https://app.wonder.tax).
    9089
    91 = Does this plugin calculate taxes at checkout? =
    92 
    93 Yes, when enabled, the plugin provides real-time tax calculation during checkout. This feature is optional and can be toggled in the settings.
     90= What does Audita™ audit? =
     91
     92The sales tax your store charges. Every order is compared with the tax it owes, so an error is found before an auditor finds it.
    9493
    9594= Will my historical orders be imported? =
    … …  
    105104Currently, WonderTax Labs focuses on US sales tax compliance. Support for additional countries may be added in the future.
    106105
    107 = Does this replace WooCommerce's built-in tax system? =
    108 
    109 When real-time tax calculation is enabled, WonderTax Labs provides tax rates instead of WooCommerce's built-in system. You can disable this feature at any time to revert to WooCommerce's tax settings.
    110 
    111106= How do I disconnect my store? =
    112107
    113 Navigate to WooCommerce > WonderTax Labs and click "Disconnect Store". This will remove all stored credentials and stop order syncing.
     108Navigate to WooCommerce > WonderTax Labs and click "Disconnect Store". This tells WonderTax Labs to stop importing your orders, removes the webhooks WonderTax Labs registered on your store, deletes the WooCommerce API key the plugin created and the stored credentials, and, if WonderTax Labs answers your checkout tax, puts your own tax settings back. Your transactions already recorded in WonderTax Labs are kept there.
    114109
    115110= Where can I get support? =
    … …  
    119114== Screenshots ==
    120115
    121 1. Settings page - Connected state with tax calculation toggle
     1161. Settings page - Connected state
    1221172. Settings page - Not connected state with features list
    123 3. Real-time tax calculation during checkout
    124118
    125119== Changelog ==
     120
     121= 1.4.1 - 2026-11-13 =
     122* Changed: Connecting no longer sends the site's admin email address to WonderTax Labs; you sign in to WonderTax Labs yourself
     123* Changed: Reconnecting keeps your working connection until WonderTax Labs confirms the new one
     124* Changed: Disconnecting removes the API key the plugin created and the webhooks WonderTax Labs or earlier versions registered, and WonderTax Labs stops importing your orders
     125* Changed: A disconnect that cannot put your own tax settings back right away changes nothing and asks you to try again
     126* Changed: The connection status is read with a signed request
     127* Changed: Each tax line shows the name of its jurisdiction
     128* Changed: Each fee's name is sent with the checkout, so WonderTax Labs can classify it
     129* Changed: The settings page says whether WonderTax Labs answers your checkout tax
     130* Added: A notice when WonderTax Labs has not answered several checkout tax requests in a row (a refusal of one cart, such as an address, does not count); it clears once WonderTax Labs answers again, starts or stops answering your checkout tax, or the store is disconnected
     131* Added: Vertex, Quaderno and Stripe Tax are recognized as other tax engines, checked while WonderTax Labs answers your checkout tax too
     132* Removed: The unused app-started connection flow and the plugin's own webhook registration
     133* Security: Every settings action requires the Manage WooCommerce capability
     134
     135= 1.4.0 - 2026-11-06 =
     136* Changed: Settings sync with your WonderTax Labs account
     137* Changed: Checkout requests carry the line details Audita™ needs
     138* Removed: The manual tax setting
    126139
    127140= 1.3.7 - 2026-09-25 =
    … …  
    191204
    192205= 1.2.4 - 2025-05-07 =
    193 * Changed: Plugin title changed to "WonderTax Labs: Audita" throughout admin UI
    194 * Changed: Menu item and page title updated to "WonderTax Labs: Audita"
     206* Changed: Plugin title changed to "WonderTax Labs: Audita™" throughout admin UI
     207* Changed: Menu item and page title updated to "WonderTax Labs: Audita™"
    195208
    196209= 1.2.3 - 2025-05-07 =
    … …  
    286299== Upgrade Notice ==
    287300
     301= 1.4.1 =
     302Reconnecting is safer, disconnecting stops order imports, and tax lines name their jurisdictions. Recommended for all users.
     303
     304= 1.4.0 =
     305WonderTax Labs: Audita™. Recommended for all users.
     306
    288307= 1.3.6 =
    289308Additional WordPress.org plugin review compliance fixes.
    … …  
    320339
    321340= 1.2.4 =
    322 Plugin title updated to "WonderTax Labs: Audita".
     341Plugin title updated to "WonderTax Labs: Audita™".
    323342
    324343= 1.2.3 =
    … …  
    375394== External Services ==
    376395
    377 This plugin connects to WonderTax Labs (app.wonder.tax) to provide tax calculation and compliance services.
     396This plugin connects to WonderTax Labs (app.wonder.tax) to provide sales tax auditing and compliance services. It contacts that service:
     397
     398* **When you connect your store** — WonderTax Labs fetches from this site, once, with a one-time token, the store's new API credentials and the store's name (offered as the name of a new business); you sign in to WonderTax Labs yourself, and no account is identified or created from this site. The plugin then reads the connection's status with a signed request.
     399* **Each time you open the plugin's settings page** — the plugin reads the connection's status with a signed request and, when it is answered, sends the same signed report as the hourly sync.
     400* **When an order is created, updated or deleted** — WooCommerce delivers the order to WonderTax Labs through the webhooks WonderTax Labs registers on connect.
     401* **Every hour** — the plugin reports its version and the store's tax settings, and reads whether WonderTax Labs answers the store's checkout tax.
     402* **At checkout, only while WonderTax Labs answers your checkout tax (Reporta™)** — the cart's address and its lines, fees and shipping are sent, and the tax answered is applied. While it does, the plugin records your own tax settings, sets the tax basis to the shipping address and keeps "Enable taxes" on; your settings are put back when you disconnect or deactivate the plugin.
     403* **When you open the WonderTax Labs dashboard or switch Live/Test Mode** — a signed link or request.
     404* **When you disconnect or deactivate the plugin** — a signed notice tells WonderTax Labs that the plugin gave your own tax settings back (after a disconnect it also stops importing your orders). A notice WonderTax Labs does not accept is sent again with the hourly sync until it is, after a disconnect as well as once a deactivated plugin is active again.
    378405
    379406**Service URL:** https://app.wonder.tax
    … …  
    388415* Order information (amounts, customer location, product details)
    389416* Store information (name, currency, timezone)
     417* The plugin's version and the store's tax settings (whether taxes are enabled, which address they are based on, whether standard tax rates exist, and whether prices are entered with tax), synced hourly
     418* At checkout, when your WonderTax Labs account requires them, the cart's line details (amounts, tax classes, shipping) and the customer's address
    390419* No payment or sensitive financial data is transmitted
    391420
  • wondertax-labs-audita/trunk/uninstall.php

    r3556520 r3814612  
    99
    1010// Exit if accessed directly or if uninstall is not called from WordPress
    11 if (!defined('WP_UNINSTALL_PLUGIN')) {
     11if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    1212        exit;
    1313}
    … …  
    1515global $wpdb;
    1616
     17// The classes name the takeover's options, its cron hook and the door's pause; loading them runs nothing.
     18require_once __DIR__ . '/includes/class-wondertax-tax-service.php';
     19require_once __DIR__ . '/includes/class-wondertax-tax-calc.php';
     20require_once __DIR__ . '/includes/class-wondertax-not-taxable-notice.php';
     21
    1722/**
    1823 * Read values needed for cleanup BEFORE deleting options
    1924 */
    20 $wondertax_api_key_id = get_option('wondertax_api_key_id');
    21 $wondertax_webhook_ids = get_option('wondertax_webhook_ids', array());
     25$wondertax_api_key_id  = get_option( 'wondertax_api_key_id' );
     26$wondertax_webhook_ids = get_option( 'wondertax_webhook_ids', array() );
     27$wondertax_pending     = get_option( 'wondertax_pending_connection', null );
    2228
    2329/**
    2430 * Delete WooCommerce API key created by plugin
    2531 */
    26 if ($wondertax_api_key_id) {
     32if ( $wondertax_api_key_id ) {
    2733        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, uninstall cleanup
    2834        $wpdb->delete(
    2935                $wpdb->prefix . 'woocommerce_api_keys',
    30                 array('key_id' => $wondertax_api_key_id),
    31                 array('%d')
     36                array( 'key_id' => $wondertax_api_key_id ),
     37                array( '%d' )
    3238        );
    3339}
    3440
    3541/**
    36  * Delete all webhooks created by plugin
     42 * Delete the WooCommerce API key of a connect left in progress
    3743 */
    38 if (!empty($wondertax_webhook_ids) && class_exists('WC_Webhook')) {
    39         foreach ($wondertax_webhook_ids as $wondertax_webhook_id) {
    40                 $wondertax_webhook = new WC_Webhook($wondertax_webhook_id);
    41                 if ($wondertax_webhook->get_id()) {
    42                         $wondertax_webhook->delete(true);
     44if ( is_array( $wondertax_pending ) && ! empty( $wondertax_pending['api_key_id'] ) ) {
     45        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce API keys table, uninstall cleanup
     46        $wpdb->delete(
     47                $wpdb->prefix . 'woocommerce_api_keys',
     48                array( 'key_id' => (int) $wondertax_pending['api_key_id'] ),
     49                array( '%d' )
     50        );
     51}
     52
     53/**
     54 * Delete all webhooks created by earlier versions of the plugin (it registers none now)
     55 */
     56if ( ! empty( $wondertax_webhook_ids ) && class_exists( 'WC_Webhook' ) ) {
     57        foreach ( $wondertax_webhook_ids as $wondertax_webhook_id ) {
     58                $wondertax_webhook = new WC_Webhook( $wondertax_webhook_id );
     59                if ( $wondertax_webhook->get_id() ) {
     60                        $wondertax_webhook->delete( true );
    4361                }
    4462        }
    … …  
    4866 * Clear any scheduled events
    4967 */
    50 wp_clear_scheduled_hook('wondertax_cleanup');
     68wp_clear_scheduled_hook( WonderTax_Tax_Service::CRON_HOOK );
    5169
    5270/**
    5371 * Delete all plugin options (after cleanup is complete)
    5472 */
    55 $wondertax_options = array(
    56         'wondertax_version',
    57         'wondertax_connected',
    58         'wondertax_consumer_key',
    59         'wondertax_consumer_secret',
    60         'wondertax_webhook_secret',
    61         'wondertax_site_url',
    62         'wondertax_tax_calculation_enabled',
    63         'wondertax_webhook_ids',
    64         'wondertax_api_key_id',
    65         'wondertax_dev_backend_url',
    66         'wondertax_install_secret',
     73$wondertax_options = array_merge(
     74        array(
     75                'wondertax_version',
     76                'wondertax_connected',
     77                'wondertax_consumer_key',
     78                'wondertax_consumer_secret',
     79                'wondertax_webhook_secret',
     80                'wondertax_site_url',
     81                // No longer read or written; a site upgraded from a release with the tax toggle can still hold the row.
     82                'wondertax_tax_calculation_enabled',
     83                'wondertax_webhook_ids',
     84                'wondertax_api_key_id',
     85                'wondertax_install_secret',
     86                'wondertax_pending_connection',
     87                'wondertax_door_failures',
     88        ),
     89        WonderTax_Tax_Service::OPTIONS
    6790);
    6891
    69 foreach ($wondertax_options as $wondertax_option) {
    70         delete_option($wondertax_option);
     92foreach ( $wondertax_options as $wondertax_option ) {
     93        delete_option( $wondertax_option );
    7194}
     95delete_transient( WonderTax_Tax_Calc::PAUSE_TRANSIENT );
     96delete_transient( WonderTax_Not_Taxable_Notice::CACHE_TRANSIENT );
    7297
    7398/**
  • wondertax-labs-audita/trunk/wondertax-labs-audita.php

    r3713774 r3814612  
    11<?php
    22/**
    3  * Plugin Name: WonderTax Labs: Audita
     3 * Plugin Name: WonderTax Labs: Audita™
    44 * Plugin URI: https://app.wonder.tax/integrations/woocommerce
    5  * Description: Connect your WooCommerce store to WonderTax Labs for automated zero-cost and zero-risk sales tax auditing. Handles OAuth setup, webhook registration, and tax service integration with Live/Test Mode support. Includes easy access to WonderTax Labs App.
    6  * Version: 1.3.7
     5 * Description: Connect your WooCommerce store to WonderTax Labs: Audita™, which audits the sales tax your store charges at zero cost and zero risk. Imports your orders with Live/Test Mode support, and with Reporta™ answers your checkout tax. Includes easy access to the WonderTax Labs app.
     6 * Version: 1.4.1
    77 * Author: WonderTax Labs
    88 * Author URI: https://app.wonder.tax
    … …  
    2424
    2525// Define plugin constants
    26 define('WONDERTAX_VERSION', '1.3.7');
     26define('WONDERTAX_VERSION', '1.4.1');
     27define('WONDERTAX_BACKEND_URL', 'https://app.wonder.tax');
    2728define('WONDERTAX_PLUGIN_DIR', plugin_dir_path(__FILE__));
    2829define('WONDERTAX_PLUGIN_URL', plugin_dir_url(__FILE__));
    … …  
    6465        <div class="notice notice-error">
    6566                <p>
    66                         <strong><?php esc_html_e('WonderTax Labs: Audita', 'wondertax-labs-audita'); ?></strong>
     67                        <strong><?php esc_html_e('WonderTax Labs: Audita™', 'wondertax-labs-audita'); ?></strong>
    6768                        <?php esc_html_e('requires WooCommerce to be installed and active.', 'wondertax-labs-audita'); ?>
    6869                        <a href="<?php echo esc_url(admin_url('plugin-install.php?s=woocommerce&tab=search&type=term')); ?>">
    … …  
    8283        <div class="notice notice-error">
    8384                <p>
    84                         <strong><?php esc_html_e('WonderTax Labs: Audita', 'wondertax-labs-audita'); ?></strong>
     85                        <strong><?php esc_html_e('WonderTax Labs: Audita™', 'wondertax-labs-audita'); ?></strong>
    8586                        <?php
    8687                        printf(
    … …  
    219220        // Load plugin classes
    220221        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-admin.php';
    221         require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-oauth.php';
    222         require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-webhooks.php';
     222        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-tax-service.php';
    223223        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-tax-calc.php';
     224        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-not-taxable-notice.php';
    224225
    225226        // Initialize components
    226227        WonderTax_Admin::get_instance();
    227         WonderTax_OAuth::get_instance();
    228         WonderTax_Webhooks::get_instance();
    229228        WonderTax_Tax_Calc::get_instance();
     229
     230        // A checkout WonderTax Labs keeps failing to answer is named to the store's managers (the store charged its own rates).
     231        add_action('admin_notices', array('WonderTax_Tax_Calc', 'render_door_failure_notice'));
     232
     233        // The products WooCommerce marks not taxable, which WonderTax Labs taxes, named in the WordPress admin
     234        WonderTax_Not_Taxable_Notice::register_hooks();
    230235
    231236        // Register REST API endpoint for token exchange
    232237        add_action('rest_api_init', 'wondertax_register_token_exchange_endpoint');
     238
     239        // Hourly sync of the store's checkout tax setting with WonderTax Labs. Scheduled here as well as on activation,
     240        // because an update does not run the activation hook.
     241        add_action(WonderTax_Tax_Service::CRON_HOOK, 'wondertax_run_tax_service_sync');
     242        WonderTax_Tax_Service::register_hooks();
     243        if (!wp_next_scheduled(WonderTax_Tax_Service::CRON_HOOK)) {
     244                wp_schedule_event(time() + MINUTE_IN_SECONDS, 'hourly', WonderTax_Tax_Service::CRON_HOOK);
     245        }
    233246}
    234247add_action('plugins_loaded', 'wondertax_init');
     248
     249/**
     250 * Hourly WP-cron: reads the tax service WonderTax Labs asks for and moves the store to it.
     251 */
     252function wondertax_run_tax_service_sync()
     253{
     254        if (class_exists('WonderTax_Tax_Service')) {
     255                WonderTax_Tax_Service::sync();
     256        }
     257}
    235258
    236259/**
    … …  
    253276 *
    254277 * Security model:
    255  * - Token is one-time use, 5-minute expiry
     278 * - Token is one-time use, 15-minute expiry: WonderTax Labs redeems it as the browser lands (WonderTax_Admin::TOKEN_TTL)
    256279 * - Exchange happens server-to-server (not via browser)
    257  * - Install secret is returned so WonderTax can verify future webhooks
     280 * - The connection's install secret is returned so WonderTax Labs can verify the signed link and every later signed call.
     281 *   A connect in progress serves its PENDING secret: the store's working connection keeps its own until WonderTax Labs
     282 *   confirms the new one (WonderTax_Admin::confirm_pending_connection).
    258283 *
    259284 * @param WP_REST_Request $request The REST request
    … …  
    299324        delete_transient($transient_key);
    300325
    301         // Return credentials along with install secret for future HMAC verification
    302         // This is secure because:
     326        // Return credentials along with the connection's install secret for HMAC verification. This is secure because:
    303327        // 1. Exchange happens server-to-server over HTTPS
    304328        // 2. Token was one-time use and is now deleted
    305         // 3. Install secret allows WonderTax to verify future webhook signatures
     329        // 3. The install secret lets WonderTax Labs verify this connect link and every later signed call
     330        $install_secret = isset($credentials['install_secret']) ? (string) $credentials['install_secret'] : wondertax_get_install_secret();
     331        unset($credentials['install_secret']);
    306332        return new WP_REST_Response(array(
    307333                'success' => true,
    308334                'credentials' => $credentials,
    309                 'install_secret' => wondertax_get_install_secret(),
     335                'install_secret' => $install_secret,
    310336        ), 200);
    311337}
    … …  
    320346                deactivate_plugins(WONDERTAX_PLUGIN_BASENAME);
    321347                wp_die(
    322                         esc_html__('WonderTax Labs: Audita requires PHP 8.0 or higher.', 'wondertax-labs-audita'),
     348                        esc_html__('WonderTax Labs: Audita™ requires PHP 8.0 or higher.', 'wondertax-labs-audita'),
    323349                        esc_html__('Plugin Activation Error', 'wondertax-labs-audita'),
    324350                        array('back_link' => true)
    … …  
    329355                deactivate_plugins(WONDERTAX_PLUGIN_BASENAME);
    330356                wp_die(
    331                         esc_html__('WonderTax Labs: Audita requires WooCommerce to be installed and active.', 'wondertax-labs-audita'),
     357                        esc_html__('WonderTax Labs: Audita™ requires WooCommerce to be installed and active.', 'wondertax-labs-audita'),
    332358                        esc_html__('Plugin Activation Error', 'wondertax-labs-audita'),
    333359                        array('back_link' => true)
    … …  
    337363        // Set default options
    338364        add_option('wondertax_version', WONDERTAX_VERSION);
    339         add_option('wondertax_tax_calculation_enabled', false);
    340365
    341366        // Set flag to redirect to settings page after activation (store user ID for security)
    … …  
    393418function wondertax_deactivate()
    394419{
    395         // Clean up scheduled events if any
    396         wp_clear_scheduled_hook('wondertax_cleanup');
     420        require_once WONDERTAX_PLUGIN_DIR . 'includes/class-wondertax-tax-service.php';
     421
     422        // Clean up scheduled events
     423        wp_clear_scheduled_hook(WonderTax_Tax_Service::CRON_HOOK);
     424
     425        // A deactivated plugin answers no checkout, so the store's own tax setting is put back now, and WonderTax Labs is
     426        // told (it keeps its record of that setting until the plugin is back).
     427        WonderTax_Tax_Service::give_back('deactivated');
    397428}
    398429register_deactivation_hook(__FILE__, 'wondertax_deactivate');
Note: See TracChangeset for help on using the changeset viewer.