# Analytics API Automation – GTM and GA4 Admin

**Last Updated:** 2026-02-17

Scripts to configure GTM and GA4 via APIs instead of manual UI changes.

## Scripts

| Script | Purpose |
|--------|---------|
| `v2/scripts/dev-helpers/ga4-admin-key-events.php` | Mark events as GA4 key events (conversions) |
| `v2/scripts/dev-helpers/ga4-admin-custom-dimensions.php` | Register custom dimensions (conversion_type, form_id, cta_name, cta_location) |
| `v2/scripts/dev-helpers/gtm-configure-cta-tracking.php` | Create cta_click trigger, variables, GA4 tag in GTM |

## GA4 Admin API – Key Events

### Prerequisites

1. **Enable Analytics Admin API** in GCP Console:
   - https://console.cloud.google.com/apis/library/analyticsadmin.googleapis.com

2. **Grant service account access** to GA4 property:
   - GA4 Admin → Property → Property Access Management
   - Add `client_email` from `v2/config/google-api-credentials.json` with **Editor** role

### Usage

```bash
# Dry run (show what would be created)
php v2/scripts/dev-helpers/ga4-admin-key-events.php --dry-run

# Create key events
php v2/scripts/dev-helpers/ga4-admin-key-events.php
```

Events marked: `generate_lead`, `cta_click`.

### GA4 Admin API – Custom Dimensions

```bash
# Dry run (show what would be created)
php v2/scripts/dev-helpers/ga4-admin-custom-dimensions.php --dry-run

# Create custom dimensions (skips existing)
php v2/scripts/dev-helpers/ga4-admin-custom-dimensions.php
```

Dimensions created: `conversion_type`, `form_id`, `cta_name`, `cta_location` (all event-scoped). Allow 24–48 hours for them to appear in reports.

### GA4 Admin Checklist

| Item | Automation | Manual |
|------|-------------|--------|
| Custom dimensions | `php v2/scripts/dev-helpers/ga4-admin-custom-dimensions.php` | Admin → Custom definitions |
| Key events | `php v2/scripts/dev-helpers/ga4-admin-key-events.php` | Admin → Events → Key events |
| Key event counting | — | Use "Once per event" for `generate_lead`, `cta_click` |
| Data retention | — | Admin → Data settings → 14 months |

**Custom dimensions script** registers: `conversion_type`, `form_id`, `cta_name`, `cta_location` (event-scoped). See [GA4_EVENT_NAMING.md](GA4_EVENT_NAMING.md).

### Full GA4 Setup Checklist

Use this checklist when onboarding, auditing, or recovering the GA4/GTM setup.

**GA4 Admin (Admin → Property 275821028):**

| Item | Location | Action |
|------|----------|--------|
| Custom dimensions | Custom definitions | Run `ga4-admin-custom-dimensions.php` or verify: conversion_type, form_id, cta_name, cta_location |
| Key events | Events → Key events | Run `ga4-admin-key-events.php` or verify: generate_lead, cta_click |
| Key event counting | Events → Key events → Change counting | Set "Once per event" for both |
| Data retention | Data settings | 14 months |
| Reporting identity | Data display | Blended (if Advanced Consent Mode) |
| Enhanced measurement | Data streams → Web → Configure | Scrolls, outbound clicks, site search, etc. – verify and document |
| Internal traffic | Admin → Data streams → Configure | Exclude dev/staging IPs or hostnames; define internal traffic rules |

**GTM (GTM-5DWSFND):**

| Item | Action |
|------|--------|
| CTA trigger | Fire on `cta_click` custom event (not generic clicks) |
| CTA variables | DLV - CTA Name, DLV - CTA Location |
| Form trigger | Custom Event `form_submit` |
| Form variables | DLV - Conversion Type, DLV - Form ID |
| generate_lead tag | Fire on form_submit; pass conversion_type, form_id |
| GA4 config | Fire before event tags (tag sequencing) |
| Consent | Default denied; update on banner interaction |

**Code:**

| Item | Action |
|------|--------|
| CTA elements | `data-event-type="button_click"`, `data-event-name="..."` |
| GTMFormTracker | All forms include `conversionType` |

**Validation:**

| Item | Command / Action |
|------|------------------|
| API validation | `php v2/scripts/dev-helpers/ga4-setup-validate.php` |
| Browser validation | [BROWSER_VALIDATION_CHECKLIST.md](BROWSER_VALIDATION_CHECKLIST.md) |

### GA4 Admin – Enhanced Measurement, Retention, Internal Traffic

**Enhanced Measurement** (Admin → Data streams → Web stream → Configure):

- Page views (auto)
- Scrolls (90% threshold)
- Outbound clicks
- Site search (if applicable)
- Form interactions (if not using GTMFormTracker for all)
- File downloads

