PHP网站如何通过Google Analytics API按会话ID获取会话数据?
Alright, let's walk through this step by step—since you already have Google Developer Console basics down, this should slot right into your existing setup.
Step 1: Capture & Save GA Session ID with Orders
First, you need to grab the GA session ID from the frontend, send it to your PHP backend, and store it with the order record.
Frontend: Fetch GA Session ID
If you're using GA4 (the current standard), use the gtag API to get the session ID. Add this code to your order page, and populate a hidden form field with the ID before submitting the order:
// Wait for GA to load, then get the session ID gtag('get', 'G-XXXXXX', 'session_id', (sessionId) => { // Replace G-XXXXXX with your GA4 measurement ID document.getElementById('ga_session_id').value = sessionId; });
Add a hidden input to your order form:
<input type="hidden" id="ga_session_id" name="ga_session_id">
Backend: Save ID to Database
When your PHP backend receives the order submission, capture the ga_session_id parameter and save it with the rest of the order data. Example:
// Assume you're using PDO for database connections $gaSessionId = $_POST['ga_session_id'] ?? null; // Insert order into your database (adjust table/columns to match your setup) $stmt = $pdo->prepare("INSERT INTO orders (order_num, total_amount, ga_session_id) VALUES (?, ?, ?)"); $stmt->execute([uniqid('ORD-'), $_POST['total'], $gaSessionId]);
Make sure your orders table has a ga_session_id column (varchar type, enough length to hold the GA session ID string).
Step 2: Fetch Session Data via Google Analytics Data API
To pull the session details (duration, device type, browser, etc.) using the saved session ID, you'll use the Google Analytics Data API v1 (for GA4). Here's how to implement this in PHP:
1. Prep API Credentials
Since you know your way around the Developer Console:
- Enable the Google Analytics Data API v1 for your project
- Create a service account (download the JSON key file)
- Add the service account email to your GA4 property's user list with "Viewer" permissions
2. Install Google Client Library
Use Composer to install the official PHP client:
composer require google/apiclient:^2.0
3. Write the Query Code
This script will take a saved GA session ID and fetch the corresponding session data:
require __DIR__ . '/vendor/autoload.php'; // Initialize Google Client $client = new Google\Client(); $client->setApplicationName('GA Session Data Lookup'); $client->setScopes([Google\Service\AnalyticsData::ANALYTICS_READONLY]); $client->setAuthConfig('path/to/your/service-account-key.json'); // Replace with your key path $client->setAccessType('offline'); // Create Analytics Data service instance $analyticsData = new Google\Service\AnalyticsData($client); // Your GA4 property ID (format: 2XXXXXXX) $propertyId = '212345678'; // Get the session ID from your orders database $targetSessionId = '123456789.1698765432'; // Build the report request $request = new Google\Service\AnalyticsData\RunReportRequest(); $request->setDateRanges([ new Google\Service\AnalyticsData\DateRange([ 'startDate' => '2024-01-01', // Use the order's creation date here to narrow results 'endDate' => 'today' ]) ]); // Define dimensions and metrics you want to fetch $request->setDimensions([ new Google\Service\AnalyticsData\Dimension(['name' => 'sessionId']), new Google\Service\AnalyticsData\Dimension(['name' => 'deviceCategory']), new Google\Service\AnalyticsData\Dimension(['name' => 'browser']) ]); $request->setMetrics([ new Google\Service\AnalyticsData\Metric(['name' => 'sessionDuration']), new Google\Service\AnalyticsData\Metric(['name' => 'sessions']) ]); // Filter to only the target session ID $request->setDimensionFilter( new Google\Service\AnalyticsData\FilterExpression([ 'filter' => new Google\Service\AnalyticsData\Filter([ 'fieldName' => 'sessionId', 'stringFilter' => new Google\Service\AnalyticsData\StringFilter([ 'matchType' => 'EXACT', 'value' => $targetSessionId ]) ]) ]) ); // Execute the query try { $response = $analyticsData->properties->runReport("properties/{$propertyId}", $request); // Parse and use the results foreach ($response->getRows() as $row) { $dims = $row->getDimensionValues(); $metrics = $row->getMetricValues(); echo "Session ID: {$dims[0]->getValue()}<br>"; echo "Device Type: {$dims[1]->getValue()}<br>"; echo "Browser: {$dims[2]->getValue()}<br>"; echo "Session Duration (seconds): {$metrics[0]->getValue()}<br>"; } } catch (Exception $e) { echo "Error fetching data: {$e->getMessage()}"; }
Key Notes
- GA4 Session ID Format: GA4 session IDs are strings like
123456789.1698765432—make sure you save and query them exactly as they are (case-sensitive). - Optimize Date Range: Instead of a broad date range, use the order's creation date as the start/end to reduce API load and speed up queries.
- API Quotas: The GA Data API has usage limits—cache results if you're looking up the same session multiple times to avoid hitting quotas.
If You're Still Using Universal Analytics (UA)
If you haven't migrated to GA4 yet, you can use the Google Analytics Reporting API v4 instead. The core flow is the same, but the dimension/metric names change (e.g., ga:sessionId for the session ID, ga:sessionDuration for duration). Keep in mind UA is being sunset, so migrating to GA4 is strongly recommended.
内容的提问来源于stack exchange,提问作者Pini

