accordion plus FAQPage JSON-LD), so search engines * and AI crawlers that don't run JavaScript can read them. The answers are * written once per page in Agentmatica and kept stable, so the result is * cached for 12 hours. The markup matches the Shopify theme block, and the * data-agentmatica-faq-rendered flag tells the chat widget to leave it alone. * * When the request fails, nothing is printed. When the page has no FAQs yet, * an empty placeholder is printed so the chat widget (if it is on the page) * can ask for them. * * @package Agentmatica */ declare(strict_types=1); if ( ! defined( 'ABSPATH' ) ) { exit; } final class Agentmatica_Product_Faqs { public const SHORTCODE = 'agentmatica_faq'; public const AGENT_ID_OPTION = 'agentmatica_faq_agent_id'; public const WOO_PRODUCT_OPTION = 'agentmatica_faq_woo_product_page'; public const TRANSIENT_PREFIX = 'agentmatica_faq_'; private const SESSION_PREFIX = 'agentmatica_faq_wgt_'; private const TIMEOUT_SECONDS = 5; private const CACHE_TTL = 12 * HOUR_IN_SECONDS; private const PENDING_TTL = 10 * MINUTE_IN_SECONDS; private const ERROR_TTL = 5 * MINUTE_IN_SECONDS; private const SESSION_TTL = 50 * MINUTE_IN_SECONDS; private const MAX_ITEMS = 20; /** @var bool */ private static $printed_styles = false; public static function init(): void { add_shortcode( self::SHORTCODE, array( __CLASS__, 'render_shortcode' ) ); if ( self::woo_product_page_enabled() ) { // Tabs print at priority 10, upsells at 15: FAQs go between them. add_action( 'woocommerce_after_single_product_summary', array( __CLASS__, 'print_on_product_page' ), 12 ); } } public static function get_agent_id(): string { $value = strtolower( trim( (string) get_option( self::AGENT_ID_OPTION, '' ) ) ); return Agentmatica_Starter_Questions::is_uuid( $value ) ? $value : ''; } public static function woo_product_page_enabled(): bool { return '1' === (string) get_option( self::WOO_PRODUCT_OPTION, '0' ); } /** * Save the admin settings. An invalid agent ID is stored as empty. */ public static function save_settings( string $agent_id, bool $woo_product_page ): bool { $agent_id = strtolower( trim( $agent_id ) ); $valid = '' === $agent_id || Agentmatica_Starter_Questions::is_uuid( $agent_id ); update_option( self::AGENT_ID_OPTION, $valid ? $agent_id : '', false ); update_option( self::WOO_PRODUCT_OPTION, $woo_product_page ? '1' : '0', true ); return $valid; } public static function print_on_product_page(): void { echo self::render( self::get_agent_id(), self::current_page_url(), '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render() escapes every value. } /** * @param array|string $atts Shortcode attributes. */ public static function render_shortcode( $atts ): string { $atts = shortcode_atts( array( 'agent' => '', 'url' => '', 'heading' => '', ), is_array( $atts ) ? $atts : array(), self::SHORTCODE ); $agent_id = strtolower( trim( (string) $atts['agent'] ) ); if ( '' === $agent_id ) { $agent_id = self::get_agent_id(); } if ( ! Agentmatica_Starter_Questions::is_uuid( $agent_id ) ) { if ( current_user_can( 'edit_posts' ) ) { return '

' . esc_html__( 'Agentmatica FAQs: add your agent ID under Settings → Agentmatica, or use [agentmatica_faq agent="..."].', 'agentmatica-mcp-connector' ) . '

'; } return ''; } $url = trim( (string) $atts['url'] ); $url = '' !== $url ? esc_url_raw( $url, array( 'http', 'https' ) ) : self::current_page_url(); return self::render( $agent_id, $url, sanitize_text_field( (string) $atts['heading'] ) ); } /** * Build the FAQ block for one page. Returns '' when it can't be shown. */ public static function render( string $agent_id, string $url, string $heading_override ): string { if ( ! Agentmatica_Starter_Questions::is_uuid( $agent_id ) || '' === $url ) { return ''; } $data = self::get_faqs( $agent_id, $url ); if ( null === $data ) { return ''; } $heading = '' !== $heading_override ? $heading_override : $data['heading']; if ( '' === $heading ) { $heading = __( 'Questions and answers', 'agentmatica-mcp-connector' ); } if ( array() === $data['faqs'] ) { // Not written yet: the chat widget renders and requests them. return '
'; } $items = ''; $ld = array(); foreach ( $data['faqs'] as $faq ) { $items .= '
' . '' . esc_html( $faq['question'] ) . '' . '

' . esc_html( $faq['answer'] ) . '

' . '
'; $ld[] = array( '@type' => 'Question', 'name' => $faq['question'], 'acceptedAnswer' => array( '@type' => 'Answer', 'text' => $faq['answer'], ), ); } // JSON_HEX_TAG keeps "" in an answer from closing the tag. $json_ld = wp_json_encode( array( '@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => $ld, ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); $html = '
'; $html .= '

' . esc_html( $heading ) . '

'; $follow_up = ! empty( $data['follow_up'] ) ? ' data-agentmatica-faq-follow-up-on="true"' : ''; $html .= '
' . $items . '
'; if ( is_string( $json_ld ) ) { $html .= ''; } $html .= '
'; return self::styles() . $html; } /** * FAQs for one page, from the cache or Agentmatica. * * @return array{heading: string, faqs: list}|null */ public static function get_faqs( string $agent_id, string $url ): ?array { $key = self::TRANSIENT_PREFIX . md5( $agent_id . '|' . $url ); $cached = get_transient( $key ); if ( is_array( $cached ) ) { return isset( $cached['error'] ) ? null : $cached; } $data = self::fetch( $agent_id, $url ); if ( null === $data ) { // Short negative cache, so a broken setup doesn't add a timeout to every page view. set_transient( $key, array( 'error' => true ), self::ERROR_TTL ); return null; } set_transient( $key, $data, array() === $data['faqs'] ? self::PENDING_TTL : self::CACHE_TTL ); return $data; } /** * @return array{heading: string, faqs: list}|null */ private static function fetch( string $agent_id, string $url ): ?array { $token = self::get_session_token( $agent_id, false ); if ( '' === $token ) { return null; } $response = self::request_faqs( $agent_id, $url, $token ); if ( ! is_wp_error( $response ) && 401 === wp_remote_retrieve_response_code( $response ) ) { // Token expired or the signing secret rotated: get a new one once. $token = self::get_session_token( $agent_id, true ); if ( '' === $token ) { return null; } $response = self::request_faqs( $agent_id, $url, $token ); } if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { return null; } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $body ) ) { return null; } $faqs = array(); foreach ( is_array( $body['faqs'] ?? null ) ? $body['faqs'] : array() as $item ) { if ( ! is_array( $item ) ) { continue; } $question = trim( is_string( $item['question'] ?? null ) ? $item['question'] : '' ); $answer = trim( is_string( $item['answer'] ?? null ) ? $item['answer'] : '' ); if ( '' === $question || '' === $answer ) { continue; } $faqs[] = array( 'question' => $question, 'answer' => $answer, ); if ( count( $faqs ) >= self::MAX_ITEMS ) { break; } } return array( 'heading' => trim( is_string( $body['heading'] ?? null ) ? $body['heading'] : '' ), 'faqs' => $faqs, // "Ask a follow-up" links, added by the chat widget when this is on. 'follow_up' => true === ( $body['followUp'] ?? false ), ); } /** * @return array|WP_Error */ private static function request_faqs( string $agent_id, string $url, string $token ) { $endpoint = add_query_arg( array( 'botId' => rawurlencode( $agent_id ), 'url' => rawurlencode( $url ), 'for' => 'faq', ), self::platform_url() . '/api/widget/product-qa' ); return wp_remote_get( $endpoint, array( 'timeout' => self::TIMEOUT_SECONDS, 'redirection' => 0, 'headers' => array( 'Authorization' => 'Bearer ' . $token, 'Accept' => 'application/json', ), ) ); } /** * A widget session token, the same one the chat widget gets. Agentmatica * checks the Origin against the agent's website and allowed embed domains. */ private static function get_session_token( string $agent_id, bool $refresh ): string { $key = self::SESSION_PREFIX . md5( $agent_id ); if ( ! $refresh ) { $cached = get_transient( $key ); if ( is_string( $cached ) && '' !== $cached ) { return $cached; } } $origin = self::site_origin(); $response = wp_remote_post( self::platform_url() . '/api/widget/session', array( 'timeout' => self::TIMEOUT_SECONDS, 'redirection' => 0, 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Origin' => $origin, 'Referer' => $origin . '/', ), 'body' => (string) wp_json_encode( array( 'botId' => $agent_id ) ), ) ); if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { delete_transient( $key ); return ''; } $body = json_decode( wp_remote_retrieve_body( $response ), true ); $token = is_array( $body ) && is_string( $body['token'] ?? null ) ? $body['token'] : ''; if ( 0 !== strpos( $token, 'amk_wgt_' ) ) { return ''; } // Tokens last an hour; keep a margin. set_transient( $key, $token, self::SESSION_TTL ); return $token; } private static function platform_url(): string { return Agentmatica_Order_Attribution::resolve_platform_api_url(); } private static function site_origin(): string { $parts = wp_parse_url( home_url() ); if ( ! is_array( $parts ) || empty( $parts['host'] ) ) { return ''; } $origin = ( $parts['scheme'] ?? 'https' ) . '://' . $parts['host']; if ( ! empty( $parts['port'] ) ) { $origin .= ':' . $parts['port']; } return $origin; } /** * The URL Agentmatica crawled for this page: the permalink on single * posts, pages and products, otherwise the request path without a query. */ public static function current_page_url(): string { if ( is_singular() ) { $permalink = get_permalink( get_queried_object_id() ); if ( is_string( $permalink ) && '' !== $permalink ) { return $permalink; } } global $wp; $path = isset( $wp->request ) ? (string) $wp->request : ''; return home_url( '' === $path ? '/' : user_trailingslashit( $path ) ); } private static function styles(): string { if ( self::$printed_styles ) { return ''; } self::$printed_styles = true; return ''; } }