setApplicationName("Hello Analytics Reporting"); $client->setAuthConfig($KEY_FILE_LOCATION); $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); $analytics = new Google_Service_AnalyticsReporting($client); return $analytics; } function getReport($analytics, $start_date, $end_date) { // Replace with your view ID, for example XXXX. $VIEW_ID = "436681896"; // Create the DateRange object. $dateRange = new Google_Service_AnalyticsReporting_DateRange(); $dateRange->setStartDate("start_date"); $dateRange->setEndDate("end_date"); // Create the Metrics object. $sessions = new Google_Service_AnalyticsReporting_Metric(); $sessions->setExpression("ga:sessions"); $sessions->setAlias("sessions"); // Create the Metrics object. $users = new Google_Service_AnalyticsReporting_Metric(); $users->setExpression("ga:users"); $users->setAlias("users"); // Create the Metrics object. $organicSearches = new Google_Service_AnalyticsReporting_Metric(); $organicSearches->setExpression("ga:organicSearches"); $organicSearches->setAlias("organicSearches"); // Create the Metrics object. $avgPageLoadTime = new Google_Service_AnalyticsReporting_Metric(); $avgPageLoadTime->setExpression("ga:avgPageLoadTime"); $avgPageLoadTime->setAlias("avgPageLoadTime"); // Create the ReportRequest object. $request = new Google_Service_AnalyticsReporting_ReportRequest(); $request->setViewId($VIEW_ID); $request->setDateRanges($dateRange); $request->setMetrics(array($sessions,$users,$organicSearches,$avgPageLoadTime)); $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); $body->setReportRequests( array( $request) ); return $analytics->reports->batchGet( $body ); } // function getLatestData($data){ // $analytics = initializeAnalytics(); // $i = 0; // for($j = 6;$j>0; $j--){ // $start_date = date('Y-m',strtotime("-$j month")) . '-01'; // $d = new DateTime($start_date); // $end_date = $d->format('Y-m-t'); // } // } $analytics = initializeAnalytics(); $result = getReport($analytics, '2024-01-01','2024-05-01'); print_r($result); /* // Report all PHP errors putenv("GOOGLE_APPLICATION_CREDENTIALS=" . __DIR__ . '/key.json'); error_reporting(E_ALL); ini_set('display_errors', '1'); require_once __DIR__ . '/vendor/autoload.php'; use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\DateRange; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; function google_analytics_report_shortcode($atts) { // Extract shortcode attributes $atts = shortcode_atts(array( 'property_id' => '436681896' ), $atts); // Initialize BetaAnalyticsDataClient $client = new BetaAnalyticsDataClient(); // Make an API call. $response = $client->runReport([ 'property' => 'properties/' . $atts['property_id'], 'dateRanges' => [ new DateRange([ 'start_date' => '2023-03-31', 'end_date' => 'today', ]), ], 'dimensions' => [ new Dimension(['name' => 'city']), ], 'metrics' => [ new Metric(['name' => 'activeUsers']), ] ]); // Prepare output $output = '
GA4 Data will be displayed here.
'; } get("https://analyticsreporting.googleapis.com/v4/reports:batchGet?key=$apiKey", [ 'json' => [ 'reportRequests' => [ 'viewId' => $propertyId, // Add your report request configuration here ] ] ]); // Decode response $data = json_decode($response->getBody(), true); // Process and display data (for demonstration purposes) // You need to implement your own logic to process the data return '' . print_r($data, true) . ''; } /* get("https://analyticsreporting.googleapis.com/v4/reports:batchGet?key=$apiKey", [ 'json' => [ 'reportRequests' => [ 'viewId' => $propertyId, // Add your report request configuration here ] ] ]); // Decode response $data = json_decode($response->getBody(), true); // Process and display data (for demonstration purposes) // You need to implement your own logic to process the data return '
' . print_r($data, true) . ''; } */ /* Plugin Name: GA4 Connector Description: Connects to Google Analytics 4 (GA4) using shortcode. Version: 1.0 Author: Your Name // Include Composer autoloader require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php'; // Add shortcode to fetch GA4 data add_shortcode('ga4_data', 'fetch_ga4_data'); function fetch_ga4_data() { // Set your Google Analytics property ID $propertyId = '436681896'; // Set your API key $apiKey = 'AIzaSyDb0wOoHZt55ONwBKXhVI76n-6u8yGq5tw'; // Initialize GuzzleHttp Client $client = new GuzzleHttp\Client(); try { // Make request to Google Analytics Data API $response = $client->post("https://analyticsreporting.googleapis.com/v4/reports:batchGet?key=$apiKey", [ 'json' => [ 'reportRequests' => [ [ 'viewId' => $propertyId, 'dateRanges' => [ 'startDate' => '7daysAgo', 'endDate' => 'today' ], 'metrics' => [ ['expression' => 'ga:sessions'] ] // Add any other report request configurations as needed ] ] ] ]); // Decode response $data = json_decode($response->getBody(), true); // Process and display data (for demonstration purposes) // You need to implement your own logic to process the data return '
' . print_r($data, true) . ''; } catch (Exception $e) { return 'Error fetching GA4 data: ' . $e->getMessage(); } } // Add shortcode to fetch GA4 data add_shortcode('ga4_data', 'fetch_ga4_data'); POST https://analyticsdata.googleapis.com/v1beta/properties/436681896:runRealtimeReport { "dimensions": [{ "name": "country" }], "metrics": [{ "name": "activeUsers" }] } */ /* Plugin Name: GA4 Analytics Plugin Description: Fetch GA4 data and display it using a shortcode. Version: 1.0 Author: Your Name // Add shortcode to fetch GA4 data add_shortcode('ga4_data', 'fetch_ga4_data'); function fetch_ga4_data() { // Include the Firebase JWT library require_once plugin_dir_path(__FILE__) . 'JWT.php'; // Load the JSON file containing the service account credentials $key_file = plugin_dir_path(__FILE__) . 'key.json'; $key_data = file_get_contents($key_file); // Check if the file was loaded successfully if ($key_data === false) { return "Error loading service account credentials file."; } // Decode the JSON data $key_json = json_decode($key_data, true); // Check if JSON decoding was successful if (json_last_error() !== JSON_ERROR_NONE) { return "Error decoding service account credentials: " . json_last_error_msg(); } // Extract the required fields from the JSON data $private_key = $key_json['private_key']; $client_email = $key_json['client_email']; // Prepare the JWT payload $jwt_payload = array( 'iss' => $client_email, 'aud' => 'https://analyticsdata.googleapis.com/', 'exp' => time() + 3600, // Token expiration time (1 hour from now) 'iat' => time(), // Token issuance time ); // Create the JWT $jwt = \Firebase\JWT\JWT::encode($jwt_payload, $private_key, 'RS256'); // Define the Google Analytics API endpoint $endpoint = 'https://analyticsdata.googleapis.com/v1beta/properties/436681896:runRealtimeReport'; // Define request body $request_body = json_encode(array( "dimensions" => array(array("name" => "country")), "metrics" => array(array("name" => "activeUsers")) )); // Make the request using WordPress HTTP API $response = wp_remote_post($endpoint, array( 'body' => $request_body, 'headers' => array( 'Authorization' => 'Bearer ' . $jwt, 'Content-Type' => 'application/json', ), )); // Check if the request was successful if (is_wp_error($response)) { return "Error fetching data: " . $response->get_error_message(); } else { $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Process and display the data as needed // For example, you could return a formatted output $output = "
" . print_r($data, true) . ""; return $output; } } function run_analytics_report() { require 'vendor/autoload.php'; use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\DateRange; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\RunReportRequest; function sample_run_report($property_id = "YOUR-GA4-PROPERTY-ID") { // Make changes here $property_id = "436681896"; $client = new BetaAnalyticsDataClient(); $request = new RunReportRequest([ 'property' => "properties/{$property_id}", 'metrics' => [new Metric(['name' => 'totalUsers'])], // Fetch the conversion metric 'dateRanges' => [new DateRange(['startDate' => '2024-01-01', 'endDate' => 'yesterday'])], ]); $response = $client->runReport($request); $total_conversions = 0; foreach ($response->getRows() as $row) { $total_conversions += intval($row->getMetricValues()[0]->getValue()); } echo "Total Conversions (yesterday): " . $total_conversions . PHP_EOL; } if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'])) { sample_run_report(); } add_shortcode('ga4_data', 'analytics_report_shortcode'); // Add shortcode to fetch GA4 data add_shortcode('ga4_data', 'run_analytics_report'); function run_analytics_report() { require 'vendor/autoload.php'; $service_account_key_file_path = "/var/www/html/sigeita/wp-content/plugins/sige-analytics/key.json"; use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; try { // Authenticate using a keyfile path $client = new BetaAnalyticsDataClient([ 'credentials' => $service_account_key_file_path ]); // CHANGE THIS $ga4_property = '436681896'; // Set the date range for the last 90 days. $start_date = date('Y-m-d', strtotime('-90 days')); $end_date = date('Y-m-d'); $date_range = new \Google\Analytics\Data\V1beta\DateRange(['start_date' => $start_date, 'end_date' => $end_date]); $date_ranges = [$date_range]; // Set the dimensions and metrics for the request. $dimensions = [new \Google\Analytics\Data\V1beta\Dimension(['name' => 'pagePath'])]; $metrics = [ new \Google\Analytics\Data\V1beta\Metric(['name' => 'activeUsers']), ]; $response = $client->runReport([ 'property' => 'properties/' . $ga4_property, 'dateRanges' => $date_ranges, 'dimensions' => $dimensions, 'metrics' => $metrics, ]); foreach ($response->getRows() as $row) { foreach ($row->getDimensionValues() as $dimensionValue) { print 'Dimension Value: ' . $dimensionValue->getValue() . PHP_EOL; } foreach ($row->getMetricValues() as $metricValue) { print 'Metric Value: ' . $metricValue->getValue() . PHP_EOL; } } } catch (\Google\ApiCore\ValidationException $e) { printf($e); } } */ /* Plugin Name: Google Analytics Report Shortcode Description: Adds a shortcode to display Google Analytics data. // Define shortcode handler function function google_analytics_report_shortcode() { putenv("GOOGLE_APPLICATION_CREDENTIALS=" . __DIR__ . '/key.json'); require 'vendor/autoload.php'; use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; $client = new BetaAnalyticsDataClient(); $response = $client->runReport([ 'property' => 'properties/[436681896]' ]); $output = ''; foreach ($response->getRows() as $row) { foreach ($row->getDimensionValues() as $dimensionValue) { $output .= 'Dimension Value: ' . $dimensionValue->getValue() . '