Document which features are enabled. Disable any that duplicate custom events (e.g. form interactions if we track via GTMFormTracker).

**Data retention:** Admin → Data settings → Data retention. Set to 14 months for event data.

**Internal traffic:** Admin → Data streams → Configure tag → Define internal traffic. Add rules to exclude dev/staging (e.g. hostname contains `localhost`, `staging`, or specific IPs). Prevents internal traffic from inflating reports.

### Consent Mode Timing (Audit)

**Current flow (v2/base/footer.php):** On `window.load`: (1) `setDefaultConsent()` pushes `gtag('consent', 'default', {...})` to dataLayer, (2) `loadGTM()` loads GTM. Consent default is set **before** GTM loads, which meets best practice. GTM processes the dataLayer queue and sees consent state before firing tags.

**Basic mode:** Tags are blocked until consent granted. For Advanced mode (cookieless pings when denied), GTM would need to load before the consent banner; document trade-offs in this section if adopted.

### footer_free_trial_updated.php (Audit)

**Used by:** `kostenlos_testen.php`, `kostenlos_testen_neu.php`

**Status (2026-02-18):** Aligned with main footer. Unconditional HubSpot, Facebook Pixel, LinkedIn, and TikTok removed. `loadScripts()` now includes `sendPageView()` when analytics consent and `loadHubSpot()` when hubspot consent. Consent default set before GTM; `configureTracking()` no longer fires unconditional page_view. GTM handles GA4/Meta via Consent Mode.

---

## GTM API – CTA Tracking

**Note:** Tag Manager API must be enabled. If disabled, use manual steps in [GTM_IMPLEMENTATION_STEPS.md](GTM_IMPLEMENTATION_STEPS.md).

### Prerequisites

1. **Enable Tag Manager API** in GCP Console:
   - https://console.cloud.google.com/apis/library/tagmanager.googleapis.com

2. **Grant service account access** to GTM account:
   - GTM → Admin → User Management
   - Add `client_email` from credentials with **Edit** permission

### Usage

```bash
# Dry run (show planned changes)
php v2/scripts/dev-helpers/gtm-configure-cta-tracking.php --dry-run

# Create trigger, variables, tag; create version (no publish)
php v2/scripts/dev-helpers/gtm-configure-cta-tracking.php

# Create and publish
php v2/scripts/dev-helpers/gtm-configure-cta-tracking.php --publish

# Specify account if auto-discovery fails
php v2/scripts/dev-helpers/gtm-configure-cta-tracking.php --account=123456
```

### What It Creates

- **Trigger:** Custom Event `cta_click`
- **Variables:** DLV - CTA Name (`cta_name`), DLV - CTA Location (`cta_location`)
- **Tag:** GA4 Event - cta_click (sends to G-2JRTDQFVPZ)
- **Version:** Container version (optional publish)

---

## Credentials

Both scripts use `v2/config/google-api-credentials.php` and `getGoogleAPIClientWithScopes()`.

- **GA4 Admin:** `analytics.edit`
- **GTM:** `tagmanager.edit.containers`, `tagmanager.publish`

---

## Pending Manual Tasks and Next Steps

**GTM configuration** (codebase ready; requires GTM UI or API):

1. **CTA trigger narrowing** – Fire on `cta_click` custom event only. See [GTM_IMPLEMENTATION_STEPS.md](GTM_IMPLEMENTATION_STEPS.md).
2. **form_submit → generate_lead** – Create trigger, DLV - Conversion Type, GA4 tag. See [GTM_IMPLEMENTATION_STEPS.md](GTM_IMPLEMENTATION_STEPS.md).

**Optional:** Enable Tag Manager API to run `gtm-configure-cta-tracking.php --publish` for automated CTA setup:
- https://console.cloud.google.com/apis/library/tagmanager.googleapis.com

**After GTM changes:**
- Run [BROWSER_VALIDATION_CHECKLIST.md](BROWSER_VALIDATION_CHECKLIST.md)
- Run `make validate-analytics` (after 24–48h for data)
- Run `ga4-cta-funnel-analysis.php` to verify improved funnel completion rate

## References

- [GTM_IMPLEMENTATION_STEPS.md](GTM_IMPLEMENTATION_STEPS.md) – Step-by-step manual GTM tasks
- [GTM_CONFIGURATION_GUIDE.md](GTM_CONFIGURATION_GUIDE.md) – Manual GTM setup
- [GA4_EVENT_NAMING.md](GA4_EVENT_NAMING.md) – Event naming, custom dimensions
- [CONVERSION_POINTS_AUDIT.md](CONVERSION_POINTS_AUDIT.md) – Conversion inventory
- GA4 property: https://analytics.google.com/analytics/web/#/p275821028 (ordio-472310)
