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 ); /** * 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(); } /** * 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 ); ?>

Admark CRM

v2.0.0
Total Messages Sent
Active Default Template
Messages in Range
→

API Configuration

Template Cache

Templates cache cleared. Refreshing…

'; } wp_nonce_field( 'wats_refresh_templates_action' ); ?>

Templates are cached for 10 minutes. Click to force reload from the Admark API.

count] $var_opts = wats_get_variable_options(); // Events that support a configurable send delay $delay_events = array( 'welcome' => array( 'value' => 0, 'unit' => 'minutes', 'label' => 'Send delay after registration' ), 'add_to_cart' => array( 'value' => 20, 'unit' => 'minutes', 'label' => 'Send after' ), 'abandoned_cart' => array( 'value' => 3, 'unit' => 'hours', 'label' => 'Send after' ), 'feedback_request' => array( 'value' => 2, 'unit' => 'days', 'label' => 'Send after delivery' ), ); // Build saved maps for JS: { event_key: { slot: 'field_key' } } $saved_maps_js = array(); $saved_counts_js = array(); foreach ( $events as $ek => $ev ) { $saved_maps_js[ $ek ] = array(); $saved_counts_js[ $ek ] = (int) get_option( 'wats_varcount_' . $ek, 0 ); for ( $i = 1; $i <= 10; $i++ ) { $saved_maps_js[ $ek ][ $i ] = wats_get_var_map( $ek, $i ); } } ?>

Admark CRM

v

Please configure your API Key and Phone Number ID in Settings first.

Automation Flow

🌐 Visit
→
šŸ›’ Cart
→
ā° Abandoned
→
āœ… Order
→
šŸ’³ Payment
→
🚚 Dispatch
→
šŸ“¦ Delivered
→
⭐ Feedback
$event ) : $enabled = wats_get_event_enabled( $event_key ); $cur_tpl = wats_get_event_template( $event_key ); ?>

No templates loaded — add your API key in Settings to auto-fetch.

Admark CRM

v2.0.0

Sample Message Templates

These are sample messages for reference. Create matching templates in your Admark Dashboard using these formats, then assign them in the Automation tab.

$event ) : ?>