array( 'label' => 'Order Confirmation', 'description' => 'Sent when a WooCommerce order is placed (Thank You page).', 'placeholders' => '{{1}} = Order ID, {{2}} = Amount', 'sample' => "Thank you for shopping with Admark π\n\nYour order has been successfully placed.\n\nπ¦ Order ID: {{1}}\nπ° Amount: βΉ{{2}}\n\nWe'll notify you once your order is dispatched.", 'var_count' => 2, 'var_defaults' => array( 1 => 'order_id', 2 => 'order_total' ), ), 'payment_confirmation' => array( 'label' => 'Payment Confirmation', 'description' => 'Sent when payment status changes to processing/completed.', 'placeholders' => '{{1}} = Customer Name, {{2}} = Order ID', 'sample' => "Hi {{1}}\n\nWe have received your payment successfully for Order ID {{2}} β \n\nThank you for choosing Admark.\n\nYour order is now being processed.", 'var_count' => 2, 'var_defaults' => array( 1 => 'customer_name', 2 => 'order_id' ), ), 'order_dispatch' => array( 'label' => 'Order Dispatch', 'description' => 'Sent when order status changes to On-Hold (map to shipped).', 'placeholders' => '{{1}} = Customer Name, {{2}} = Order ID, {{3}} = Tracking Link', 'sample' => "Good news {{1}} π\n\nYour Admark order has been dispatched.\n\nπ¦ Order ID: {{2}}\nπ Tracking Link: {{3}}\n\nThank you for shopping with us.", 'var_count' => 3, 'var_defaults' => array( 1 => 'customer_name', 2 => 'order_id', 3 => 'tracking_link' ), ), 'delivery_confirmation' => array( 'label' => 'Delivery Confirmation', 'description' => 'Sent when order status changes to Completed.', 'placeholders' => '{{1}} = Customer Name', 'sample' => "Hi {{1}}\n\nYour Admark order has been delivered successfully β \n\nWe hope you enjoy the products.\n\nThank you for shopping with Admark π", 'var_count' => 1, 'var_defaults' => array( 1 => 'customer_name' ), ), 'feedback_request' => array( 'label' => 'Feedback / Review Request', 'description' => 'Sent 2 days after delivery via WP-Cron.', 'placeholders' => '{{1}} = Customer Name, {{2}} = Review Link', 'sample' => "Namaste {{1}}\n\nWe hope you loved your Admark purchase π\n\nPlease share your feedback and help us serve you better.\n\nβ Give Review:\n{{2}}\n\nThank you for being a valued customer.", 'var_count' => 2, 'var_defaults' => array( 1 => 'customer_name', 2 => 'review_link' ), ), 'reorder_reminder' => array( 'label' => 'Repeat Purchase / Reorder', 'description' => 'Sent manually or via campaign to encourage repeat orders.', 'placeholders' => '{{1}} = Customer Name, {{2}} = Shop Link', 'sample' => "Hello {{1}}\n\nRunning low on your favorite Admark products?\n\nπ Reorder quickly here:\n{{2}}\n\nEnjoy hassle-free shopping and doorstep delivery.", 'var_count' => 2, 'var_defaults' => array( 1 => 'customer_name', 2 => 'shop_url' ), ), 'offer_campaign' => array( 'label' => 'Offer & Festival Campaign', 'description' => 'Promotional or festival offer messages.', 'placeholders' => '{{1}} = Shop/Offer Link', 'sample' => "π Special Offer from Admark π\n\nGet exciting deals on selected products for a limited time.\n\nποΈ Shop Now:\n{{1}}\n\nHurry! Offer valid till stocks last.", 'var_count' => 1, 'var_defaults' => array( 1 => 'shop_url' ), ), 'welcome' => array( 'label' => 'Welcome Message', 'description' => 'Sent when a new customer registers on the website.', 'placeholders' => '{{1}} = Customer Name, {{2}} = Shop Link', 'sample' => "Namaste {{1}} π\n\nWelcome to Admark Online Shopping.\n\nExplore authentic Admark products, exclusive offers, and easy doorstep delivery.\n\nπ Shop Now: {{2}}\n\nIf you need any help regarding products or orders, feel free to reply to this message.", 'var_count' => 2, 'var_defaults' => array( 1 => 'customer_name', 2 => 'shop_url' ), ), 'add_to_cart' => array( 'label' => 'Add to Cart Reminder', 'description' => 'Sent ~20 minutes after a product is added to the cart (logged-in users).', 'placeholders' => '{{1}} = Customer Name, {{2}} = Cart Link', 'sample' => "Hi {{1}} π\n\nYou've added products to your cart on Admark Shopping.\n\nποΈ Your selected items are waiting for you.\n\nComplete your order here:\n{{2}}\n\nOrder now before stock runs out.", 'var_count' => 2, 'var_defaults' => array( 1 => 'customer_name', 2 => 'cart_url' ), ), 'abandoned_cart' => array( 'label' => 'Abandoned Cart', 'description' => 'Sent 3 hours after cart is abandoned without purchase.', 'placeholders' => '{{1}} = Customer Name, {{2}} = Cart/Resume Link', 'sample' => "Hello {{1}}\n\nLooks like you left some items in your Admark cart π\n\nComplete your purchase now and get your favorite products delivered to your doorstep.\n\nπ Resume Order:\n{{2}}\n\nNeed any assistance? Simply reply to this message.", 'var_count' => 2, 'var_defaults' => array( 1 => 'customer_name', 2 => 'cart_url' ), ), ); } // Option getters (fallback to constants) function wats_get_api_key() { $opt = trim( (string) get_option( 'wats_api_key', '' ) ); return $opt !== '' ? $opt : WATS_API_KEY; } function wats_get_phone_number_id() { $opt = trim( (string) get_option( 'wats_phone_number_id', '' ) ); return $opt !== '' ? $opt : WATS_PHONE_NUMBER_ID; } function wats_get_selected_template() { return trim( (string) get_option( 'wats_selected_template', '' ) ); } function wats_get_event_template( $event ) { return trim( (string) get_option( 'wats_tpl_' . $event, '' ) ); } function wats_get_event_enabled( $event ) { return (bool) get_option( 'wats_enable_' . $event, 0 ); } /** * Get configured delay in seconds for timed events (welcome, add_to_cart, abandoned_cart, feedback_request). * Defaults: welcome=0s, add_to_cart=20m, abandoned_cart=3h, feedback_request=2d. */ function wats_get_event_delay( $event ) { $defaults = array( 'welcome' => array( 'value' => 0, 'unit' => 'minutes' ), 'add_to_cart' => array( 'value' => 20, 'unit' => 'minutes' ), 'abandoned_cart' => array( 'value' => 3, 'unit' => 'hours' ), 'feedback_request' => array( 'value' => 2, 'unit' => 'days' ), ); $def = isset( $defaults[ $event ] ) ? $defaults[ $event ] : array( 'value' => 0, 'unit' => 'minutes' ); $val = (int) get_option( 'wats_delay_val_' . $event, $def['value'] ); $unit = sanitize_key( (string) get_option( 'wats_delay_unit_' . $event, $def['unit'] ) ); switch ( $unit ) { case 'hours': return $val * HOUR_IN_SECONDS; case 'days': return $val * DAY_IN_SECONDS; default: return $val * MINUTE_IN_SECONDS; } } // ==== VARIABLE MAPPING HELPERS ==== /** * Returns all available data fields that can be mapped to template variables. */ function wats_get_variable_options() { return array( 'customer_name' => 'Customer Name', 'phone' => 'Mobile Number', 'email' => 'Email', 'billing_address' => 'Billing Address', 'order_id' => 'Order ID', 'order_total' => 'Order Amount', 'product_names' => 'Product Name(s)', 'product_qty' => 'Product Quantity', 'tracking_link' => 'Tracking Link', 'shop_url' => 'Shop URL', 'cart_url' => 'Cart URL', 'review_link' => 'Review Link', ); } /** * Get the saved variable mapping for an event slot, falling back to the event default. */ function wats_get_var_map( $event, $slot ) { $saved = trim( (string) get_option( 'wats_varmap_' . $event . '_' . $slot, '' ) ); if ( $saved !== '' ) { return $saved; } $events = wats_get_events(); return isset( $events[ $event ]['var_defaults'][ $slot ] ) ? $events[ $event ]['var_defaults'][ $slot ] : ''; } /** * Resolve a variable map key to an actual value using order/user context. */ function wats_resolve_var( $key, $order = null, $user = null ) { switch ( $key ) { case 'customer_name': if ( $order ) { return trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ); } if ( $user ) { return trim( $user->first_name . ' ' . $user->last_name ) ?: $user->display_name; } return ''; case 'phone': if ( $order ) { return $order->get_billing_phone(); } if ( $user ) { return (string) get_user_meta( $user->ID, 'billing_phone', true ); } return ''; case 'email': if ( $order ) { return $order->get_billing_email(); } if ( $user ) { return $user->user_email; } return ''; case 'billing_address': if ( $order ) { return wp_strip_all_tags( $order->get_formatted_billing_address() ); } return ''; case 'order_id': if ( $order ) { return (string) $order->get_id(); } return ''; case 'order_total': if ( $order ) { return html_entity_decode( wp_strip_all_tags( $order->get_formatted_order_total() ) ); } return ''; case 'product_names': if ( $order ) { $names = array(); foreach ( $order->get_items() as $item ) { $names[] = $item->get_name(); } return implode( ', ', $names ); } return ''; case 'product_qty': if ( $order ) { $qtys = array(); foreach ( $order->get_items() as $item ) { $qtys[] = (string) $item->get_quantity(); } return implode( ', ', $qtys ); } return ''; case 'tracking_link': if ( $order ) { $link = (string) $order->get_meta( '_wats_tracking_link' ); return $link !== '' ? $link : home_url(); } return home_url(); case 'shop_url': return function_exists( 'wc_get_page_id' ) ? ( get_permalink( wc_get_page_id( 'shop' ) ) ?: home_url( '/shop/' ) ) : home_url( '/shop/' ); case 'cart_url': return function_exists( 'wc_get_cart_url' ) ? wc_get_cart_url() : home_url( '/cart/' ); case 'review_link': if ( $order ) { return get_permalink( $order->get_id() ) ?: home_url(); } return home_url(); default: return ''; } } // ==== SANITIZERS ==== function wats_sanitize_api_key( $value ) { return sanitize_text_field( (string) $value ); } function wats_sanitize_phone_number_id( $value ) { $value = sanitize_text_field( (string) $value ); // keep digits only return preg_replace( '/\D+/', '', $value ); } function wats_sanitize_selected_template( $value ) { $val = sanitize_text_field( (string) $value ); if ( $val === '' ) { return ''; } $api_key_present = ( wats_get_api_key() !== '' ); $templates = $api_key_present ? get_transient( 'wats_templates_cache' ) : array(); if ( $templates === false && $api_key_present ) { // Best-effort fetch when saving, so we can validate $templates = wats_fetch_templates(); } if ( ! is_array( $templates ) ) { $templates = array(); } return in_array( $val, $templates, true ) ? $val : ''; } function wats_sanitize_send_count( $value ) { return absint( $value ); } function wats_sanitize_send_log( $value ) { if ( ! is_array( $value ) ) { return array(); } $out = array(); $tz = wp_timezone(); foreach ( $value as $entry ) { if ( is_array( $entry ) ) { $utc = isset( $entry['utc'] ) ? (int) $entry['utc'] : 0; $local = isset( $entry['local'] ) ? sanitize_text_field( (string) $entry['local'] ) : ''; if ( $utc > 0 && $utc < 32503680000 ) { // simple sanity bound (< year 3000) $out[] = array( 'local' => $local, 'utc' => $utc ); } } elseif ( is_string( $entry ) ) { $dt = date_create_immutable( $entry, $tz ); if ( $dt ) { $out[] = array( 'local' => sanitize_text_field( $entry ), 'utc' => $dt->getTimestamp() - (int) $tz->getOffset( $dt ), ); } } } // keep the log from growing unbounded when saved via options if ( count( $out ) > 5000 ) { $out = array_slice( $out, -5000 ); } return $out; } // ===================== /** * Normalize an Indian phone number to 91XXXXXXXXXX (digits only). */ function wats_normalize_phone( $raw ) { $digits = preg_replace( '/\D+/', '', (string) $raw ); if ( strlen( $digits ) === 11 && wats_str_starts_with( $digits, '0' ) ) { $digits = substr( $digits, 1 ); } if ( wats_str_starts_with( $digits, '91' ) && strlen( $digits ) === 12 ) { return $digits; } if ( strlen( $digits ) === 10 ) { return '91' . $digits; } return $digits; } /** * Prepare values for {{1}}..{{5}} and return csvVariables as a URL-ready CSV string. */ function wats_build_csv_variables( $order ) { $items = $order->get_items(); $names = array(); $quantities = array(); foreach ( $items as $item ) { $names[] = $item->get_name(); $quantities[] = (string) $item->get_quantity(); } $products_str = implode( ', ', $names ); $quantities_str = implode( ', ', $quantities ); $total_str = html_entity_decode( wp_strip_all_tags( $order->get_formatted_order_total() ) ); $first_name = $order->get_billing_first_name(); $last_name = $order->get_billing_last_name(); $customer_name = trim( $first_name . ' ' . $last_name ); $values = array( $customer_name, // {{1}} (string) $order->get_id(), // {{2}} $products_str, // {{3}} $quantities_str, // {{4}} $total_str, // {{5}} ); $encoded = array_map( 'rawurlencode', $values ); return implode( ',', $encoded ); } /** * Build csvVariables string for a specific automation event using saved variable mappings. * Uses the saved wats_varcount_{event} option (set by the admin UI) so any template * variable count is respected, not just the hardcoded event default. */ function wats_build_csv_for_event( $event, $order = null, $user = null ) { $var_count = (int) get_option( 'wats_varcount_' . $event, 0 ); if ( $var_count <= 0 ) { // Fall back to event definition default $events = wats_get_events(); $var_count = isset( $events[ $event ]['var_count'] ) ? (int) $events[ $event ]['var_count'] : 2; } $vars = array(); for ( $i = 1; $i <= $var_count; $i++ ) { $map_key = wats_get_var_map( $event, $i ); $vars[] = $map_key !== '' ? wats_resolve_var( $map_key, $order, $user ) : ''; } return implode( ',', array_map( 'rawurlencode', $vars ) ); } /** * Build API URL with query params, using csvVariables. */ function wats_build_url( $args ) { $params = array( 'api-key' => wats_get_api_key(), 'templateName' => $args['templateName'] ?? '', 'phoneNumber' => $args['phoneNumber'] ?? '', 'phoneNumberId' => wats_get_phone_number_id(), 'csvVariables' => $args['csvVariables'] ?? '', ); $params = array_filter( $params, function( $v ) { return $v !== '' && $v !== null; } ); return add_query_arg( $params, WATS_API_BASE ); } /** * Send Admark CRM template call for a given event and log timestamp for stats. */ function wats_send_template( $order, $event = 'order_confirmation' ) { try { if ( ! class_exists( 'WC_Order' ) || ! ( is_object( $order ) && $order instanceof WC_Order ) ) { return; } // Resolve template for this event, falling back to legacy default $template = wats_get_event_template( $event ); if ( $template === '' && $event === 'order_confirmation' ) { $template = wats_get_selected_template(); } $order_id = $order->get_id(); $raw_phone = $order->get_billing_phone(); if ( empty( $raw_phone ) ) { wc_get_logger()->warning( "[WATS] Order {$order_id} / {$event}: Missing billing phone; skipping." ); return; } if ( $template === '' ) { wc_get_logger()->warning( "[WATS] Order {$order_id} / {$event}: No template configured; skipping." ); return; } $phone = wats_normalize_phone( $raw_phone ); $csv = wats_build_csv_for_event( $event, $order ); $url = wats_build_url( array( 'templateName' => $template, 'phoneNumber' => $phone, 'csvVariables' => $csv, ) ); $response = wp_remote_get( $url, array( 'timeout' => 15, 'headers' => array( 'Accept' => 'application/json' ), ) ); if ( is_wp_error( $response ) ) { wc_get_logger()->error( "[WATS] Order {$order_id} / {$event}: HTTP error - " . $response->get_error_message() ); return; } $code = wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); if ( $code >= 200 && $code < 300 ) { wc_get_logger()->info( "[WATS] Order {$order_id} / {$event}: WhatsApp sent to {$phone}. Response: {$body}" ); $count = (int) get_option( 'wats_send_count', 0 ); update_option( 'wats_send_count', $count + 1, false ); $log = get_option( 'wats_send_log', array() ); if ( ! is_array( $log ) ) { $log = array(); } $log[] = array( 'local' => current_time( 'mysql' ), 'utc' => time(), 'event' => $event ); update_option( 'wats_send_log', $log, false ); } else { wc_get_logger()->error( "[WATS] Order {$order_id} / {$event}: API returned {$code}. Response: {$body}" ); } } catch ( Throwable $e ) { wc_get_logger()->error( "[WATS] Event {$event} error: " . $e->getMessage() ); } } // ==== AUTOMATION HOOKS ==== // 1. Order Confirmation β Thank You page add_action( 'woocommerce_thankyou', function( $order_id ) { if ( ! $order_id ) { return; } if ( ! wats_get_event_enabled( 'order_confirmation' ) ) { return; } $order = wc_get_order( $order_id ); if ( $order && ! $order->get_meta( '_wats_order_confirmation_sent' ) ) { wats_send_template( $order, 'order_confirmation' ); $order->update_meta_data( '_wats_order_confirmation_sent', current_time( 'mysql' ) ); $order->save(); } }, 20, 1 ); // 2. Payment Confirmation β status β processing add_action( 'woocommerce_order_status_processing', function( $order_id ) { if ( ! wats_get_event_enabled( 'payment_confirmation' ) ) { return; } $order = wc_get_order( $order_id ); if ( $order && ! $order->get_meta( '_wats_payment_confirmation_sent' ) ) { wats_send_template( $order, 'payment_confirmation' ); $order->update_meta_data( '_wats_payment_confirmation_sent', current_time( 'mysql' ) ); $order->save(); } }, 10, 1 ); // 3. Order Dispatch β status β on-hold (re-map in WooCommerce if you have a "Shipped" status) add_action( 'woocommerce_order_status_on-hold', function( $order_id ) { if ( ! wats_get_event_enabled( 'order_dispatch' ) ) { return; } $order = wc_get_order( $order_id ); if ( $order && ! $order->get_meta( '_wats_dispatch_sent' ) ) { wats_send_template( $order, 'order_dispatch' ); $order->update_meta_data( '_wats_dispatch_sent', current_time( 'mysql' ) ); $order->save(); } }, 10, 1 ); // 4. Delivery Confirmation β status β completed add_action( 'woocommerce_order_status_completed', function( $order_id ) { if ( ! wats_get_event_enabled( 'delivery_confirmation' ) ) { return; } $order = wc_get_order( $order_id ); if ( $order && ! $order->get_meta( '_wats_delivery_sent' ) ) { wats_send_template( $order, 'delivery_confirmation' ); $order->update_meta_data( '_wats_delivery_sent', current_time( 'mysql' ) ); $order->save(); } }, 10, 1 ); // 5. Feedback Request β 2 days after delivery (WP-Cron) add_action( 'woocommerce_order_status_completed', function( $order_id ) { if ( ! wats_get_event_enabled( 'feedback_request' ) ) { return; } if ( ! wp_next_scheduled( 'wats_send_feedback', array( $order_id ) ) ) { wp_schedule_single_event( time() + 2 * DAY_IN_SECONDS, 'wats_send_feedback', array( $order_id ) ); } }, 20, 1 ); add_action( 'wats_send_feedback', function( $order_id ) { $order = wc_get_order( $order_id ); if ( $order && ! $order->get_meta( '_wats_feedback_sent' ) ) { wats_send_template( $order, 'feedback_request' ); $order->update_meta_data( '_wats_feedback_sent', current_time( 'mysql' ) ); $order->save(); } }, 10, 1 ); // 6. Welcome Message β new user registration (optionally delayed) add_action( 'user_register', function( $user_id ) { if ( ! wats_get_event_enabled( 'welcome' ) ) { return; } $template = wats_get_event_template( 'welcome' ); if ( $template === '' ) { return; } $delay = wats_get_event_delay( 'welcome' ); if ( $delay > 0 ) { wp_schedule_single_event( time() + $delay, 'wats_send_welcome', array( $user_id ) ); } else { $user = get_userdata( $user_id ); $phone = get_user_meta( $user_id, 'billing_phone', true ); if ( empty( $phone ) ) { return; } $csv = wats_build_csv_for_event( 'welcome', null, $user ); wp_remote_get( wats_build_url( array( 'templateName' => $template, 'phoneNumber' => wats_normalize_phone( $phone ), 'csvVariables' => $csv ) ), array( 'timeout' => 15 ) ); } }, 10, 1 ); add_action( 'wats_send_welcome', function( $user_id ) { $template = wats_get_event_template( 'welcome' ); if ( $template === '' ) { return; } $user = get_userdata( $user_id ); $phone = get_user_meta( $user_id, 'billing_phone', true ); if ( empty( $phone ) ) { return; } $csv = wats_build_csv_for_event( 'welcome', null, $user ); wp_remote_get( wats_build_url( array( 'templateName' => $template, 'phoneNumber' => wats_normalize_phone( $phone ), 'csvVariables' => $csv ) ), array( 'timeout' => 15 ) ); }, 10, 1 ); // 7. Add to Cart Reminder β configurable delay after add to cart (logged-in users) add_action( 'woocommerce_add_to_cart', function() { if ( ! wats_get_event_enabled( 'add_to_cart' ) ) { return; } $user_id = get_current_user_id(); if ( ! $user_id ) { return; } $args = array( $user_id ); $existing = wp_next_scheduled( 'wats_send_cart_reminder', $args ); if ( $existing ) { wp_unschedule_event( $existing, 'wats_send_cart_reminder', $args ); } $delay = wats_get_event_delay( 'add_to_cart' ); wp_schedule_single_event( time() + max( 60, $delay ), 'wats_send_cart_reminder', $args ); }, 10, 0 ); add_action( 'wats_send_cart_reminder', function( $user_id ) { $template = wats_get_event_template( 'add_to_cart' ); if ( $template === '' ) { return; } $user = get_userdata( $user_id ); $phone = get_user_meta( $user_id, 'billing_phone', true ); if ( empty( $phone ) ) { return; } $csv = wats_build_csv_for_event( 'add_to_cart', null, $user ); wp_remote_get( wats_build_url( array( 'templateName' => $template, 'phoneNumber' => wats_normalize_phone( $phone ), 'csvVariables' => $csv ) ), array( 'timeout' => 15 ) ); }, 10, 1 ); // 8. Abandoned Cart β configurable delay after add_to_cart, cancelled if order placed add_action( 'woocommerce_add_to_cart', function() { if ( ! wats_get_event_enabled( 'abandoned_cart' ) ) { return; } $user_id = get_current_user_id(); if ( ! $user_id ) { return; } $args = array( $user_id ); $existing = wp_next_scheduled( 'wats_send_abandoned_cart', $args ); if ( $existing ) { wp_unschedule_event( $existing, 'wats_send_abandoned_cart', $args ); } $delay = wats_get_event_delay( 'abandoned_cart' ); wp_schedule_single_event( time() + max( 60, $delay ), 'wats_send_abandoned_cart', $args ); }, 10, 0 ); add_action( 'woocommerce_thankyou', function( $order_id ) { $order = wc_get_order( $order_id ); $user_id = $order ? $order->get_user_id() : 0; if ( $user_id ) { foreach ( array( 'wats_send_abandoned_cart', 'wats_send_cart_reminder' ) as $hook ) { $args = array( $user_id ); $existing = wp_next_scheduled( $hook, $args ); if ( $existing ) { wp_unschedule_event( $existing, $hook, $args ); } } } }, 5, 1 ); add_action( 'wats_send_abandoned_cart', function( $user_id ) { $template = wats_get_event_template( 'abandoned_cart' ); if ( $template === '' ) { return; } $user = get_userdata( $user_id ); $phone = get_user_meta( $user_id, 'billing_phone', true ); if ( empty( $phone ) ) { return; } $csv = wats_build_csv_for_event( 'abandoned_cart', null, $user ); wp_remote_get( wats_build_url( array( 'templateName' => $template, 'phoneNumber' => wats_normalize_phone( $phone ), 'csvVariables' => $csv ) ), array( 'timeout' => 15 ) ); }, 10, 1 ); // ==== SURECART INTEGRATION ==== /** * Extract phone from any SureCart object (checkout session OR order). * Tries every known property path, then falls back to WP user meta via email lookup. */ function wats_get_surecart_phone( $obj ) { // Flat direct fields foreach ( array( 'phone', 'billing_phone', 'customer_phone' ) as $k ) { if ( ! empty( $obj->$k ) ) { return (string) $obj->$k; } } // Metadata array/object (custom checkout fields) if ( ! empty( $obj->metadata ) ) { $meta = (array) $obj->metadata; foreach ( array( 'phone', 'Phone', 'billing_phone', 'customer_phone' ) as $k ) { if ( ! empty( $meta[ $k ] ) ) { return (string) $meta[ $k ]; } } } // Nested customer object if ( ! empty( $obj->customer->phone ) ) { return (string) $obj->customer->phone; } // Address objects (checkout session stores phone here) if ( ! empty( $obj->billing_address->phone ) ) { return (string) $obj->billing_address->phone; } if ( ! empty( $obj->shipping_address->phone ) ) { return (string) $obj->shipping_address->phone; } // WordPress user meta fallback β look up by customer email $email = ''; if ( ! empty( $obj->customer->email ) ) { $email = (string) $obj->customer->email; } elseif ( ! empty( $obj->customer_email ) ) { $email = (string) $obj->customer_email; } elseif ( ! empty( $obj->email ) ) { $email = (string) $obj->email; } if ( $email !== '' ) { $user = get_user_by( 'email', $email ); if ( $user ) { $phone = (string) get_user_meta( $user->ID, 'billing_phone', true ); if ( $phone !== '' ) { return $phone; } } } return ''; } /** * Resolve a mapping key against a SureCart object (checkout session or order). * When a checkout session is passed, also looks inside ->order for line_items/amounts. */ function wats_resolve_surecart_var( $key, $obj ) { // If $obj is a checkout session, the actual order is nested $order = isset( $obj->order ) ? $obj->order : $obj; switch ( $key ) { case 'customer_name': if ( ! empty( $obj->customer_name ) ) { return (string) $obj->customer_name; } if ( ! empty( $obj->customer->name ) ) { return (string) $obj->customer->name; } if ( ! empty( $order->customer->name ) ) { return (string) $order->customer->name; } return ''; case 'phone': return wats_get_surecart_phone( $obj ); case 'email': if ( ! empty( $obj->customer->email ) ) { return (string) $obj->customer->email; } if ( ! empty( $obj->customer_email ) ) { return (string) $obj->customer_email; } if ( ! empty( $obj->email ) ) { return (string) $obj->email; } return ''; case 'order_id': if ( ! empty( $order->number ) ) { return '#' . $order->number; } if ( ! empty( $order->id ) ) { return (string) $order->id; } if ( ! empty( $obj->number ) ) { return '#' . $obj->number; } return ''; case 'order_total': $amount = null; if ( isset( $order->total_amount ) ) { $amount = (int) $order->total_amount; } elseif ( isset( $obj->total_amount ) ) { $amount = (int) $obj->total_amount; } elseif ( isset( $order->amount_due ) ) { $amount = (int) $order->amount_due; } if ( $amount !== null ) { $currency = isset( $order->currency ) ? strtoupper( $order->currency ) : ( isset( $obj->currency ) ? strtoupper( $obj->currency ) : 'INR' ); return $currency . ' ' . number_format( $amount / 100, 2 ); } return ''; case 'product_names': // Try obj->line_items, order->line_items in both array and ->data forms foreach ( array( $obj, $order ) as $src ) { if ( isset( $src->line_items->data ) && is_array( $src->line_items->data ) ) { $names = array(); foreach ( $src->line_items->data as $item ) { $name = $item->price->product->name ?? ( $item->product_name ?? ( $item->name ?? '' ) ); if ( $name !== '' ) { $names[] = $name; } } if ( $names ) { return implode( ', ', $names ); } } if ( isset( $src->line_items ) && is_array( $src->line_items ) ) { $names = array(); foreach ( $src->line_items as $item ) { $name = $item->price->product->name ?? ( $item->product_name ?? ( $item->name ?? '' ) ); if ( $name !== '' ) { $names[] = $name; } } if ( $names ) { return implode( ', ', $names ); } } } return ''; case 'product_qty': foreach ( array( $obj, $order ) as $src ) { if ( isset( $src->line_items->data ) && is_array( $src->line_items->data ) ) { $qtys = array(); foreach ( $src->line_items->data as $item ) { $qtys[] = isset( $item->quantity ) ? (string) $item->quantity : '1'; } if ( $qtys ) { return implode( ', ', $qtys ); } } if ( isset( $src->line_items ) && is_array( $src->line_items ) ) { $qtys = array(); foreach ( $src->line_items as $item ) { $qtys[] = isset( $item->quantity ) ? (string) $item->quantity : '1'; } if ( $qtys ) { return implode( ', ', $qtys ); } } } return ''; case 'billing_address': $addr = $obj->billing_address ?? ( $obj->shipping_address ?? ( $order->billing_address ?? ( $order->shipping_address ?? null ) ) ); if ( $addr ) { $parts = array_filter( array( isset( $addr->line_1 ) ? (string) $addr->line_1 : '', isset( $addr->line_2 ) ? (string) $addr->line_2 : '', isset( $addr->city ) ? (string) $addr->city : '', isset( $addr->state ) ? (string) $addr->state : '', isset( $addr->postal_code ) ? (string) $addr->postal_code : '', isset( $addr->country ) ? (string) $addr->country : '', ) ); return implode( ', ', $parts ); } return ''; case 'shop_url': return home_url(); case 'cart_url': return home_url(); case 'tracking_link': return home_url(); case 'review_link': return home_url(); default: return ''; } } /** * Build csvVariables string for a SureCart event using saved variable mappings. */ function wats_build_csv_for_surecart_event( $event, $order ) { $var_count = (int) get_option( 'wats_varcount_' . $event, 0 ); if ( $var_count <= 0 ) { $events = wats_get_events(); $var_count = isset( $events[ $event ]['var_count'] ) ? (int) $events[ $event ]['var_count'] : 2; } $vars = array(); for ( $i = 1; $i <= $var_count; $i++ ) { $map_key = wats_get_var_map( $event, $i ); $vars[] = $map_key !== '' ? wats_resolve_surecart_var( $map_key, $order ) : ''; } return implode( ',', array_map( 'rawurlencode', $vars ) ); } /** * Send a WhatsApp template message for a SureCart event. * $sc_obj can be a checkout session OR an order β phone extraction handles both. */ function wats_send_template_surecart( $sc_obj, $event = 'order_confirmation' ) { try { $template = wats_get_event_template( $event ); if ( $template === '' ) { error_log( '[WATS SureCart] Event ' . $event . ': No template configured; skipping.' ); return; } $raw_phone = wats_get_surecart_phone( $sc_obj ); if ( empty( $raw_phone ) ) { // Log the object shape so we can debug what properties exist error_log( '[WATS SureCart] Event ' . $event . ': No phone found. Object keys: ' . implode( ', ', array_keys( (array) $sc_obj ) ) ); return; } $phone = wats_normalize_phone( $raw_phone ); $csv = wats_build_csv_for_surecart_event( $event, $sc_obj ); $url = wats_build_url( array( 'templateName' => $template, 'phoneNumber' => $phone, 'csvVariables' => $csv, ) ); error_log( '[WATS SureCart] Event ' . $event . ': Sending to ' . $phone . ' template=' . $template ); $response = wp_remote_get( $url, array( 'timeout' => 15, 'headers' => array( 'Accept' => 'application/json' ), ) ); if ( is_wp_error( $response ) ) { error_log( '[WATS SureCart] Event ' . $event . ': HTTP error - ' . $response->get_error_message() ); return; } $code = wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); if ( $code >= 200 && $code < 300 ) { error_log( '[WATS SureCart] Event ' . $event . ': Sent OK. Response: ' . $body ); $count = (int) get_option( 'wats_send_count', 0 ); update_option( 'wats_send_count', $count + 1, false ); $log = get_option( 'wats_send_log', array() ); if ( ! is_array( $log ) ) { $log = array(); } $log[] = array( 'local' => current_time( 'mysql' ), 'utc' => time(), 'event' => $event . '_sc' ); update_option( 'wats_send_log', $log, false ); } else { error_log( '[WATS SureCart] Event ' . $event . ': API returned ' . $code . '. Body: ' . $body ); } } catch ( Throwable $e ) { error_log( '[WATS SureCart] Event ' . $event . ' error: ' . $e->getMessage() ); } } /** * Central handler β accepts a checkout session or order object, deduplicates by order ID. */ function wats_handle_surecart_paid( $sc_obj ) { // Resolve the order ID for deduplication $order = isset( $sc_obj->order ) ? $sc_obj->order : $sc_obj; $order_id = isset( $order->id ) ? (string) $order->id : ''; error_log( '[WATS SureCart] Hook fired. Order ID: ' . ( $order_id ?: 'unknown' ) . ' Object type: ' . ( isset( $sc_obj->object ) ? $sc_obj->object : get_class( $sc_obj ) ) ); if ( wats_get_event_enabled( 'order_confirmation' ) ) { if ( ! ( $order_id && get_option( '_wats_sc_order_confirmation_' . $order_id ) ) ) { wats_send_template_surecart( $sc_obj, 'order_confirmation' ); if ( $order_id ) { update_option( '_wats_sc_order_confirmation_' . $order_id, 1, false ); } } } if ( wats_get_event_enabled( 'payment_confirmation' ) ) { if ( ! ( $order_id && get_option( '_wats_sc_payment_confirmation_' . $order_id ) ) ) { wats_send_template_surecart( $sc_obj, 'payment_confirmation' ); if ( $order_id ) { update_option( '_wats_sc_payment_confirmation_' . $order_id, 1, false ); } } } } // Hook 1: surecart/checkout_session_completed β most reliable, fires on every paid checkout // IMPORTANT: pass the full $checkout (not $checkout->order) so billing_address->phone is accessible add_action( 'surecart/checkout_session_completed', function( $checkout ) { wats_handle_surecart_paid( $checkout ); }, 10, 1 ); // Hook 2: surecart/order_paid β fires in some SureCart versions add_action( 'surecart/order_paid', function( $order ) { wats_handle_surecart_paid( $order ); }, 10, 1 ); // Hook 3: surecart/checkout_confirmed β alternate hook name in some versions add_action( 'surecart/checkout_confirmed', function( $checkout ) { wats_handle_surecart_paid( $checkout ); }, 10, 1 ); /** * Fetch templates list from provider. Returns array of template names. * Also caches variable count per template in wats_template_vars_cache. */ function wats_fetch_templates() { $api_key = wats_get_api_key(); if ( $api_key === '' ) { delete_transient( 'wats_templates_cache' ); delete_transient( 'wats_template_vars_cache' ); return array(); } $url = add_query_arg( array( 'api-key' => $api_key ), 'https://verifiedwhatsapp.admarksolution.com/templates' ); $response = wp_remote_get( $url, array( 'timeout' => 15, 'headers' => array( 'Accept' => 'application/json' ) ) ); if ( is_wp_error( $response ) ) { return array(); } $code = wp_remote_retrieve_response_code( $response ); if ( $code < 200 || $code >= 300 ) { return array(); } $data = json_decode( wp_remote_retrieve_body( $response ), true ); $out = array(); $var_counts = array(); // template_name => variable count if ( is_array( $data ) ) { foreach ( $data as $item ) { if ( is_string( $item ) ) { $out[] = $item; } elseif ( is_array( $item ) && isset( $item['name'] ) && is_string( $item['name'] ) ) { $name = $item['name']; $out[] = $name; // Detect variable count from components (standard WhatsApp API format) $count = 0; if ( isset( $item['components'] ) && is_array( $item['components'] ) ) { foreach ( $item['components'] as $comp ) { $type = isset( $comp['type'] ) ? strtolower( $comp['type'] ) : ''; if ( $type === 'body' ) { // Count {{n}} placeholders in body text $text = isset( $comp['text'] ) ? $comp['text'] : ''; if ( $text !== '' && preg_match_all( '/\{\{(\d+)\}\}/', $text, $m ) ) { $count = max( $count, max( array_map( 'intval', $m[1] ) ) ); } // Fallback: count from example body_text array if ( isset( $comp['example']['body_text'][0] ) && is_array( $comp['example']['body_text'][0] ) ) { $count = max( $count, count( $comp['example']['body_text'][0] ) ); } } } } // Fallback fields some providers include if ( $count === 0 && isset( $item['variables_count'] ) ) { $count = (int) $item['variables_count']; } if ( $count === 0 && isset( $item['params_count'] ) ) { $count = (int) $item['params_count']; } $var_counts[ $name ] = $count; } } } if ( ! empty( $out ) ) { set_transient( 'wats_templates_cache', $out, 10 * MINUTE_IN_SECONDS ); set_transient( 'wats_template_vars_cache', $var_counts, 10 * MINUTE_IN_SECONDS ); } else { delete_transient( 'wats_templates_cache' ); delete_transient( 'wats_template_vars_cache' ); } return array_values( array_unique( $out ) ); } /** * Get cached variable counts per template name. Returns array: ['name' => count]. */ function wats_get_template_var_counts() { $counts = get_transient( 'wats_template_vars_cache' ); return is_array( $counts ) ? $counts : array(); } /** * AJAX: Fetch variable count for a single template via /template-byname endpoint. */ add_action( 'wp_ajax_wats_get_template_vars', function() { check_ajax_referer( 'wats_ajax_nonce', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorized', 403 ); } $template_name = sanitize_text_field( (string) ( $_GET['template'] ?? '' ) ); if ( $template_name === '' ) { wp_send_json_error( 'Missing template name', 400 ); } $api_key = wats_get_api_key(); if ( $api_key === '' ) { wp_send_json_error( 'No API key configured', 400 ); } $url = add_query_arg( array( 'name' => $template_name, 'api-key' => $api_key ), 'https://verifiedwhatsapp.admarksolution.com/template-byname' ); $response = wp_remote_get( $url, array( 'timeout' => 15, 'headers' => array( 'Accept' => 'application/json' ) ) ); if ( is_wp_error( $response ) ) { wp_send_json_error( $response->get_error_message(), 502 ); } $code = wp_remote_retrieve_response_code( $response ); if ( $code < 200 || $code >= 300 ) { wp_send_json_error( 'API error ' . $code, 502 ); } $data = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $data ) ) { wp_send_json_error( 'Invalid API response', 502 ); } // Parse variable count β try every known response format $var_count = 0; // Format: {"variables": {"count": 3}} if ( isset( $data['variables']['count'] ) ) { $var_count = (int) $data['variables']['count']; } // Format: {"variables": {"1": {...}, "2": {...}}} β object keyed by slot number if ( $var_count === 0 && isset( $data['variables'] ) && is_array( $data['variables'] ) ) { $var_count = count( $data['variables'] ); } // Parse body component for {{n}} placeholders if ( $var_count === 0 && isset( $data['components'] ) && is_array( $data['components'] ) ) { foreach ( $data['components'] as $comp ) { $type = isset( $comp['type'] ) ? strtolower( $comp['type'] ) : ''; if ( $type === 'body' ) { $text = isset( $comp['text'] ) ? $comp['text'] : ''; if ( $text !== '' && preg_match_all( '/\{\{(\d+)\}\}/', $text, $m ) ) { $var_count = max( $var_count, max( array_map( 'intval', $m[1] ) ) ); } if ( isset( $comp['example']['body_text'][0] ) && is_array( $comp['example']['body_text'][0] ) ) { $var_count = max( $var_count, count( $comp['example']['body_text'][0] ) ); } } } } // Fallback scalar fields if ( $var_count === 0 && isset( $data['variables_count'] ) ) { $var_count = (int) $data['variables_count']; } if ( $var_count === 0 && isset( $data['params_count'] ) ) { $var_count = (int) $data['params_count']; } if ( $var_count === 0 && isset( $data['variable_count'] ) ) { $var_count = (int) $data['variable_count']; } // Update the cache $cache = get_transient( 'wats_template_vars_cache' ); if ( ! is_array( $cache ) ) { $cache = array(); } $cache[ $template_name ] = $var_count; set_transient( 'wats_template_vars_cache', $cache, 10 * MINUTE_IN_SECONDS ); wp_send_json_success( array( 'template' => $template_name, 'var_count' => $var_count, 'raw' => $data, ) ); } ); /** * Count sends within a date range (inclusive) using UTC-safe comparisons. */ function wats_count_between( $start, $end ) { $log = get_option( 'wats_send_log', array() ); if ( empty( $log ) ) { return 0; } $tz = wp_timezone(); // site timezone $start_dt = $start ? date_create_immutable( $start . ' 00:00:00', $tz ) : null; $end_dt = $end ? date_create_immutable( $end . ' 23:59:59', $tz ) : null; $start_utc = $start_dt ? $start_dt->getTimestamp() - (int) $tz->getOffset( $start_dt ) : PHP_INT_MIN; $end_utc = $end_dt ? $end_dt->getTimestamp() - (int) $tz->getOffset( $end_dt ) : PHP_INT_MAX; $count = 0; foreach ( $log as $entry ) { if ( is_array( $entry ) && isset( $entry['utc'] ) ) { $ts = (int) $entry['utc']; } else { $dt = date_create_immutable( (string) $entry, $tz ); $ts = $dt ? $dt->getTimestamp() - (int) $tz->getOffset( $dt ) : 0; } if ( $ts >= $start_utc && $ts <= $end_utc ) { $count++; } } return $count; } /** * Admin menu: add top-level page and subpages. */ add_action( 'admin_menu', function () { add_menu_page( 'Admark CRM', 'Admark CRM', 'manage_options', 'wats-settings', 'wats_render_settings_page', 'dashicons-whatsapp', 56 ); add_submenu_page( 'wats-settings', 'Settings', 'Settings', 'manage_options', 'wats-settings', 'wats_render_settings_page' ); add_submenu_page( 'wats-settings', 'Automation', 'Automation', 'manage_options', 'wats-automation', 'wats_render_automation_page' ); add_submenu_page( 'wats-settings', 'Message Templates', 'Message Templates', 'manage_options', 'wats-message-templates', 'wats_render_message_templates_page' ); } ); // Enqueue admin styles and scripts only on our pages add_action( 'admin_enqueue_scripts', function( $hook_suffix ) { $pages = array( 'toplevel_page_wats-settings', 'admark-crm_page_wats-automation', 'admark-crm_page_wats-message-templates' ); if ( ! in_array( $hook_suffix, $pages, true ) ) { return; } wp_register_style( 'admark-crm-admin', plugins_url( 'assets/admin.css', __FILE__ ), array(), '2.0.0' ); wp_enqueue_style( 'admark-crm-admin' ); wp_register_script( 'admark-crm-admin', plugins_url( 'assets/admin.js', __FILE__ ), array(), '2.0.0', true ); wp_enqueue_script( 'admark-crm-admin' ); } ); /** * Register settings. */ add_action( 'admin_init', function () { register_setting( 'wats_settings_group', 'wats_api_key', array( 'sanitize_callback' => 'wats_sanitize_api_key' ) ); register_setting( 'wats_settings_group', 'wats_phone_number_id', array( 'sanitize_callback' => 'wats_sanitize_phone_number_id' ) ); register_setting( 'wats_settings_group', 'wats_selected_template', array( 'sanitize_callback' => 'wats_sanitize_selected_template' ) ); register_setting( 'wats_settings_group', 'wats_send_count', array( 'sanitize_callback' => 'wats_sanitize_send_count' ) ); register_setting( 'wats_settings_group', 'wats_send_log', array( 'sanitize_callback' => 'wats_sanitize_send_log' ) ); foreach ( array_keys( wats_get_events() ) as $event ) { register_setting( 'wats_automation_group', 'wats_enable_' . $event, array( 'sanitize_callback' => 'absint' ) ); register_setting( 'wats_automation_group', 'wats_tpl_' . $event, array( 'sanitize_callback' => 'sanitize_text_field' ) ); register_setting( 'wats_automation_group', 'wats_varcount_' . $event, array( 'sanitize_callback' => 'absint' ) ); register_setting( 'wats_automation_group', 'wats_delay_val_' . $event, array( 'sanitize_callback' => 'absint' ) ); register_setting( 'wats_automation_group', 'wats_delay_unit_' . $event, array( 'sanitize_callback' => 'sanitize_key' ) ); for ( $i = 1; $i <= 10; $i++ ) { register_setting( 'wats_automation_group', 'wats_varmap_' . $event . '_' . $i, array( 'sanitize_callback' => 'sanitize_text_field' ) ); } } } ); // ==== SHARED NAV HELPER ==== function wats_render_nav( $active ) { $tabs = array( 'wats-settings' => 'Settings', 'wats-automation' => 'Automation', 'wats-message-templates' => 'Message Templates', ); echo ''; } // ==== SETTINGS PAGE ==== function wats_render_settings_page() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Insufficient permissions', 'admark-crm' ) ); } $api_key_present = ( wats_get_api_key() !== '' ); $templates = $api_key_present ? get_transient( 'wats_templates_cache' ) : array(); if ( $templates === false && $api_key_present ) { $templates = wats_fetch_templates(); } if ( ! $api_key_present ) { delete_transient( 'wats_templates_cache' ); $templates = array(); } if ( ! is_array( $templates ) ) { $templates = array(); } $selected = wats_get_selected_template(); $total_sent = (int) get_option( 'wats_send_count', 0 ); $today_iso = current_time( 'Y-m-d' ); $first_date = ''; $log = get_option( 'wats_send_log', array() ); if ( ! empty( $log ) ) { $min_ts = PHP_INT_MAX; $tz = wp_timezone(); foreach ( $log as $entry ) { if ( is_array( $entry ) && isset( $entry['utc'] ) ) { $min_ts = min( $min_ts, (int) $entry['utc'] ); } else { $dt = date_create_immutable( (string) $entry, $tz ); if ( $dt ) { $min_ts = min( $min_ts, $dt->getTimestamp() - (int) $tz->getOffset( $dt ) ); } } } if ( $min_ts !== PHP_INT_MAX ) { $first_date = wp_date( 'Y-m-d', $min_ts, $tz ); } } $start_date = isset( $_POST['wats_from'] ) ? sanitize_text_field( $_POST['wats_from'] ) : ( $first_date ?: $today_iso ); $end_date = isset( $_POST['wats_to'] ) ? sanitize_text_field( $_POST['wats_to'] ) : $today_iso; if ( $start_date > $today_iso ) { $start_date = $today_iso; } if ( $end_date > $today_iso ) { $end_date = $today_iso; } if ( $end_date < $start_date ) { $end_date = $start_date; } $range_count = wats_count_between( $start_date, $end_date ); ?>
Templates are cached for 10 minutes. Click to force reload from the Admark API.
Please configure your API Key and Phone Number ID in Settings first.
These are sample messages for reference. Create matching templates in your Admark Dashboard using these formats, then assign them in the Automation tab.