Files
google-ads-ver-2/scripts/reports/test_ga4_access.py
2026-05-15 09:28:11 +02:00

41 lines
1.3 KiB
Python

"""Quick test: check if OAuth credentials can access GA4 property."""
import os
from dotenv import load_dotenv
from google.oauth2.credentials import Credentials
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import RunReportRequest, DateRange, Metric
load_dotenv()
PROPERTY_ID = os.getenv("GA4_PROPERTY_ID_studio-zoe.pl")
CLIENT_ID = os.getenv("GOOGLE_ADS_OAUTH2_CLIENT_ID")
CLIENT_SECRET = os.getenv("GOOGLE_ADS_OAUTH2_CLIENT_SECRET")
REFRESH_TOKEN = os.getenv("GA4_REFRESH_TOKEN")
print(f"GA4 Property ID: {PROPERTY_ID}")
credentials = Credentials(
token=None,
refresh_token=REFRESH_TOKEN,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
token_uri="https://oauth2.googleapis.com/token",
)
client = BetaAnalyticsDataClient(credentials=credentials)
try:
request = RunReportRequest(
property=f"properties/{PROPERTY_ID}",
date_ranges=[DateRange(start_date="2026-02-01", end_date="2026-02-28")],
metrics=[Metric(name="sessions"), Metric(name="totalUsers")],
)
response = client.run_report(request)
for row in response.rows:
print(f"Sessions: {row.metric_values[0].value}, Users: {row.metric_values[1].value}")
print("\nGA4 access works!")
except Exception as e:
print(f"\nGA4 access failed: {e}")