10, 'sslverify' => true, 'body' => [ 'site_callback' => $site_callback, 'nonce' => $token, ], ] ); if ( is_wp_error( $start ) || 200 !== wp_remote_retrieve_response_code( $start ) ) { $detail = is_wp_error( $start ) ? $start->get_error_message() : 'HTTP ' . wp_remote_retrieve_response_code( $start ) . ' - ' . wp_remote_retrieve_body( $start ); wp_redirect( add_query_arg( [ 'ga4_error' => 'broker_unreachable', 'ga4_detail' => rawurlencode( $detail ) ], admin_url( 'admin.php?page=awbseo-settings' ) ) ); exit; } $state = json_decode( wp_remote_retrieve_body( $start ), true )['state'] ?? ''; if ( ! $state ) { wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_error=broker_error' ) ); exit; } $oauth_url = add_query_arg( [ 'client_id' => AWBSEO_GSC_CLIENT_ID, // same Google app as GSC 'redirect_uri' => AWBSEO_OAUTH_BROKER . '/callback', 'response_type' => 'code', 'scope' => 'https://www.googleapis.com/auth/analytics.readonly', 'access_type' => 'offline', 'prompt' => 'consent', 'state' => $state, ], self::OAUTH_ENDPOINT ); wp_redirect( $oauth_url ); exit; } /** * Called by AWBSEO_GSC::handle_callback() when it detects the transient * value is 'ga4' (meaning this is a GA4 connect flow, not a GSC one). * The nonce has already been verified and deleted by the GSC handler. */ public static function store_tokens_from_gsc_callback() { if ( ! empty( $_POST['error'] ) ) { $err = sanitize_text_field( $_POST['error'] ); wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_error=' . rawurlencode( $err ) ) ); exit; } $tokens = [ 'access_token' => sanitize_text_field( $_POST['access_token'] ?? '' ), 'refresh_token' => sanitize_text_field( $_POST['refresh_token'] ?? '' ), 'expires_at' => time() + (int) ( $_POST['expires_in'] ?? 3600 ), ]; if ( ! $tokens['access_token'] ) { wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_error=no_token' ) ); exit; } update_option( self::OPTION_TOKENS, $tokens, false ); self::flush_transients(); // Auto-detect property after connecting. $property = self::detect_property(); if ( $property ) { update_option( self::OPTION_PROPERTY, $property ); } wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_connected=1' ) ); exit; } public static function handle_disconnect() { check_admin_referer( 'awbseo_ga4_disconnect' ); if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Forbidden' ); delete_option( self::OPTION_TOKENS ); delete_option( self::OPTION_PROPERTY ); self::flush_transients(); wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_disconnected=1' ) ); exit; } public static function handle_detect_property() { check_admin_referer( 'awbseo_ga4_detect_property' ); if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Forbidden' ); $property = self::detect_property(); if ( $property ) { update_option( self::OPTION_PROPERTY, $property ); wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_detected=1' ) ); } else { wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_error=no_property_found' ) ); } exit; } /** * Saves a manually selected GA4 property from the settings dropdown. */ public static function handle_set_property() { check_admin_referer( 'awbseo_ga4_set_property' ); if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Forbidden' ); $property = sanitize_text_field( $_POST['ga4_property'] ?? '' ); // Normalize: accept bare numeric ID (e.g. "123456789") or full form. if ( $property && ! str_starts_with( $property, 'properties/' ) ) { $property = 'properties/' . $property; } if ( $property && $property !== 'properties/' ) { update_option( self::OPTION_PROPERTY, $property ); self::flush_transients(); wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_detected=1' ) ); } else { wp_redirect( admin_url( 'admin.php?page=awbseo-settings&ga4_error=no_property_found' ) ); } exit; } // ── Token Management ────────────────────────────────────────────────────── public function is_connected() { $tokens = get_option( self::OPTION_TOKENS, [] ); if ( empty( $tokens['access_token'] ) ) return false; // Token is still within its validity window — definitely connected. if ( ! empty( $tokens['expires_at'] ) && time() < $tokens['expires_at'] - 60 ) { return true; } // Token is expired. If we have a refresh token, get_access_token() can // renew it on demand — report connected so the caller can attempt a refresh. if ( ! empty( $tokens['refresh_token'] ) ) { return true; } // Expired with no refresh token — permanently unusable. Clear it so the // Settings page shows the Connect button instead of an unresolvable error. delete_option( self::OPTION_TOKENS ); return false; } public function get_property() { return get_option( self::OPTION_PROPERTY, '' ); } /** * Returns a valid access token, refreshing if expired. * Mirrors the same pattern as AWBSEO_GSC::get_access_token(). */ public function get_access_token() { $tokens = get_option( self::OPTION_TOKENS, [] ); if ( empty( $tokens['access_token'] ) ) return null; if ( ! empty( $tokens['expires_at'] ) && time() < $tokens['expires_at'] - 60 ) { return $tokens['access_token']; } if ( empty( $tokens['refresh_token'] ) ) return null; // Don't hammer the broker if a recent refresh attempt failed transiently. // The backoff transient is cleared automatically by flush_transients() // whenever the user successfully reconnects. if ( get_transient( 'awbseo_ga4_refresh_backoff' ) ) { return null; } $response = wp_remote_post( AWBSEO_OAUTH_BROKER . '/refresh', [ 'timeout' => 10, 'sslverify' => true, 'body' => [ 'refresh_token' => $tokens['refresh_token'] ], ] ); if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { // Transient failure (network error, broker down). Throttle retries // and fall back to the stored access token — it may still be // accepted by Google for a short window, and if not, Google's own // 401 gives the user a clearer error than "no token on file". set_transient( 'awbseo_ga4_refresh_backoff', 1, 15 * MINUTE_IN_SECONDS ); return $tokens['access_token']; } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( empty( $body['access_token'] ) ) { set_transient( 'awbseo_ga4_refresh_backoff', 1, 15 * MINUTE_IN_SECONDS ); return $tokens['access_token']; // same fallback } $tokens['access_token'] = $body['access_token']; $tokens['expires_at'] = time() + (int) ( $body['expires_in'] ?? 3600 ); update_option( self::OPTION_TOKENS, $tokens, false ); return $tokens['access_token']; } public static function flush_transients() { global $wpdb; $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_awbseo\_ga4\_%' OR option_name LIKE '\_transient\_timeout\_awbseo\_ga4\_%'" ); } // ── Property Detection ──────────────────────────────────────────────────── /** Stores the last error from list_properties() for display in the UI. */ private static $list_error = ''; /** Stores the last error from run_report() / get_sessions_by_source(). */ private static $data_error = ''; public static function get_list_error() { return self::$list_error; } public static function get_data_error() { return self::$data_error; } /** * Lists all GA4 properties the connected account has access to. * Returns array of [ 'id' => 'properties/123', 'name' => 'My Site (123)' ]. * On failure stores a human-readable error in self::$list_error. */ public function list_properties() { self::$list_error = ''; $token = $this->get_access_token(); if ( ! $token ) { self::$list_error = 'No valid access token — try reconnecting GA4.'; return []; } $response = wp_remote_get( self::ADMIN_API_BASE . 'accountSummaries?pageSize=200', [ 'headers' => [ 'Authorization' => 'Bearer ' . $token ], 'timeout' => 15 ] ); if ( is_wp_error( $response ) ) { self::$list_error = 'API request failed: ' . $response->get_error_message(); return []; } $code = wp_remote_retrieve_response_code( $response ); $raw = wp_remote_retrieve_body( $response ); if ( 200 !== $code ) { $decoded = json_decode( $raw, true ); self::$list_error = $decoded['error']['message'] ?? ( 'GA4 Admin API returned HTTP ' . $code . '. ' . 'Make sure the Google Analytics Admin API is enabled in your Google Cloud project for client ID ' . AWBSEO_GSC_CLIENT_ID . '.' ); return []; } $body = json_decode( $raw, true ); $properties = []; foreach ( $body['accountSummaries'] ?? [] as $account ) { foreach ( $account['propertySummaries'] ?? [] as $prop ) { $id = $prop['property'] ?? ''; // e.g. "properties/123456789" $name = $prop['displayName'] ?? $id; if ( $id ) { $properties[] = [ 'id' => $id, 'name' => $name . ' (' . str_replace( 'properties/', '', $id ) . ')', ]; } } } if ( empty( $properties ) && empty( $body['accountSummaries'] ) ) { self::$list_error = 'No GA4 properties found. This Google account may not have any GA4 properties, or the Analytics Admin API may not be enabled in your Google Cloud project.'; } return $properties; } /** * Auto-detects the GA4 property matching this site's URL. * Falls back to the first property if URL matching finds nothing. */ public static function detect_property() { $instance = self::get_instance(); $properties = $instance->list_properties(); if ( empty( $properties ) ) return ''; $site_host = strtolower( parse_url( home_url(), PHP_URL_HOST ) ); foreach ( $properties as $prop ) { // GA4 property display names often contain the domain. $prop_lower = strtolower( $prop['name'] ); if ( strpos( $prop_lower, $site_host ) !== false ) { return $prop['id']; } } // Return the first property as a best-effort fallback. return $properties[0]['id'] ?? ''; } // ── Data API ────────────────────────────────────────────────────────────── /** * Runs a GA4 Data API report for the given property. * $dimensions: [ 'sessionSource', 'sessionMedium' ] etc. * $metrics: [ 'sessions', 'totalUsers' ] etc. */ public function run_report( $property_id, array $dimensions, array $metrics, $days = 30 ) { self::$data_error = ''; $token = $this->get_access_token(); if ( ! $token ) { self::$data_error = 'No valid access token — reconnect GA4 in Settings.'; return null; } if ( ! $property_id ) { self::$data_error = 'No GA4 property selected — save a property in Settings.'; return null; } // Strip "properties/" prefix if already included — DATA_API_BASE ends with "properties/". $prop_numeric = str_replace( 'properties/', '', $property_id ); $url = self::DATA_API_BASE . $prop_numeric . ':runReport'; $payload = [ 'dateRanges' => [ [ 'startDate' => $days . 'daysAgo', 'endDate' => 'today' ] ], 'dimensions' => array_map( fn( $d ) => [ 'name' => $d ], $dimensions ), 'metrics' => array_map( fn( $m ) => [ 'name' => $m ], $metrics ), 'limit' => 50, 'orderBys' => [ [ 'metric' => [ 'metricName' => $metrics[0] ], 'desc' => true ] ], ]; $response = wp_remote_post( $url, [ 'timeout' => 20, 'headers' => [ 'Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', ], 'body' => wp_json_encode( $payload ), ] ); if ( is_wp_error( $response ) ) { self::$data_error = 'GA4 Data API request failed: ' . $response->get_error_message(); return null; } $code = wp_remote_retrieve_response_code( $response ); $raw = wp_remote_retrieve_body( $response ); if ( 200 !== $code ) { $decoded = json_decode( $raw, true ); self::$data_error = $decoded['error']['message'] ?? ( 'GA4 Data API returned HTTP ' . $code . ': ' . wp_strip_all_tags( $raw ) ); return null; } return json_decode( $raw, true ); } /** * Returns sessions grouped by source/medium, sorted by sessions desc. * Each row: [ 'source' => string, 'medium' => string, 'sessions' => int ] */ public function get_sessions_by_source( $days = 30 ) { $property = $this->get_property(); if ( ! $property ) return []; $cache_key = 'awbseo_ga4_src_' . md5( $property . $days ); $cached = get_transient( $cache_key ); if ( $cached ) return $cached; $report = $this->run_report( $property, [ 'sessionSource', 'sessionMedium' ], [ 'sessions' ], $days ); if ( empty( $report['rows'] ) ) return []; $rows = array_map( function ( $row ) { return [ 'source' => $row['dimensionValues'][0]['value'] ?? '', 'medium' => $row['dimensionValues'][1]['value'] ?? '', 'sessions' => (int) ( $row['metricValues'][0]['value'] ?? 0 ), ]; }, $report['rows'] ); set_transient( $cache_key, $rows, HOUR_IN_SECONDS ); return $rows; } /** * Returns sessions from known AI engine sources specifically. * Uses get_sessions_by_source() and filters by domain match against * the same engine domain list used by the Referer tracker. * * Returns: [ 'ChatGPT' => 42, 'Perplexity' => 18, ... ] sorted desc. */ public function get_ai_sessions( $days = 30 ) { $all_rows = $this->get_sessions_by_source( $days ); if ( empty( $all_rows ) ) return []; // Source domain → engine name (GA4 strips subdomain from source). $engine_map = [ 'chatgpt.com' => 'ChatGPT', 'chat.openai.com' => 'ChatGPT', 'openai.com' => 'ChatGPT', 'perplexity.ai' => 'Perplexity', 'gemini.google.com' => 'Google Gemini', 'aistudio.google.com' => 'Google Gemini', 'copilot.microsoft.com' => 'Microsoft Copilot', 'bing.com' => 'Microsoft Copilot', 'claude.ai' => 'Claude (Anthropic)', 'you.com' => 'You.com', 'meta.ai' => 'Meta AI', 'grok.com' => 'Grok (xAI)', 'x.com' => 'Grok (xAI)', 'kagi.com' => 'Kagi', 'phind.com' => 'Phind', 'poe.com' => 'Poe', ]; $totals = []; foreach ( $all_rows as $row ) { $src = strtolower( trim( $row['source'] ) ); // GA4 often strips subdomain (reports "openai.com" for chat.openai.com). foreach ( $engine_map as $domain => $engine ) { if ( $src === $domain || str_ends_with( $src, '.' . $domain ) ) { $totals[ $engine ] = ( $totals[ $engine ] ?? 0 ) + $row['sessions']; break; } } } arsort( $totals ); return $totals; } /** * Total sessions from AI engines for the period. */ public function get_ai_total( $days = 30 ) { return array_sum( $this->get_ai_sessions( $days ) ); } }