Plugin Directory

Changeset 3751625


Ignore:
Timestamp:
10/17/2026 08:16:54 AM (4 weeks ago)
Author:
hazelchat
Message:

Hazelchat 1.1.0

Location:
hazelchat
Files:
8 edited
1 copied

Legend:

Unmodified
Added
Removed
  • hazelchat/tags/1.1.0/assets/settings.css

    r3749053 r3751625  
    1616.hazelchat-settings h1 { font-size: 32px; font-weight: 700; letter-spacing: -.045em; }
    1717.hazelchat-settings .hazelchat-panel { background: #fffdf8; border: 1px solid #e3dccf; border-radius: 24px; padding: 12px 24px; }
     18.hazelchat-settings .hazelchat-panel + .hazelchat-panel { margin-top: 16px; }
     19.hazelchat-settings .hazelchat-notice { background: #e3f1d6; color: #2d5a17; border-radius: 12px; padding: 8px 12px; }
    1820.hazelchat-settings .hazelchat-start { margin-bottom: 24px; }
    1921.hazelchat-settings .hazelchat-start h2 { margin: 12px 0 0; font-size: 20px; }
  • hazelchat/tags/1.1.0/hazelchat.php

    r3749053 r3751625  
    33 * Plugin Name: Hazelchat
    44 * Description: Add your Hazelchat website agent to WordPress. Answer from reviewed sources and offer visitors a next step.
    5  * Version: 1.0.1
     5 * Version: 1.1.0
    66 * Requires at least: 6.3
    77 * Requires PHP: 7.4
    … …  
    2323        const SCRIPT_URL = 'https://app.hazelchat.co/widget.js';
    2424        const APP_URL = 'https://app.hazelchat.co';
    25         const VERSION = '1.0.1';
     25        const VERSION = '1.1.0';
    2626        // Room for a pasted installation code; the key itself is 64 characters.
    2727        const MAX_INPUT = 1000;
     28        // Orders after a chat (1.1.0): off until the owner types a code from
     29        // Hazelchat. The connection and its signing secret live in their own
     30        // option, never autoloaded and never part of the settings form.
     31        const ORDERS_OPTION = 'hazelchat_order_tracking';
     32        const CONNECT_URL = 'https://app.hazelchat.co/api/integrations/woocommerce/connect';
     33        const REPORT_URL = 'https://app.hazelchat.co/api/integrations/woocommerce/orders';
     34        const REPORT_HOOK = 'hazelchat_send_order_report';
     35        const QUEUE_GROUP = 'hazelchat';
     36        // The conversation reference Hazelchat puts on a chat's Add to cart.
     37        const REF_PATTERN = '/\A[a-z2-7]{12}\z/';
     38        // Where WooCommerce's Store API and cart page are on this site, as the
     39        // widget accepts them (public/widget.js checks the same shapes).
     40        const STORE_API_PATTERN = '#\A(?:/[A-Za-z0-9._~-]+)*/(?:(?:index\.php/)?wp-json/wc/store/v1/|(?:index\.php)?\?rest_route=/wc/store/v1/)\z#';
     41        const CART_PATTERN = '#\A/(?:(?:[A-Za-z0-9._~-]|%[0-9A-Fa-f]{2})+/?)*(?:\?page_id=\d{1,10})?\z#';
    2842
    2943        public static function boot() {
    … …  
    3448                add_filter( 'script_loader_tag', array( __CLASS__, 'widget_tag' ), 10, 3 );
    3549                add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( __CLASS__, 'action_links' ) );
     50                // Orders after a chat: the connection code, references on cart and
     51                // order lines, and reports, all only while the owner has connected.
     52                add_action( 'admin_post_hazelchat_orders_connect', array( __CLASS__, 'connect_orders' ) );
     53                add_action( 'admin_post_hazelchat_orders_disconnect', array( __CLASS__, 'disconnect_orders' ) );
     54                add_action( 'before_woocommerce_init', array( __CLASS__, 'declare_woocommerce_features' ) );
     55                add_filter( 'woocommerce_store_api_add_to_cart_data', array( __CLASS__, 'store_api_ref' ), 10, 2 );
     56                add_filter( 'woocommerce_add_cart_item_data', array( __CLASS__, 'url_ref' ), 10, 2 );
     57                add_action( 'woocommerce_checkout_create_order_line_item', array( __CLASS__, 'line_ref' ), 10, 3 );
     58                add_action( 'woocommerce_payment_complete', array( __CLASS__, 'order_paid' ) );
     59                add_action( 'woocommerce_order_status_processing', array( __CLASS__, 'order_paid' ) );
     60                add_action( 'woocommerce_order_status_completed', array( __CLASS__, 'order_paid' ) );
     61                add_action( 'woocommerce_order_status_cancelled', array( __CLASS__, 'order_changed' ) );
     62                add_action( 'woocommerce_order_status_refunded', array( __CLASS__, 'order_changed' ) );
     63                add_action( 'woocommerce_order_refunded', array( __CLASS__, 'order_changed' ) );
     64                add_action( self::REPORT_HOOK, array( __CLASS__, 'send_report' ) );
    3665        }
    3766
    … …  
    174203                                </form>
    175204                        </div>
     205                        <?php self::render_orders(); ?>
    176206                        <h2><?php esc_html_e( 'Finish installation in Hazelchat', 'hazelchat' ); ?></h2>
    177207                        <ol>
    … …  
    215245                $html->set_attribute( 'data-agent', $settings['public_key'] );
    216246                $html->set_attribute( 'defer', true );
     247                // On a WooCommerce shop the chat's Add to cart works on this page
     248                // through WooCommerce's own Store API: where it and the cart page are.
     249                $shop = self::shop_paths();
     250                if ( $shop ) {
     251                        $html->set_attribute( 'data-platform', 'woocommerce' );
     252                        $html->set_attribute( 'data-store-api', $shop['store_api'] );
     253                        $html->set_attribute( 'data-cart', $shop['cart'] );
     254                } else {
     255                        $html->remove_attribute( 'data-platform' );
     256                        $html->remove_attribute( 'data-store-api' );
     257                        $html->remove_attribute( 'data-cart' );
     258                }
    217259                if ( $settings['require_consent'] ) {
    218260                        $html->set_attribute( 'data-require-consent', 'true' );
    … …  
    222264                return $html->get_updated_html();
    223265        }
     266
     267        // ---------------------------------------------------------------------
     268        // WooCommerce: Add to cart from the chat and orders after a chat (1.1.0)
     269        // ---------------------------------------------------------------------
     270
     271        public static function woocommerce_active() {
     272                return class_exists( 'WooCommerce' ) && function_exists( 'wc_get_cart_url' ) && function_exists( 'wc_get_order' );
     273        }
     274
     275        // A URL's path and query on this site, or '' when it fails the shape.
     276        private static function path_of( $url, $pattern ) {
     277                $parts = wp_parse_url( $url );
     278                if ( ! is_array( $parts ) ) {
     279                        return '';
     280                }
     281                $path = ( isset( $parts['path'] ) ? $parts['path'] : '/' ) . ( isset( $parts['query'] ) ? '?' . $parts['query'] : '' );
     282                return 1 === preg_match( $pattern, $path ) && false === strpos( $path, '/../' ) && false === strpos( $path, '/./' ) ? $path : '';
     283        }
     284
     285        public static function shop_paths() {
     286                if ( ! self::woocommerce_active() ) {
     287                        return null;
     288                }
     289                $store_api = self::path_of( rest_url( 'wc/store/v1/' ), self::STORE_API_PATTERN );
     290                $cart      = self::path_of( wc_get_cart_url(), self::CART_PATTERN );
     291                return '' === $store_api || '' === $cart ? null : array( 'store_api' => $store_api, 'cart' => $cart );
     292        }
     293
     294        public static function declare_woocommerce_features() {
     295                if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
     296                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
     297                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
     298                }
     299        }
     300
     301        // The stored connection, or null.
     302        public static function orders_connection() {
     303                $saved = get_option( self::ORDERS_OPTION, array() );
     304                if ( ! is_array( $saved ) || ! isset( $saved['connection'], $saved['secret'] )
     305                        || ! is_string( $saved['connection'] ) || 1 !== preg_match( '/\A[a-f0-9]{64}\z/', $saved['connection'] )
     306                        || ! is_string( $saved['secret'] ) || 1 !== preg_match( '/\A[a-f0-9]{64}\z/', $saved['secret'] ) ) {
     307                        return null;
     308                }
     309                return array(
     310                        'connection'   => $saved['connection'],
     311                        'secret'       => $saved['secret'],
     312                        'connected_at' => isset( $saved['connected_at'] ) ? absint( $saved['connected_at'] ) : 0,
     313                );
     314        }
     315
     316        // Orders are tracked only while WooCommerce is active, the widget loads
     317        // (turning loading off stops reports too) and the owner has connected.
     318        public static function tracking() {
     319                return self::woocommerce_active() && self::can_load( self::settings() ) && null !== self::orders_connection();
     320        }
     321
     322        private static function ref_value( $value ) {
     323                return is_string( $value ) && 1 === preg_match( self::REF_PATTERN, $value ) ? $value : '';
     324        }
     325
     326        // The chat's Add to cart through the Store API carries `hazelchat_ref`.
     327        public static function store_api_ref( $data, $request ) {
     328                if ( ! is_array( $data ) || ! is_object( $request ) || ! method_exists( $request, 'get_param' ) || ! self::tracking() ) {
     329                        return $data;
     330                }
     331                $ref = self::ref_value( $request->get_param( 'hazelchat_ref' ) );
     332                if ( '' !== $ref ) {
     333                        $data['cart_item_data']                  = isset( $data['cart_item_data'] ) && is_array( $data['cart_item_data'] ) ? $data['cart_item_data'] : array();
     334                        $data['cart_item_data']['hazelchat_ref'] = $ref;
     335                }
     336                return $data;
     337        }
     338
     339        // The same reference on WooCommerce's own ?add-to-cart= address, which the
     340        // chat opens where it cannot add on the page.
     341        public static function url_ref( $cart_item_data, $product_id = 0 ) {
     342                // phpcs:disable WordPress.Security.NonceVerification.Recommended -- WooCommerce's own add-to-cart address carries no nonce; the value is pattern-checked and only labels the cart line.
     343                if ( ! is_array( $cart_item_data ) || isset( $cart_item_data['hazelchat_ref'] ) || ! isset( $_GET['add-to-cart'], $_GET['hazelchat_ref'] ) || ! self::tracking() ) {
     344                        return $cart_item_data;
     345                }
     346                $ref = self::ref_value( sanitize_text_field( wp_unslash( $_GET['hazelchat_ref'] ) ) );
     347                // phpcs:enable WordPress.Security.NonceVerification.Recommended
     348                if ( '' !== $ref ) {
     349                        $cart_item_data['hazelchat_ref'] = $ref;
     350                }
     351                return $cart_item_data;
     352        }
     353
     354        // At checkout (classic and block) the reference moves to the order line,
     355        // hidden in the admin by its underscore.
     356        public static function line_ref( $item, $cart_item_key, $values ) {
     357                if ( ! is_object( $item ) || ! method_exists( $item, 'add_meta_data' ) || ! is_array( $values ) || ! isset( $values['hazelchat_ref'] ) ) {
     358                        return;
     359                }
     360                $ref = self::ref_value( $values['hazelchat_ref'] );
     361                if ( '' !== $ref ) {
     362                        $item->add_meta_data( '_hazelchat_ref', $ref, true );
     363                }
     364        }
     365
     366        // The lines added from the chat: the only lines a report names.
     367        public static function chat_lines( $order ) {
     368                $lines = array();
     369                foreach ( $order->get_items( 'line_item' ) as $item ) {
     370                        $ref = self::ref_value( $item->get_meta( '_hazelchat_ref', true ) );
     371                        if ( '' === $ref ) {
     372                                continue;
     373                        }
     374                        $lines[] = array(
     375                                'product'   => (int) $item->get_product_id(),
     376                                'variation' => (int) $item->get_variation_id(),
     377                                'quantity'  => (int) $item->get_quantity(),
     378                                'total'     => self::amount( (float) $item->get_total() + (float) $item->get_total_tax() ),
     379                                'ref'       => $ref,
     380                        );
     381                        if ( 100 === count( $lines ) ) {
     382                                break;
     383                        }
     384                }
     385                return $lines;
     386        }
     387
     388        private static function amount( $value ) {
     389                return number_format( max( 0, (float) $value ), wc_get_price_decimals(), '.', '' );
     390        }
     391
     392        private static function tracked_order( $order_id ) {
     393                if ( ! self::tracking() ) {
     394                        return null;
     395                }
     396                $order = wc_get_order( absint( $order_id ) );
     397                return $order && is_a( $order, 'WC_Order' ) && self::chat_lines( $order ) ? $order : null;
     398        }
     399
     400        // Payment, or a payment method that sets processing or completed itself:
     401        // queued once per order. An order without a chat line causes nothing.
     402        public static function order_paid( $order_id ) {
     403                $order = self::tracked_order( $order_id );
     404                if ( ! $order || $order->get_meta( '_hazelchat_reported', true ) ) {
     405                        return;
     406                }
     407                $order->update_meta_data( '_hazelchat_reported', (string) time() );
     408                $order->save_meta_data();
     409                self::queue( $order );
     410        }
     411
     412        // Cancellation and refunds, only for an order already reported as paid.
     413        public static function order_changed( $order_id ) {
     414                $order = self::tracked_order( $order_id );
     415                if ( $order && $order->get_meta( '_hazelchat_reported', true ) ) {
     416                        self::queue( $order );
     417                }
     418        }
     419
     420        // Action Scheduler sends it in the background, so checkout never waits.
     421        private static function queue( $order ) {
     422                if ( ! function_exists( 'as_enqueue_async_action' ) ) {
     423                        return;
     424                }
     425                if ( ! $order->get_meta( '_hazelchat_report_since', true ) ) {
     426                        $order->update_meta_data( '_hazelchat_report_since', (string) time() );
     427                        $order->update_meta_data( '_hazelchat_report_attempt', '0' );
     428                        $order->save_meta_data();
     429                }
     430                as_enqueue_async_action( self::REPORT_HOOK, array( (int) $order->get_id() ), self::QUEUE_GROUP, true );
     431        }
     432
     433        private static function report_status( $order ) {
     434                $status   = $order->get_status();
     435                $refunded = (float) $order->get_total_refunded();
     436                if ( 'cancelled' === $status ) {
     437                        return 'cancelled';
     438                }
     439                if ( 'refunded' === $status || ( $refunded > 0 && $refunded >= (float) $order->get_total() ) ) {
     440                        return 'refunded';
     441                }
     442                if ( $refunded > 0 ) {
     443                        return 'partly-refunded';
     444                }
     445                return in_array( $status, array( 'processing', 'completed' ), true ) ? 'paid' : '';
     446        }
     447
     448        // The report: the order's current state, built when it is sent. Only
     449        // these fields; never a name, address, email, phone, payment, shipping,
     450        // coupon, note or any line not added from the chat.
     451        public static function report_body( $order ) {
     452                $lines  = self::chat_lines( $order );
     453                $status = self::report_status( $order );
     454                if ( ! $lines || '' === $status ) {
     455                        return '';
     456                }
     457                $number = (string) $order->get_order_number();
     458                return wp_json_encode(
     459                        array(
     460                                'order' => array(
     461                                        'id'       => (int) $order->get_id(),
     462                                        'number'   => 1 === preg_match( '/\A#?[A-Za-z0-9-]{1,32}\z/', $number ) ? $number : (string) $order->get_id(),
     463                                        'status'   => $status,
     464                                        'total'    => self::amount( (float) $order->get_total() - (float) $order->get_total_refunded() ),
     465                                        'currency' => $order->get_currency(),
     466                                        'lines'    => $lines,
     467                                ),
     468                        )
     469                );
     470        }
     471
     472        // Signed with the connection's secret: HMAC-SHA256 of "<time>.<body>".
     473        public static function send_report( $order_id ) {
     474                $connection = self::orders_connection();
     475                if ( ! self::tracking() || ! $connection ) {
     476                        return;
     477                }
     478                $order = wc_get_order( absint( $order_id ) );
     479                $body  = $order && is_a( $order, 'WC_Order' ) ? self::report_body( $order ) : '';
     480                if ( '' === $body ) {
     481                        return;
     482                }
     483                $time     = time();
     484                $response = wp_remote_post(
     485                        self::REPORT_URL,
     486                        array(
     487                                'timeout'     => 10,
     488                                'redirection' => 0,
     489                                'headers'     => array(
     490                                        'Content-Type'           => 'application/json',
     491                                        'X-Hazelchat-Connection' => $connection['connection'],
     492                                        'X-Hazelchat-Signature'  => 't=' . $time . ',v1=' . hash_hmac( 'sha256', $time . '.' . $body, $connection['secret'] ),
     493                                ),
     494                                'body'        => $body,
     495                                'data_format' => 'body',
     496                        )
     497                );
     498                $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
     499                if ( ( $code >= 200 && $code < 300 ) || ( $code >= 400 && $code < 500 && 429 !== $code ) ) {
     500                        // Delivered, or refused for good: nothing is retried.
     501                        $order->delete_meta_data( '_hazelchat_report_since' );
     502                        $order->delete_meta_data( '_hazelchat_report_attempt' );
     503                        $order->save_meta_data();
     504                        return;
     505                }
     506                // Not reached, busy or failing: retried with back-off, dropped after 24 hours.
     507                $since   = absint( $order->get_meta( '_hazelchat_report_since', true ) );
     508                $attempt = absint( $order->get_meta( '_hazelchat_report_attempt', true ) ) + 1;
     509                $since   = $since ? $since : $time;
     510                $delays  = array( 60, 300, 900, 3600, 14400 );
     511                $delay   = isset( $delays[ $attempt - 1 ] ) ? $delays[ $attempt - 1 ] : 21600;
     512                if ( $time + $delay - $since > DAY_IN_SECONDS || ! function_exists( 'as_schedule_single_action' ) ) {
     513                        $order->delete_meta_data( '_hazelchat_report_since' );
     514                        $order->delete_meta_data( '_hazelchat_report_attempt' );
     515                        $order->save_meta_data();
     516                        return;
     517                }
     518                $order->update_meta_data( '_hazelchat_report_since', (string) $since );
     519                $order->update_meta_data( '_hazelchat_report_attempt', (string) $attempt );
     520                $order->save_meta_data();
     521                as_schedule_single_action( $time + $delay, self::REPORT_HOOK, array( (int) $order->get_id() ), self::QUEUE_GROUP );
     522        }
     523
     524        // The code Hazelchat shows: ten Crockford base32 characters, typed
     525        // forgivingly (lower case, spaces, hyphens, O for 0, I or L for 1).
     526        public static function normalise_code( $value ) {
     527                if ( ! is_string( $value ) || strlen( $value ) > 40 ) {
     528                        return '';
     529                }
     530                $code = strtr( preg_replace( '/[\s-]/', '', strtoupper( $value ) ), array( 'O' => '0', 'I' => '1', 'L' => '1' ) );
     531                return 1 === preg_match( '/\A[0-9A-HJKMNP-TV-Z]{10}\z/', $code ) ? $code : '';
     532        }
     533
     534        public static function site_origin() {
     535                $parts = wp_parse_url( home_url( '/' ) );
     536                return $parts['scheme'] . '://' . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' );
     537        }
     538
     539        private static function back( $outcome ) {
     540                wp_safe_redirect( add_query_arg( 'hazelchat-orders', $outcome, admin_url( 'options-general.php?page=hazelchat' ) ) );
     541                exit;
     542        }
     543
     544        // The owner typed the code: exchanged once for this site's signing secret.
     545        public static function connect_orders() {
     546                if ( ! current_user_can( 'manage_options' ) ) {
     547                        wp_die( esc_html__( 'You do not have permission to manage Hazelchat settings.', 'hazelchat' ) );
     548                }
     549                check_admin_referer( 'hazelchat_orders_connect' );
     550                $code = isset( $_POST['hazelchat_order_code'] ) ? self::normalise_code( sanitize_text_field( wp_unslash( $_POST['hazelchat_order_code'] ) ) ) : '';
     551                if ( '' === $code || ! self::woocommerce_active() ) {
     552                        self::back( 'invalid' );
     553                }
     554                $response = wp_remote_post(
     555                        self::CONNECT_URL,
     556                        array(
     557                                'timeout'     => 15,
     558                                'redirection' => 0,
     559                                'headers'     => array( 'Content-Type' => 'application/json' ),
     560                                'body'        => wp_json_encode( array( 'code' => $code, 'site' => self::site_origin() ) ),
     561                                'data_format' => 'body',
     562                        )
     563                );
     564                $status = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
     565                $data   = is_wp_error( $response ) ? null : json_decode( wp_remote_retrieve_body( $response ), true );
     566                if ( 200 === $status && is_array( $data ) && isset( $data['connection'], $data['secret'] )
     567                        && is_string( $data['connection'] ) && 1 === preg_match( '/\A[a-f0-9]{64}\z/', $data['connection'] )
     568                        && is_string( $data['secret'] ) && 1 === preg_match( '/\A[a-f0-9]{64}\z/', $data['secret'] ) ) {
     569                        delete_option( self::ORDERS_OPTION );
     570                        add_option( self::ORDERS_OPTION, array( 'connection' => $data['connection'], 'secret' => $data['secret'], 'connected_at' => time() ), '', false );
     571                        self::back( 'connected' );
     572                }
     573                self::back( 403 === $status ? 'website' : ( 0 === $status || $status >= 500 ? 'unreachable' : 'invalid' ) );
     574        }
     575
     576        public static function disconnect_orders() {
     577                if ( ! current_user_can( 'manage_options' ) ) {
     578                        wp_die( esc_html__( 'You do not have permission to manage Hazelchat settings.', 'hazelchat' ) );
     579                }
     580                check_admin_referer( 'hazelchat_orders_disconnect' );
     581                delete_option( self::ORDERS_OPTION );
     582                self::back( 'disconnected' );
     583        }
     584
     585        public static function render_orders() {
     586                if ( ! self::woocommerce_active() ) {
     587                        return;
     588                }
     589                $connection = self::orders_connection();
     590                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only selects which result message to show after the protected admin-post redirect.
     591                $outcome  = isset( $_GET['hazelchat-orders'] ) ? sanitize_key( wp_unslash( $_GET['hazelchat-orders'] ) ) : '';
     592                $messages = array(
     593                        'connected'    => __( 'Order tracking is connected.', 'hazelchat' ),
     594                        'disconnected' => __( 'Order tracking is disconnected. This site no longer sends order reports.', 'hazelchat' ),
     595                        'invalid'      => __( 'That code did not work. In Hazelchat, show a new code and type it within 30 minutes.', 'hazelchat' ),
     596                        'website'      => __( 'That code was made for another website. Use it on the website you verified in Hazelchat.', 'hazelchat' ),
     597                        'unreachable'  => __( 'Hazelchat could not be reached. Try again in a few minutes.', 'hazelchat' ),
     598                );
     599                ?>
     600                <div class="hazelchat-panel" id="hazelchat-orders">
     601                        <h2><?php esc_html_e( 'Orders after a chat', 'hazelchat' ); ?></h2>
     602                        <?php if ( isset( $messages[ $outcome ] ) ) : ?>
     603                                <p class="hazelchat-notice" role="status"><?php echo esc_html( $messages[ $outcome ] ); ?></p>
     604                        <?php endif; ?>
     605                        <p class="description"><?php esc_html_e( 'Optional, and off until you type a code from Hazelchat (Products > Orders after a chat). When connected, this site tells Hazelchat (app.hazelchat.co) when an order that includes something a visitor added to the cart from the chat is paid, cancelled or refunded: the order number and id, the total after refunds, the currency, the status, and the products, quantities and amounts added from the chat. Never the customer\'s name, email, address, payment or shipping details, and nothing about other orders. Turning widget loading off also stops these reports.', 'hazelchat' ); ?></p>
     606                        <?php if ( $connection ) : ?>
     607                                <p><strong><?php esc_html_e( 'Connected to Hazelchat.', 'hazelchat' ); ?></strong>
     608                                        <?php
     609                                        /* translators: %s: date the connection was made */
     610                                        echo esc_html( sprintf( __( 'Since %s.', 'hazelchat' ), wp_date( get_option( 'date_format' ), $connection['connected_at'] ) ) );
     611                                        ?>
     612                                </p>
     613                                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
     614                                        <input type="hidden" name="action" value="hazelchat_orders_disconnect">
     615                                        <?php wp_nonce_field( 'hazelchat_orders_disconnect' ); ?>
     616                                        <?php submit_button( __( 'Disconnect', 'hazelchat' ), 'secondary', 'submit', false ); ?>
     617                                </form>
     618                        <?php else : ?>
     619                                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
     620                                        <input type="hidden" name="action" value="hazelchat_orders_connect">
     621                                        <?php wp_nonce_field( 'hazelchat_orders_connect' ); ?>
     622                                        <p><label for="hazelchat-order-code"><?php esc_html_e( 'Order tracking code', 'hazelchat' ); ?></label><br>
     623                                                <input id="hazelchat-order-code" name="hazelchat_order_code" type="text" class="regular-text code" maxlength="40" autocomplete="off" spellcheck="false" placeholder="XXXXX-XXXXX"></p>
     624                                        <p><a href="https://hazelchat.co/privacy/" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Privacy notice', 'hazelchat' ); ?></a> · <a href="https://hazelchat.co/terms/" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Terms', 'hazelchat' ); ?></a></p>
     625                                        <?php submit_button( __( 'Connect', 'hazelchat' ), 'primary', 'submit', false ); ?>
     626                                </form>
     627                        <?php endif; ?>
     628                </div>
     629                <?php
     630        }
    224631}
    225632
  • hazelchat/tags/1.1.0/readme.txt

    r3749053 r3751625  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.0.1
     7Stable tag: 1.1.0
    88License: GPL-2.0-or-later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    3131* An optional connection gate for your visitor consent manager.
    3232* A link back to Hazelchat to check installation and test your published agent.
     33* On a WooCommerce shop: the chat's product cards can add to the visitor's cart on the page, through WooCommerce's own Store API.
     34* Optional order tracking for WooCommerce, off until you connect it: see which paid orders include something a visitor added to the cart from the chat.
    3335
    34 Activation alone does not load the hosted service. Links from the plugin and this page to Hazelchat carry campaign tags (utm_source=wordpress) so Hazelchat can count signups that start here; nothing is sent until you click one. No account password, administrative token or AI provider key belongs in WordPress settings. The public widget key grants no administrative access.
     36Activation alone does not load the hosted service, and order tracking stays off until you type a code from Hazelchat. Links from the plugin and this page to Hazelchat carry campaign tags (utm_source=wordpress) so Hazelchat can count signups that start here; nothing is sent until you click one. No account password, administrative token or AI provider key belongs in WordPress settings. The public widget key grants no administrative access.
    3537
    3638Answers use your reviewed, published sources. Source-only mode shows retrieved excerpts; AI-evidence mode writes answers from retrieved evidence. This plugin does not implement an AI engine, guarantee correctness or guarantee sales.
    3739
    38 == External service ==
     40== External services ==
    3941
    4042This plugin connects to Hazelchat, a hosted service at https://app.hazelchat.co. A Hazelchat account is required; free and paid plans are available. Billing, content management and agent configuration take place on Hazelchat, not in WordPress. Pricing: https://hazelchat.co/pricing/
    4143
    42 After an administrator supplies a valid public widget key, accepts the service connection and enables loading, visitors' browsers download https://app.hazelchat.co/widget.js. The script displays a chat frame from the same service. Browser network requests expose ordinary connection information, such as the visitor's IP address, to the service. When visitors use the chat, their questions, conversation data and any submitted enquiry details (name, email and message) are sent to Hazelchat. Configured AI-evidence mode sends questions and retrieved source passages to its model provider; source-only mode does not use a model. Retention and data requests are managed in Hazelchat. The plugin itself does not read or send WordPress users, posts, orders or private pages, and performs no server-to-server service requests or activation telemetry.
     44After an administrator supplies a valid public widget key, accepts the service connection and enables loading, visitors' browsers download https://app.hazelchat.co/widget.js. The script displays a chat frame from the same service. Browser network requests expose ordinary connection information, such as the visitor's IP address, to the service. When visitors use the chat, their questions, conversation data and any submitted enquiry details (name, email and message) are sent to Hazelchat. Configured AI-evidence mode sends questions and retrieved source passages to its model provider; source-only mode does not use a model. Retention and data requests are managed in Hazelchat. The plugin itself does not read or send WordPress users, posts or private pages, and sends no activation telemetry.
     45
     46On a WooCommerce shop, the script tag also tells the chat where WooCommerce's Store API and cart page are on your site. When a visitor clicks Add to cart on a product card in the chat, their browser adds the product to their cart on your site through WooCommerce's own Store API; nothing of the cart is sent to Hazelchat. Hazelchat reads your published products from the same public Store API, as any visitor's browser could.
     47
     48Order tracking (optional, off by default). Only after you switch it on in Hazelchat and type the code it shows into Settings > Hazelchat does this site make server-to-server requests to Hazelchat:
     49
     50* When you save the code: one request to https://app.hazelchat.co/api/integrations/woocommerce/connect with the code and your site's address. Hazelchat answers with a signing secret, which is stored in this site's database (not autoloaded) and removed on Disconnect or when you delete the plugin.
     51* When an order that includes something a visitor added to the cart from the chat is paid, cancelled or refunded: one signed request to https://app.hazelchat.co/api/integrations/woocommerce/orders, sent in the background by WooCommerce's Action Scheduler. It contains the order's id and number, its status, its total after refunds, its currency, and for each line added from the chat the product and variation id, the quantity, the line total and the random chat reference. It never contains the customer's name, email, phone, addresses, payment or shipping method, coupons, notes or any other line. Orders without a line added from the chat cause no request at all.
     52
     53The chat reference is a random code that Hazelchat adds to the chat's Add to cart; WooCommerce keeps it with that cart line and the order line (hidden in the order screen). Reports stop when you disconnect, turn widget loading off, deactivate or delete the plugin.
    4354
    4455The optional visitor-consent setting still allows the small launcher script to download; it prevents creation of the chat frame, chat API requests and session-storage access until your consent manager dispatches hazelchat-consent with detail: true. A consent manager must be connected separately. To block all external downloads before consent, configure your consent manager to block the launcher script as well. Turning consent off removes the widget but does not erase records already held by Hazelchat.
    … …  
    6576= Does it work with page builders and WooCommerce? =
    6677
    67 It adds a footer script using WordPress's normal script API. Themes must call wp_footer(). It does not import private WooCommerce data, retrieve orders or manage carts. Individual builder, commerce and optimization-plugin combinations require testing.
     78It adds a footer script using WordPress's normal script API. Themes must call wp_footer(). With WooCommerce, Hazelchat can show your published products in answers and add them to the visitor's cart through WooCommerce's Store API; connect your products in Hazelchat under Products. It never reads carts or customer data. Order tracking is optional and reports only orders that include something added from the chat (see External services). Individual builder, commerce and optimization-plugin combinations require testing.
     79
     80= What does order tracking show? =
     81
     82In Hazelchat, Analytics shows "Orders after a chat": orders that include something added to the cart from the chat, as your shop reported them, with their order number so you can check each one in WooCommerce. A click is not an order, and an order after a chat does not prove the chat caused it.
    6883
    6984= Why is my widget missing? =
    … …  
    94109== Changelog ==
    95110
     111= 1.1.0 =
     112* WooCommerce: Add to cart from the chat's product cards, on the page, through WooCommerce's Store API.
     113* Optional order tracking: after you type a code from Hazelchat, orders that include something added to the cart from the chat are reported to Hazelchat, signed and in the background. Off by default; see External services.
     114* Uninstall also removes the order tracking connection.
     115
    96116= 1.0.1 =
    97117* Settings: a "Create a free account" and "Log in" link while no key is saved.
  • hazelchat/tags/1.1.0/uninstall.php

    r3727193 r3751625  
    33if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    44        exit;
     5}
     6
     7// The settings and (1.1.0) the order tracking connection with its signing secret.
     8function hazelchat_uninstall_site() {
     9        delete_option( 'hazelchat_settings' );
     10        delete_option( 'hazelchat_order_tracking' );
     11        if ( function_exists( 'as_unschedule_all_actions' ) ) {
     12                as_unschedule_all_actions( 'hazelchat_send_order_report' );
     13        }
    514}
    615
    … …  
    1120                foreach ( $hazelchat_sites as $hazelchat_site_id ) {
    1221                        switch_to_blog( $hazelchat_site_id );
    13                         delete_option( 'hazelchat_settings' );
     22                        hazelchat_uninstall_site();
    1423                        restore_current_blog();
    1524                }
    … …  
    1726        } while ( 100 === count( $hazelchat_sites ) );
    1827} else {
    19         delete_option( 'hazelchat_settings' );
     28        hazelchat_uninstall_site();
    2029}
  • hazelchat/trunk/assets/settings.css

    r3749053 r3751625  
    1616.hazelchat-settings h1 { font-size: 32px; font-weight: 700; letter-spacing: -.045em; }
    1717.hazelchat-settings .hazelchat-panel { background: #fffdf8; border: 1px solid #e3dccf; border-radius: 24px; padding: 12px 24px; }
     18.hazelchat-settings .hazelchat-panel + .hazelchat-panel { margin-top: 16px; }
     19.hazelchat-settings .hazelchat-notice { background: #e3f1d6; color: #2d5a17; border-radius: 12px; padding: 8px 12px; }
    1820.hazelchat-settings .hazelchat-start { margin-bottom: 24px; }
    1921.hazelchat-settings .hazelchat-start h2 { margin: 12px 0 0; font-size: 20px; }
  • hazelchat/trunk/hazelchat.php

    r3749053 r3751625  
    33 * Plugin Name: Hazelchat
    44 * Description: Add your Hazelchat website agent to WordPress. Answer from reviewed sources and offer visitors a next step.
    5  * Version: 1.0.1
     5 * Version: 1.1.0
    66 * Requires at least: 6.3
    77 * Requires PHP: 7.4
    … …  
    2323        const SCRIPT_URL = 'https://app.hazelchat.co/widget.js';
    2424        const APP_URL = 'https://app.hazelchat.co';
    25         const VERSION = '1.0.1';
     25        const VERSION = '1.1.0';
    2626        // Room for a pasted installation code; the key itself is 64 characters.
    2727        const MAX_INPUT = 1000;
     28        // Orders after a chat (1.1.0): off until the owner types a code from
     29        // Hazelchat. The connection and its signing secret live in their own
     30        // option, never autoloaded and never part of the settings form.
     31        const ORDERS_OPTION = 'hazelchat_order_tracking';
     32        const CONNECT_URL = 'https://app.hazelchat.co/api/integrations/woocommerce/connect';
     33        const REPORT_URL = 'https://app.hazelchat.co/api/integrations/woocommerce/orders';
     34        const REPORT_HOOK = 'hazelchat_send_order_report';
     35        const QUEUE_GROUP = 'hazelchat';
     36        // The conversation reference Hazelchat puts on a chat's Add to cart.
     37        const REF_PATTERN = '/\A[a-z2-7]{12}\z/';
     38        // Where WooCommerce's Store API and cart page are on this site, as the
     39        // widget accepts them (public/widget.js checks the same shapes).
     40        const STORE_API_PATTERN = '#\A(?:/[A-Za-z0-9._~-]+)*/(?:(?:index\.php/)?wp-json/wc/store/v1/|(?:index\.php)?\?rest_route=/wc/store/v1/)\z#';
     41        const CART_PATTERN = '#\A/(?:(?:[A-Za-z0-9._~-]|%[0-9A-Fa-f]{2})+/?)*(?:\?page_id=\d{1,10})?\z#';
    2842
    2943        public static function boot() {
    … …  
    3448                add_filter( 'script_loader_tag', array( __CLASS__, 'widget_tag' ), 10, 3 );
    3549                add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( __CLASS__, 'action_links' ) );
     50                // Orders after a chat: the connection code, references on cart and
     51                // order lines, and reports, all only while the owner has connected.
     52                add_action( 'admin_post_hazelchat_orders_connect', array( __CLASS__, 'connect_orders' ) );
     53                add_action( 'admin_post_hazelchat_orders_disconnect', array( __CLASS__, 'disconnect_orders' ) );
     54                add_action( 'before_woocommerce_init', array( __CLASS__, 'declare_woocommerce_features' ) );
     55                add_filter( 'woocommerce_store_api_add_to_cart_data', array( __CLASS__, 'store_api_ref' ), 10, 2 );
     56                add_filter( 'woocommerce_add_cart_item_data', array( __CLASS__, 'url_ref' ), 10, 2 );
     57                add_action( 'woocommerce_checkout_create_order_line_item', array( __CLASS__, 'line_ref' ), 10, 3 );
     58                add_action( 'woocommerce_payment_complete', array( __CLASS__, 'order_paid' ) );
     59                add_action( 'woocommerce_order_status_processing', array( __CLASS__, 'order_paid' ) );
     60                add_action( 'woocommerce_order_status_completed', array( __CLASS__, 'order_paid' ) );
     61                add_action( 'woocommerce_order_status_cancelled', array( __CLASS__, 'order_changed' ) );
     62                add_action( 'woocommerce_order_status_refunded', array( __CLASS__, 'order_changed' ) );
     63                add_action( 'woocommerce_order_refunded', array( __CLASS__, 'order_changed' ) );
     64                add_action( self::REPORT_HOOK, array( __CLASS__, 'send_report' ) );
    3665        }
    3766
    … …  
    174203                                </form>
    175204                        </div>
     205                        <?php self::render_orders(); ?>
    176206                        <h2><?php esc_html_e( 'Finish installation in Hazelchat', 'hazelchat' ); ?></h2>
    177207                        <ol>
    … …  
    215245                $html->set_attribute( 'data-agent', $settings['public_key'] );
    216246                $html->set_attribute( 'defer', true );
     247                // On a WooCommerce shop the chat's Add to cart works on this page
     248                // through WooCommerce's own Store API: where it and the cart page are.
     249                $shop = self::shop_paths();
     250                if ( $shop ) {
     251                        $html->set_attribute( 'data-platform', 'woocommerce' );
     252                        $html->set_attribute( 'data-store-api', $shop['store_api'] );
     253                        $html->set_attribute( 'data-cart', $shop['cart'] );
     254                } else {
     255                        $html->remove_attribute( 'data-platform' );
     256                        $html->remove_attribute( 'data-store-api' );
     257                        $html->remove_attribute( 'data-cart' );
     258                }
    217259                if ( $settings['require_consent'] ) {
    218260                        $html->set_attribute( 'data-require-consent', 'true' );
    … …  
    222264                return $html->get_updated_html();
    223265        }
     266
     267        // ---------------------------------------------------------------------
     268        // WooCommerce: Add to cart from the chat and orders after a chat (1.1.0)
     269        // ---------------------------------------------------------------------
     270
     271        public static function woocommerce_active() {
     272                return class_exists( 'WooCommerce' ) && function_exists( 'wc_get_cart_url' ) && function_exists( 'wc_get_order' );
     273        }
     274
     275        // A URL's path and query on this site, or '' when it fails the shape.
     276        private static function path_of( $url, $pattern ) {
     277                $parts = wp_parse_url( $url );
     278                if ( ! is_array( $parts ) ) {
     279                        return '';
     280                }
     281                $path = ( isset( $parts['path'] ) ? $parts['path'] : '/' ) . ( isset( $parts['query'] ) ? '?' . $parts['query'] : '' );
     282                return 1 === preg_match( $pattern, $path ) && false === strpos( $path, '/../' ) && false === strpos( $path, '/./' ) ? $path : '';
     283        }
     284
     285        public static function shop_paths() {
     286                if ( ! self::woocommerce_active() ) {
     287                        return null;
     288                }
     289                $store_api = self::path_of( rest_url( 'wc/store/v1/' ), self::STORE_API_PATTERN );
     290                $cart      = self::path_of( wc_get_cart_url(), self::CART_PATTERN );
     291                return '' === $store_api || '' === $cart ? null : array( 'store_api' => $store_api, 'cart' => $cart );
     292        }
     293
     294        public static function declare_woocommerce_features() {
     295                if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
     296                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
     297                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
     298                }
     299        }
     300
     301        // The stored connection, or null.
     302        public static function orders_connection() {
     303                $saved = get_option( self::ORDERS_OPTION, array() );
     304                if ( ! is_array( $saved ) || ! isset( $saved['connection'], $saved['secret'] )
     305                        || ! is_string( $saved['connection'] ) || 1 !== preg_match( '/\A[a-f0-9]{64}\z/', $saved['connection'] )
     306                        || ! is_string( $saved['secret'] ) || 1 !== preg_match( '/\A[a-f0-9]{64}\z/', $saved['secret'] ) ) {
     307                        return null;
     308                }
     309                return array(
     310                        'connection'   => $saved['connection'],
     311                        'secret'       => $saved['secret'],
     312                        'connected_at' => isset( $saved['connected_at'] ) ? absint( $saved['connected_at'] ) : 0,
     313                );
     314        }
     315
     316        // Orders are tracked only while WooCommerce is active, the widget loads
     317        // (turning loading off stops reports too) and the owner has connected.
     318        public static function tracking() {
     319                return self::woocommerce_active() && self::can_load( self::settings() ) && null !== self::orders_connection();
     320        }
     321
     322        private static function ref_value( $value ) {
     323                return is_string( $value ) && 1 === preg_match( self::REF_PATTERN, $value ) ? $value : '';
     324        }
     325
     326        // The chat's Add to cart through the Store API carries `hazelchat_ref`.
     327        public static function store_api_ref( $data, $request ) {
     328                if ( ! is_array( $data ) || ! is_object( $request ) || ! method_exists( $request, 'get_param' ) || ! self::tracking() ) {
     329                        return $data;
     330                }
     331                $ref = self::ref_value( $request->get_param( 'hazelchat_ref' ) );
     332                if ( '' !== $ref ) {
     333                        $data['cart_item_data']                  = isset( $data['cart_item_data'] ) && is_array( $data['cart_item_data'] ) ? $data['cart_item_data'] : array();
     334                        $data['cart_item_data']['hazelchat_ref'] = $ref;
     335                }
     336                return $data;
     337        }
     338
     339        // The same reference on WooCommerce's own ?add-to-cart= address, which the
     340        // chat opens where it cannot add on the page.
     341        public static function url_ref( $cart_item_data, $product_id = 0 ) {
     342                // phpcs:disable WordPress.Security.NonceVerification.Recommended -- WooCommerce's own add-to-cart address carries no nonce; the value is pattern-checked and only labels the cart line.
     343                if ( ! is_array( $cart_item_data ) || isset( $cart_item_data['hazelchat_ref'] ) || ! isset( $_GET['add-to-cart'], $_GET['hazelchat_ref'] ) || ! self::tracking() ) {
     344                        return $cart_item_data;
     345                }
     346                $ref = self::ref_value( sanitize_text_field( wp_unslash( $_GET['hazelchat_ref'] ) ) );
     347                // phpcs:enable WordPress.Security.NonceVerification.Recommended
     348                if ( '' !== $ref ) {
     349                        $cart_item_data['hazelchat_ref'] = $ref;
     350                }
     351                return $cart_item_data;
     352        }
     353
     354        // At checkout (classic and block) the reference moves to the order line,
     355        // hidden in the admin by its underscore.
     356        public static function line_ref( $item, $cart_item_key, $values ) {
     357                if ( ! is_object( $item ) || ! method_exists( $item, 'add_meta_data' ) || ! is_array( $values ) || ! isset( $values['hazelchat_ref'] ) ) {
     358                        return;
     359                }
     360                $ref = self::ref_value( $values['hazelchat_ref'] );
     361                if ( '' !== $ref ) {
     362                        $item->add_meta_data( '_hazelchat_ref', $ref, true );
     363                }
     364        }
     365
     366        // The lines added from the chat: the only lines a report names.
     367        public static function chat_lines( $order ) {
     368                $lines = array();
     369                foreach ( $order->get_items( 'line_item' ) as $item ) {
     370                        $ref = self::ref_value( $item->get_meta( '_hazelchat_ref', true ) );
     371                        if ( '' === $ref ) {
     372                                continue;
     373                        }
     374                        $lines[] = array(
     375                                'product'   => (int) $item->get_product_id(),
     376                                'variation' => (int) $item->get_variation_id(),
     377                                'quantity'  => (int) $item->get_quantity(),
     378                                'total'     => self::amount( (float) $item->get_total() + (float) $item->get_total_tax() ),
     379                                'ref'       => $ref,
     380                        );
     381                        if ( 100 === count( $lines ) ) {
     382                                break;
     383                        }
     384                }
     385                return $lines;
     386        }
     387
     388        private static function amount( $value ) {
     389                return number_format( max( 0, (float) $value ), wc_get_price_decimals(), '.', '' );
     390        }
     391
     392        private static function tracked_order( $order_id ) {
     393                if ( ! self::tracking() ) {
     394                        return null;
     395                }
     396                $order = wc_get_order( absint( $order_id ) );
     397                return $order && is_a( $order, 'WC_Order' ) && self::chat_lines( $order ) ? $order : null;
     398        }
     399
     400        // Payment, or a payment method that sets processing or completed itself:
     401        // queued once per order. An order without a chat line causes nothing.
     402        public static function order_paid( $order_id ) {
     403                $order = self::tracked_order( $order_id );
     404                if ( ! $order || $order->get_meta( '_hazelchat_reported', true ) ) {
     405                        return;
     406                }
     407                $order->update_meta_data( '_hazelchat_reported', (string) time() );
     408                $order->save_meta_data();
     409                self::queue( $order );
     410        }
     411
     412        // Cancellation and refunds, only for an order already reported as paid.
     413        public static function order_changed( $order_id ) {
     414                $order = self::tracked_order( $order_id );
     415                if ( $order && $order->get_meta( '_hazelchat_reported', true ) ) {
     416                        self::queue( $order );
     417                }
     418        }
     419
     420        // Action Scheduler sends it in the background, so checkout never waits.
     421        private static function queue( $order ) {
     422                if ( ! function_exists( 'as_enqueue_async_action' ) ) {
     423                        return;
     424                }
     425                if ( ! $order->get_meta( '_hazelchat_report_since', true ) ) {
     426                        $order->update_meta_data( '_hazelchat_report_since', (string) time() );
     427                        $order->update_meta_data( '_hazelchat_report_attempt', '0' );
     428                        $order->save_meta_data();
     429                }
     430                as_enqueue_async_action( self::REPORT_HOOK, array( (int) $order->get_id() ), self::QUEUE_GROUP, true );
     431        }
     432
     433        private static function report_status( $order ) {
     434                $status   = $order->get_status();
     435                $refunded = (float) $order->get_total_refunded();
     436                if ( 'cancelled' === $status ) {
     437                        return 'cancelled';
     438                }
     439                if ( 'refunded' === $status || ( $refunded > 0 && $refunded >= (float) $order->get_total() ) ) {
     440                        return 'refunded';
     441                }
     442                if ( $refunded > 0 ) {
     443                        return 'partly-refunded';
     444                }
     445                return in_array( $status, array( 'processing', 'completed' ), true ) ? 'paid' : '';
     446        }
     447
     448        // The report: the order's current state, built when it is sent. Only
     449        // these fields; never a name, address, email, phone, payment, shipping,
     450        // coupon, note or any line not added from the chat.
     451        public static function report_body( $order ) {
     452                $lines  = self::chat_lines( $order );
     453                $status = self::report_status( $order );
     454                if ( ! $lines || '' === $status ) {
     455                        return '';
     456                }
     457                $number = (string) $order->get_order_number();
     458                return wp_json_encode(
     459                        array(
     460                                'order' => array(
     461                                        'id'       => (int) $order->get_id(),
     462                                        'number'   => 1 === preg_match( '/\A#?[A-Za-z0-9-]{1,32}\z/', $number ) ? $number : (string) $order->get_id(),
     463                                        'status'   => $status,
     464                                        'total'    => self::amount( (float) $order->get_total() - (float) $order->get_total_refunded() ),
     465                                        'currency' => $order->get_currency(),
     466                                        'lines'    => $lines,
     467                                ),
     468                        )
     469                );
     470        }
     471
     472        // Signed with the connection's secret: HMAC-SHA256 of "<time>.<body>".
     473        public static function send_report( $order_id ) {
     474                $connection = self::orders_connection();
     475                if ( ! self::tracking() || ! $connection ) {
     476                        return;
     477                }
     478                $order = wc_get_order( absint( $order_id ) );
     479                $body  = $order && is_a( $order, 'WC_Order' ) ? self::report_body( $order ) : '';
     480                if ( '' === $body ) {
     481                        return;
     482                }
     483                $time     = time();
     484                $response = wp_remote_post(
     485                        self::REPORT_URL,
     486                        array(
     487                                'timeout'     => 10,
     488                                'redirection' => 0,
     489                                'headers'     => array(
     490                                        'Content-Type'           => 'application/json',
     491                                        'X-Hazelchat-Connection' => $connection['connection'],
     492                                        'X-Hazelchat-Signature'  => 't=' . $time . ',v1=' . hash_hmac( 'sha256', $time . '.' . $body, $connection['secret'] ),
     493                                ),
     494                                'body'        => $body,
     495                                'data_format' => 'body',
     496                        )
     497                );
     498                $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
     499                if ( ( $code >= 200 && $code < 300 ) || ( $code >= 400 && $code < 500 && 429 !== $code ) ) {
     500                        // Delivered, or refused for good: nothing is retried.
     501                        $order->delete_meta_data( '_hazelchat_report_since' );
     502                        $order->delete_meta_data( '_hazelchat_report_attempt' );
     503                        $order->save_meta_data();
     504                        return;
     505                }
     506                // Not reached, busy or failing: retried with back-off, dropped after 24 hours.
     507                $since   = absint( $order->get_meta( '_hazelchat_report_since', true ) );
     508                $attempt = absint( $order->get_meta( '_hazelchat_report_attempt', true ) ) + 1;
     509                $since   = $since ? $since : $time;
     510                $delays  = array( 60, 300, 900, 3600, 14400 );
     511                $delay   = isset( $delays[ $attempt - 1 ] ) ? $delays[ $attempt - 1 ] : 21600;
     512                if ( $time + $delay - $since > DAY_IN_SECONDS || ! function_exists( 'as_schedule_single_action' ) ) {
     513                        $order->delete_meta_data( '_hazelchat_report_since' );
     514                        $order->delete_meta_data( '_hazelchat_report_attempt' );
     515                        $order->save_meta_data();
     516                        return;
     517                }
     518                $order->update_meta_data( '_hazelchat_report_since', (string) $since );
     519                $order->update_meta_data( '_hazelchat_report_attempt', (string) $attempt );
     520                $order->save_meta_data();
     521                as_schedule_single_action( $time + $delay, self::REPORT_HOOK, array( (int) $order->get_id() ), self::QUEUE_GROUP );
     522        }
     523
     524        // The code Hazelchat shows: ten Crockford base32 characters, typed
     525        // forgivingly (lower case, spaces, hyphens, O for 0, I or L for 1).
     526        public static function normalise_code( $value ) {
     527                if ( ! is_string( $value ) || strlen( $value ) > 40 ) {
     528                        return '';
     529                }
     530                $code = strtr( preg_replace( '/[\s-]/', '', strtoupper( $value ) ), array( 'O' => '0', 'I' => '1', 'L' => '1' ) );
     531                return 1 === preg_match( '/\A[0-9A-HJKMNP-TV-Z]{10}\z/', $code ) ? $code : '';
     532        }
     533
     534        public static function site_origin() {
     535                $parts = wp_parse_url( home_url( '/' ) );
     536                return $parts['scheme'] . '://' . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' );
     537        }
     538
     539        private static function back( $outcome ) {
     540                wp_safe_redirect( add_query_arg( 'hazelchat-orders', $outcome, admin_url( 'options-general.php?page=hazelchat' ) ) );
     541                exit;
     542        }
     543
     544        // The owner typed the code: exchanged once for this site's signing secret.
     545        public static function connect_orders() {
     546                if ( ! current_user_can( 'manage_options' ) ) {
     547                        wp_die( esc_html__( 'You do not have permission to manage Hazelchat settings.', 'hazelchat' ) );
     548                }
     549                check_admin_referer( 'hazelchat_orders_connect' );
     550                $code = isset( $_POST['hazelchat_order_code'] ) ? self::normalise_code( sanitize_text_field( wp_unslash( $_POST['hazelchat_order_code'] ) ) ) : '';
     551                if ( '' === $code || ! self::woocommerce_active() ) {
     552                        self::back( 'invalid' );
     553                }
     554                $response = wp_remote_post(
     555                        self::CONNECT_URL,
     556                        array(
     557                                'timeout'     => 15,
     558                                'redirection' => 0,
     559                                'headers'     => array( 'Content-Type' => 'application/json' ),
     560                                'body'        => wp_json_encode( array( 'code' => $code, 'site' => self::site_origin() ) ),
     561                                'data_format' => 'body',
     562                        )
     563                );
     564                $status = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
     565                $data   = is_wp_error( $response ) ? null : json_decode( wp_remote_retrieve_body( $response ), true );
     566                if ( 200 === $status && is_array( $data ) && isset( $data['connection'], $data['secret'] )
     567                        && is_string( $data['connection'] ) && 1 === preg_match( '/\A[a-f0-9]{64}\z/', $data['connection'] )
     568                        && is_string( $data['secret'] ) && 1 === preg_match( '/\A[a-f0-9]{64}\z/', $data['secret'] ) ) {
     569                        delete_option( self::ORDERS_OPTION );
     570                        add_option( self::ORDERS_OPTION, array( 'connection' => $data['connection'], 'secret' => $data['secret'], 'connected_at' => time() ), '', false );
     571                        self::back( 'connected' );
     572                }
     573                self::back( 403 === $status ? 'website' : ( 0 === $status || $status >= 500 ? 'unreachable' : 'invalid' ) );
     574        }
     575
     576        public static function disconnect_orders() {
     577                if ( ! current_user_can( 'manage_options' ) ) {
     578                        wp_die( esc_html__( 'You do not have permission to manage Hazelchat settings.', 'hazelchat' ) );
     579                }
     580                check_admin_referer( 'hazelchat_orders_disconnect' );
     581                delete_option( self::ORDERS_OPTION );
     582                self::back( 'disconnected' );
     583        }
     584
     585        public static function render_orders() {
     586                if ( ! self::woocommerce_active() ) {
     587                        return;
     588                }
     589                $connection = self::orders_connection();
     590                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only selects which result message to show after the protected admin-post redirect.
     591                $outcome  = isset( $_GET['hazelchat-orders'] ) ? sanitize_key( wp_unslash( $_GET['hazelchat-orders'] ) ) : '';
     592                $messages = array(
     593                        'connected'    => __( 'Order tracking is connected.', 'hazelchat' ),
     594                        'disconnected' => __( 'Order tracking is disconnected. This site no longer sends order reports.', 'hazelchat' ),
     595                        'invalid'      => __( 'That code did not work. In Hazelchat, show a new code and type it within 30 minutes.', 'hazelchat' ),
     596                        'website'      => __( 'That code was made for another website. Use it on the website you verified in Hazelchat.', 'hazelchat' ),
     597                        'unreachable'  => __( 'Hazelchat could not be reached. Try again in a few minutes.', 'hazelchat' ),
     598                );
     599                ?>
     600                <div class="hazelchat-panel" id="hazelchat-orders">
     601                        <h2><?php esc_html_e( 'Orders after a chat', 'hazelchat' ); ?></h2>
     602                        <?php if ( isset( $messages[ $outcome ] ) ) : ?>
     603                                <p class="hazelchat-notice" role="status"><?php echo esc_html( $messages[ $outcome ] ); ?></p>
     604                        <?php endif; ?>
     605                        <p class="description"><?php esc_html_e( 'Optional, and off until you type a code from Hazelchat (Products > Orders after a chat). When connected, this site tells Hazelchat (app.hazelchat.co) when an order that includes something a visitor added to the cart from the chat is paid, cancelled or refunded: the order number and id, the total after refunds, the currency, the status, and the products, quantities and amounts added from the chat. Never the customer\'s name, email, address, payment or shipping details, and nothing about other orders. Turning widget loading off also stops these reports.', 'hazelchat' ); ?></p>
     606                        <?php if ( $connection ) : ?>
     607                                <p><strong><?php esc_html_e( 'Connected to Hazelchat.', 'hazelchat' ); ?></strong>
     608                                        <?php
     609                                        /* translators: %s: date the connection was made */
     610                                        echo esc_html( sprintf( __( 'Since %s.', 'hazelchat' ), wp_date( get_option( 'date_format' ), $connection['connected_at'] ) ) );
     611                                        ?>
     612                                </p>
     613                                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
     614                                        <input type="hidden" name="action" value="hazelchat_orders_disconnect">
     615                                        <?php wp_nonce_field( 'hazelchat_orders_disconnect' ); ?>
     616                                        <?php submit_button( __( 'Disconnect', 'hazelchat' ), 'secondary', 'submit', false ); ?>
     617                                </form>
     618                        <?php else : ?>
     619                                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
     620                                        <input type="hidden" name="action" value="hazelchat_orders_connect">
     621                                        <?php wp_nonce_field( 'hazelchat_orders_connect' ); ?>
     622                                        <p><label for="hazelchat-order-code"><?php esc_html_e( 'Order tracking code', 'hazelchat' ); ?></label><br>
     623                                                <input id="hazelchat-order-code" name="hazelchat_order_code" type="text" class="regular-text code" maxlength="40" autocomplete="off" spellcheck="false" placeholder="XXXXX-XXXXX"></p>
     624                                        <p><a href="https://hazelchat.co/privacy/" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Privacy notice', 'hazelchat' ); ?></a> · <a href="https://hazelchat.co/terms/" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Terms', 'hazelchat' ); ?></a></p>
     625                                        <?php submit_button( __( 'Connect', 'hazelchat' ), 'primary', 'submit', false ); ?>
     626                                </form>
     627                        <?php endif; ?>
     628                </div>
     629                <?php
     630        }
    224631}
    225632
  • hazelchat/trunk/readme.txt

    r3749053 r3751625  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.0.1
     7Stable tag: 1.1.0
    88License: GPL-2.0-or-later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    3131* An optional connection gate for your visitor consent manager.
    3232* A link back to Hazelchat to check installation and test your published agent.
     33* On a WooCommerce shop: the chat's product cards can add to the visitor's cart on the page, through WooCommerce's own Store API.
     34* Optional order tracking for WooCommerce, off until you connect it: see which paid orders include something a visitor added to the cart from the chat.
    3335
    34 Activation alone does not load the hosted service. Links from the plugin and this page to Hazelchat carry campaign tags (utm_source=wordpress) so Hazelchat can count signups that start here; nothing is sent until you click one. No account password, administrative token or AI provider key belongs in WordPress settings. The public widget key grants no administrative access.
     36Activation alone does not load the hosted service, and order tracking stays off until you type a code from Hazelchat. Links from the plugin and this page to Hazelchat carry campaign tags (utm_source=wordpress) so Hazelchat can count signups that start here; nothing is sent until you click one. No account password, administrative token or AI provider key belongs in WordPress settings. The public widget key grants no administrative access.
    3537
    3638Answers use your reviewed, published sources. Source-only mode shows retrieved excerpts; AI-evidence mode writes answers from retrieved evidence. This plugin does not implement an AI engine, guarantee correctness or guarantee sales.
    3739
    38 == External service ==
     40== External services ==
    3941
    4042This plugin connects to Hazelchat, a hosted service at https://app.hazelchat.co. A Hazelchat account is required; free and paid plans are available. Billing, content management and agent configuration take place on Hazelchat, not in WordPress. Pricing: https://hazelchat.co/pricing/
    4143
    42 After an administrator supplies a valid public widget key, accepts the service connection and enables loading, visitors' browsers download https://app.hazelchat.co/widget.js. The script displays a chat frame from the same service. Browser network requests expose ordinary connection information, such as the visitor's IP address, to the service. When visitors use the chat, their questions, conversation data and any submitted enquiry details (name, email and message) are sent to Hazelchat. Configured AI-evidence mode sends questions and retrieved source passages to its model provider; source-only mode does not use a model. Retention and data requests are managed in Hazelchat. The plugin itself does not read or send WordPress users, posts, orders or private pages, and performs no server-to-server service requests or activation telemetry.
     44After an administrator supplies a valid public widget key, accepts the service connection and enables loading, visitors' browsers download https://app.hazelchat.co/widget.js. The script displays a chat frame from the same service. Browser network requests expose ordinary connection information, such as the visitor's IP address, to the service. When visitors use the chat, their questions, conversation data and any submitted enquiry details (name, email and message) are sent to Hazelchat. Configured AI-evidence mode sends questions and retrieved source passages to its model provider; source-only mode does not use a model. Retention and data requests are managed in Hazelchat. The plugin itself does not read or send WordPress users, posts or private pages, and sends no activation telemetry.
     45
     46On a WooCommerce shop, the script tag also tells the chat where WooCommerce's Store API and cart page are on your site. When a visitor clicks Add to cart on a product card in the chat, their browser adds the product to their cart on your site through WooCommerce's own Store API; nothing of the cart is sent to Hazelchat. Hazelchat reads your published products from the same public Store API, as any visitor's browser could.
     47
     48Order tracking (optional, off by default). Only after you switch it on in Hazelchat and type the code it shows into Settings > Hazelchat does this site make server-to-server requests to Hazelchat:
     49
     50* When you save the code: one request to https://app.hazelchat.co/api/integrations/woocommerce/connect with the code and your site's address. Hazelchat answers with a signing secret, which is stored in this site's database (not autoloaded) and removed on Disconnect or when you delete the plugin.
     51* When an order that includes something a visitor added to the cart from the chat is paid, cancelled or refunded: one signed request to https://app.hazelchat.co/api/integrations/woocommerce/orders, sent in the background by WooCommerce's Action Scheduler. It contains the order's id and number, its status, its total after refunds, its currency, and for each line added from the chat the product and variation id, the quantity, the line total and the random chat reference. It never contains the customer's name, email, phone, addresses, payment or shipping method, coupons, notes or any other line. Orders without a line added from the chat cause no request at all.
     52
     53The chat reference is a random code that Hazelchat adds to the chat's Add to cart; WooCommerce keeps it with that cart line and the order line (hidden in the order screen). Reports stop when you disconnect, turn widget loading off, deactivate or delete the plugin.
    4354
    4455The optional visitor-consent setting still allows the small launcher script to download; it prevents creation of the chat frame, chat API requests and session-storage access until your consent manager dispatches hazelchat-consent with detail: true. A consent manager must be connected separately. To block all external downloads before consent, configure your consent manager to block the launcher script as well. Turning consent off removes the widget but does not erase records already held by Hazelchat.
    … …  
    6576= Does it work with page builders and WooCommerce? =
    6677
    67 It adds a footer script using WordPress's normal script API. Themes must call wp_footer(). It does not import private WooCommerce data, retrieve orders or manage carts. Individual builder, commerce and optimization-plugin combinations require testing.
     78It adds a footer script using WordPress's normal script API. Themes must call wp_footer(). With WooCommerce, Hazelchat can show your published products in answers and add them to the visitor's cart through WooCommerce's Store API; connect your products in Hazelchat under Products. It never reads carts or customer data. Order tracking is optional and reports only orders that include something added from the chat (see External services). Individual builder, commerce and optimization-plugin combinations require testing.
     79
     80= What does order tracking show? =
     81
     82In Hazelchat, Analytics shows "Orders after a chat": orders that include something added to the cart from the chat, as your shop reported them, with their order number so you can check each one in WooCommerce. A click is not an order, and an order after a chat does not prove the chat caused it.
    6883
    6984= Why is my widget missing? =
    … …  
    94109== Changelog ==
    95110
     111= 1.1.0 =
     112* WooCommerce: Add to cart from the chat's product cards, on the page, through WooCommerce's Store API.
     113* Optional order tracking: after you type a code from Hazelchat, orders that include something added to the cart from the chat are reported to Hazelchat, signed and in the background. Off by default; see External services.
     114* Uninstall also removes the order tracking connection.
     115
    96116= 1.0.1 =
    97117* Settings: a "Create a free account" and "Log in" link while no key is saved.
  • hazelchat/trunk/uninstall.php

    r3727193 r3751625  
    33if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    44        exit;
     5}
     6
     7// The settings and (1.1.0) the order tracking connection with its signing secret.
     8function hazelchat_uninstall_site() {
     9        delete_option( 'hazelchat_settings' );
     10        delete_option( 'hazelchat_order_tracking' );
     11        if ( function_exists( 'as_unschedule_all_actions' ) ) {
     12                as_unschedule_all_actions( 'hazelchat_send_order_report' );
     13        }
    514}
    615
    … …  
    1120                foreach ( $hazelchat_sites as $hazelchat_site_id ) {
    1221                        switch_to_blog( $hazelchat_site_id );
    13                         delete_option( 'hazelchat_settings' );
     22                        hazelchat_uninstall_site();
    1423                        restore_current_blog();
    1524                }
    … …  
    1726        } while ( 100 === count( $hazelchat_sites ) );
    1827} else {
    19         delete_option( 'hazelchat_settings' );
     28        hazelchat_uninstall_site();
    2029}
Note: See TracChangeset for help on using the changeset viewer.