方法与优势
事件分类会明确名称、参数和转化定义,生成的追踪计划可以直接作为开发说明。数据收集以后,运营也能依据同一份文档解释报表,知道某个指标究竟代表哪一步动作,而不是靠事件名称猜测。
把用户在店铺里的关键动作转成清楚的 GA4 电商埋点方案。提供购物路径、现有分析配置和转化定义后,这项 Skill 会帮助助手明确事件、参数和命名,检查数据质量,并整理同意机制、重复触发和上线验证事项,让运营与开发使用同一份追踪说明。
相似动作使用不同名称,或业务动作尚未完成就触发事件,都会让分析结果难以解释。这项 Skill 通过事件分类与追踪计划生成器,把客户动作、参数和验证要求联系起来,减少运营口径与开发实现之间的偏差。
适合新建追踪方案,或检查已有 GA4/GTM 配置。尽量提供事件样本和当前转化规则,便于发现具体问题。安装包不会获得后台权限或发布 GTM 容器,实施后仍需在真实页面检查事件是否按计划发生。
事件分类会明确名称、参数和转化定义,生成的追踪计划可以直接作为开发说明。数据收集以后,运营也能依据同一份文档解释报表,知道某个指标究竟代表哪一步动作,而不是靠事件名称猜测。
验证范围包含系统如何响应用户的同意选择、重复事件和归因相关检查。把写方案与验证实现分开,实际检查事件内容和页面行为,避免文档看起来完整,线上却存在重复计数、未按选择控制追踪或参数缺失的问题。
用户路径、分析技术栈、已有事件、转化定义、同意机制和事件载荷样例。
使用支持 Skill 且能访问文件的 Agent。随包 Python 辅助工具需要 Python 3;提供数据前先查看样例结构。
本包不会授予分析权限或发布 GTM 容器;实时事件、同意行为、去重和归因需另行测试。
将指令复制给 Codex 或 Claude Code,让助手从原始仓库下载固定提交,安装完整文件并检查所需依赖。
请在我当前使用的应用中安装 analytics-tracking,直接执行文件安装,不要只解释步骤。
原始仓库:https://github.com/alirezarezvani/claude-skills.git
固定提交:6d2f02ea077eead1bee5411a31bcc6db5a11a70c
Skill 路径:marketing-skill/skills/analytics-tracking
1. 将这个版本下载到新目录。执行随包脚本前,先阅读 SKILL.md 和安装参考文件,不替换成其他作者的包。
2. Codex 安装到 ~/.agents/skills/analytics-tracking,Claude Code 安装到 ~/.claude/skills/analytics-tracking,只安装到我正在使用的应用。安装完整 Skill 文件夹,保留 scripts、references、assets 和随包声明;将仓库根目录许可证一并保留。先检查所有目标目录;已有安装时,说明差异后再决定是否替换。
3. 比较来源和安装目录的文件清单、文件哈希,检查文档要求的运行时、依赖及外部连接。只配置此 Skill 所需的本地依赖,适用时使用隔离环境;账号登录由我在本地完成,不把凭据贴进聊天。
4. 返回来源提交、实际安装路径、文件检查结果及尚未完成的运行环境配置,说明如何调用 analytics-tracking。文件复制与应用发现分别检查,需要时新建会话。不要执行生产任务,也不要把安装完成说成已确认业务效果。以下为已核对版本未经改写的 SKILL.md。安装完整包才能保留引用的脚本、素材和指引。下方启动提示词为 EcomAgentTools 编写的示例。
---
name: "analytics-tracking"
description: "Set up, audit, and debug analytics tracking implementation — GA4, Google Tag Manager, event taxonomy, conversion tracking, and data quality. Use when building a tracking plan from scratch, auditing existing analytics for gaps or errors, debugging missing events, or setting up GTM. Trigger keywords: GA4 setup, Google Tag Manager, GTM, event tracking, analytics implementation, conversion tracking, tracking plan, event taxonomy, custom dimensions, UTM tracking, analytics audit, missing events, tracking broken. NOT for analyzing marketing campaign data — use campaign-analytics for that. NOT for BI dashboards — use product-analytics for in-product event analysis."
license: MIT
metadata:
version: 1.0.0
author: Alireza Rezvani
category: marketing
updated: 2026-03-06
---
# Analytics Tracking
You are an expert in analytics implementation. Your goal is to make sure every meaningful action in the customer journey is captured accurately, consistently, and in a way that can actually be used for decisions — not just for the sake of having data.
Bad tracking is worse than no tracking. Duplicate events, missing parameters, unconsented data, and broken conversions lead to decisions made on bad data. This skill is about building it right the first time, or finding what's broken and fixing it.
## Before Starting
**Check for context first:**
If `.claude/product-marketing-context.md` exists, read it before asking questions. Use that context and only ask for what's missing.
Gather this context:
### 1. Current State
- Do you have GA4 and/or GTM already set up? If so, what's broken or missing?
- What's your tech stack? (React SPA, Next.js, WordPress, custom, etc.)
- Do you have a consent management platform (CMP)? Which one?
- What events are you currently tracking (if any)?
### 2. Business Context
- What are your primary conversion actions? (signup, purchase, lead form, free trial start)
- What are your key micro-conversions? (pricing page view, feature discovery, demo request)
- Do you run paid campaigns? (Google Ads, Meta, LinkedIn — affects conversion tracking needs)
### 3. Goals
- Building from scratch, auditing existing, or debugging a specific issue?
- Do you need cross-domain tracking? Multiple properties or subdomains?
- Server-side tagging requirement? (GDPR-sensitive markets, performance concerns)
## How This Skill Works
### Mode 1: Set Up From Scratch
No analytics in place — we'll build the tracking plan, implement GA4 and GTM, define the event taxonomy, and configure key events.
Start from the generator, then customize:
```bash
python3 scripts/tracking_plan_generator.py # embedded sample → full tracking plan
python3 scripts/tracking_plan_generator.py plan.json # your funnel definition
python3 scripts/tracking_plan_generator.py --json # parseable JSON for pipelines
```
Its output (event taxonomy + parameters + GA4/GTM config checklist) is the working draft for the Event Taxonomy Design section below — review every generated event name against the naming convention before implementing.
### Mode 2: Audit Existing Tracking
Tracking exists but you don't trust the data, coverage is incomplete, or you're adding new goals. We'll audit what's there, gap-fill, and clean up.
### Mode 3: Debug Tracking Issues
Specific events are missing, conversion numbers don't add up, or GTM preview shows events firing but GA4 isn't recording them. Structured debugging workflow.
---
## Event Taxonomy Design
Get this right before touching GA4 or GTM. Retrofitting taxonomy is painful.
### Naming Convention
**Format:** `object_action` (snake_case, verb at the end)
| ✅ Good | ❌ Bad |
|--------|--------|
| `form_submit` | `submitForm`, `FormSubmitted`, `form-submit` |
| `plan_selected` | `clickPricingPlan`, `selected_plan`, `PlanClick` |
| `video_started` | `videoPlay`, `StartVideo`, `VideoStart` |
| `checkout_completed` | `purchase`, `buy_complete`, `checkoutDone` |
**Rules:**
- Always `noun_verb` not `verb_noun`
- Lowercase + underscores only — no camelCase, no hyphens
- Be specific enough to be unambiguous, not so verbose it's a sentence
- Consistent tense: `_started`, `_completed`, `_failed` (not mix of past/present)
### Standard Parameters
Every event should include these where applicable:
| Parameter | Type | Example | Purpose |
|-----------|------|---------|---------|
| `page_location` | string | `https://app.co/pricing` | Auto-captured by GA4 |
| `page_title` | string | `Pricing - Acme` | Auto-captured by GA4 |
| `user_id` | string | `usr_abc123` | Link to your CRM/DB |
| `plan_name` | string | `Professional` | Segment by plan |
| `value` | number | `99` | Revenue/order value |
| `currency` | string | `USD` | Required with value |
| `content_group` | string | `onboarding` | Group pages/flows |
| `method` | string | `google_oauth` | How (signup method, etc.) |
### Event Taxonomy for SaaS
**Core funnel events:**
```
visitor_arrived (page view — automatic in GA4)
signup_started (user clicked "Sign up")
signup_completed (account created successfully)
trial_started (free trial began)
onboarding_step_completed (param: step_name, step_number)
feature_activated (param: feature_name)
plan_selected (param: plan_name, billing_period)
checkout_started (param: value, currency, plan_name)
checkout_completed (param: value, currency, transaction_id)
subscription_cancelled (param: cancel_reason, plan_name)
```
**Micro-conversion events:**
```
pricing_viewed
demo_requested (param: source)
form_submitted (param: form_name, form_location)
content_downloaded (param: content_name, content_type)
video_started (param: video_title)
video_completed (param: video_title, percent_watched)
chat_opened
help_article_viewed (param: article_name)
```
See [references/event-taxonomy-guide.md](references/event-taxonomy-guide.md) for the full taxonomy catalog with custom dimension recommendations.
---
## GA4 Setup
### Data Stream Configuration
1. **Create property** in GA4 → Admin → Properties → Create
2. **Add web data stream** with your domain
3. **Enhanced Measurement** — enable all, then review:
- ✅ Page views (keep)
- ✅ Scrolls (keep)
- ✅ Outbound clicks (keep)
- ✅ Site search (keep if you have search)
- ⚠️ Video engagement (disable if you'll track videos manually — avoid duplicates)
- ⚠️ File downloads (disable if you'll track these in GTM for better parameters)
4. **Configure domains** — add all subdomains used in your funnel
### Custom Events in GA4
For any event not auto-collected, create it in GTM (preferred) or via gtag directly:
**Via gtag:**
```javascript
gtag('event', 'signup_completed', {
method: 'email',
user_id: 'usr_abc123',
plan_name: "trial"
});
```
**Via GTM data layer (preferred — see GTM section):**
```javascript
window.dataLayer.push({
event: 'signup_completed',
signup_method: 'email',
user_id: 'usr_abc123'
});
```
### Key Events Configuration
Mark these events as key events in GA4 → Admin → Key events (GA4 renamed "Conversions" to "Key events" in March 2024 — "conversions" now refers only to Google Ads conversion actions):
- `signup_completed`
- `checkout_completed`
- `demo_requested`
- `trial_started` (if separate from signup)
**Rules:**
- Max 30 key events per property — curate, don't mark everything
- Key events are retroactive in GA4 — turning one on applies to 6 months of history
- Don't mark micro-conversions as key events unless you're also optimizing ad campaigns for them
---
## Google Tag Manager Setup
### Container Structure
```
GTM Container
├── Tags
│ ├── GA4 Configuration (fires on all pages)
│ ├── GA4 Event — [event_name] (one tag per event)
│ ├── Google Ads Conversion (per conversion action)
│ └── Meta Pixel (if running Meta ads)
├── Triggers
│ ├── All Pages
│ ├── DOM Ready
│ ├── Data Layer Event — [event_name]
│ └── Custom Element Click — [selector]
└── Variables
├── Data Layer Variables (dlv — for each dL key)
├── Constant — GA4 Measurement ID
└── JavaScript Variables (computed values)
```
### Tag Patterns for SaaS
**Pattern 1: Data Layer Push (most reliable)**
Your app pushes to dataLayer → GTM picks it up → sends to GA4.
```javascript
// In your app code (on event):
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'signup_completed',
signup_method: 'email',
user_id: userId,
plan_name: "trial"
});
```
```
GTM Tag: GA4 Event
Event Name: {{DLV - event}} OR hardcode "signup_completed"
Parameters:
signup_method: {{DLV - signup_method}}
user_id: {{DLV - user_id}}
plan_name: "dlv-plan-name"
Trigger: Custom Event - "signup_completed"
```
**Pattern 2: CSS Selector Click**
For events triggered by UI elements without app-level hooks.
```
GTM Trigger:
Type: Click - All Elements
Conditions: Click Element matches CSS selector [data-track="demo-cta"]
GTM Tag: GA4 Event
Event Name: demo_requested
Parameters:
page_location: {{Page URL}}
```
See [references/gtm-patterns.md](references/gtm-patterns.md) for full configuration templates.
---
## Conversion Tracking: Platform-Specific
### Google Ads
1. Create conversion action in Google Ads → Tools → Conversions
2. Import GA4 conversions (recommended — single source of truth) OR use the Google Ads tag
3. Set attribution model: **Data-driven** (if >50 conversions/month), otherwise **Last click**
4. Conversion window: 30 days for lead gen, 90 days for high-consideration purchases
### Meta (Facebook/Instagram) Pixel
1. Install Meta Pixel base code via GTM
2. Standard events: `PageView`, `Lead`, `CompleteRegistration`, `Purchase`
3. Conversions API (CAPI) strongly recommended — client-side pixel loses ~30% of conversions due to ad blockers and iOS
4. CAPI requires server-side implementation (Meta's docs or GTM server-side)
---
## Cross-Platform Tracking
### UTM Strategy
Enforce strict UTM conventions or your channel data becomes noise.
| Parameter | Convention | Example |
|-----------|-----------|---------|
| `utm_source` | Platform name (lowercase) | `google`, `linkedin`, `newsletter` |
| `utm_medium` | Traffic type | `cpc`, `email`, `social`, `organic` |
| `utm_campaign` | Campaign ID or name | `q1-trial-push`, `brand-awareness` |
| `utm_content` | Ad/creative variant | `hero-cta-blue`, `text-link` |
| `utm_term` | Paid keyword | `saas-analytics` |
**Rule:** Never tag organic or direct traffic with UTMs. UTMs override GA4's automatic source/medium attribution.
### Attribution Windows
| Platform | Default Window | Recommended for SaaS |
|---------|---------------|---------------------|
| GA4 | 30 days | 30-90 days depending on sales cycle |
| Google Ads | 30 days | 30 days (trial), 90 days (enterprise) |
| Meta | 7-day click, 1-day view | 7-day click only |
| LinkedIn | 30 days | 30 days |
### Cross-Domain Tracking
For funnels that cross domains (e.g., `acme.com` → `app.acme.com`):
1. In GA4 → Admin → Data Streams → Configure tag settings → List unwanted referrals → Add both domains
2. In GTM → GA4 Configuration tag → Cross-domain measurement → Add both domains
3. Test: visit domain A, click link to domain B, check GA4 DebugView — session should not restart
---
## Data Quality
### Deduplication
**Events firing twice?** Common causes:
- GTM tag + hardcoded gtag both firing
- Enhanced Measurement + custom GTM tag for same event
- SPA router firing pageview on every route change AND GTM page view tag
Fix: Audit GTM Preview for double-fires. Check Network tab in DevTools for duplicate hits.
### Bot Filtering
GA4 filters known bots automatically. For internal traffic:
1. GA4 → Admin → Data Filters → Internal Traffic
2. Add your office IPs and developer IPs
3. Enable filter (starts as testing mode — activate it)
### Consent Management Impact
Under GDPR/ePrivacy, analytics may require consent. Plan for this:
| Consent Mode setting | Impact |
|---------------------|--------|
| **No consent mode** | Visitors who decline cookies → zero data |
| **Basic consent mode** | Visitors who decline → zero data |
| **Advanced consent mode** | Visitors who decline → modeled data (GA4 estimates using consented users) |
**Recommendation:** Implement Advanced Consent Mode via GTM. Requires CMP integration (Cookiebot, OneTrust, Usercentrics, etc.).
Expected consent rate by region: 60-75% EU, 85-95% US.
---
## Proactive Triggers
Surface these without being asked:
- **Events firing on every page load** → Symptom of misconfigured trigger. Flag: duplicate data inflation.
- **No user_id being passed** → You can't connect analytics to your CRM or understand cohorts. Flag for fix.
- **Conversions not matching GA4 vs Ads** → Attribution window mismatch or pixel duplication. Flag for audit.
- **No consent mode configured in EU markets** → Legal exposure and underreported data. Flag immediately.
- **All pages showing as "/(not set)" or generic paths** → SPA routing not handled. GA4 is recording wrong pages.
- **UTM source showing as "direct" for paid campaigns** → UTMs missing or being stripped. Traffic attribution is broken.
---
## Output Artifacts
| When you ask for... | You get... |
|--------------------|-----------|
| "Build a tracking plan" | Event taxonomy table (events + parameters + triggers), GA4 configuration checklist, GTM container structure |
| "Audit my tracking" | Gap analysis vs. standard SaaS funnel, data quality scorecard (0-100), prioritized fix list |
| "Set up GTM" | Tag/trigger/variable configuration for each event, container setup checklist |
| "Debug missing events" | Structured debugging steps using GTM Preview + GA4 DebugView + Network tab |
| "Set up conversion tracking" | Conversion action configuration for GA4 + Google Ads + Meta |
| "Generate tracking plan" | Run `python3 scripts/tracking_plan_generator.py [plan.json] [--json]` — event taxonomy + GA4/GTM checklist |
---
## Communication
All output follows the structured communication standard:
- **Bottom line first** — what's broken or what needs building before methodology
- **What + Why + How** — every finding has all three
- **Actions have owners and deadlines** — no vague "consider implementing"
- **Confidence tagging** — 🟢 verified / 🟡 estimated / 🔴 assumed
---
## Related Skills
- **campaign-analytics**: Use for analyzing marketing performance and channel ROI. NOT for implementation — use this skill for tracking setup.
- **ab-test-setup**: Use when designing experiments. NOT for event tracking setup (though this skill's events feed A/B tests).
- **analytics-tracking** (this skill): covers setup only. For dashboards and reporting, use campaign-analytics.
- **seo-audit**: Use for technical SEO. NOT for analytics tracking (though both use GA4 data).
- **gdpr-dsgvo-expert**: Use for GDPR compliance posture. This skill covers consent mode implementation; that skill covers the full compliance framework.
以下是主要功能的用例提示词,可以直接复制使用。
起草购买与漏斗事件规格 适用于:起草购买与漏斗事件规格。请准备:用户路径、分析技术栈、已有事件、转化定义、同意机制和事件载荷样例。
请使用已安装的 analytics-tracking Skill。任务:起草购买与漏斗事件规格。输入:[INPUT]。限制:[CONSTRAINTS]。先检查缺失信息,再输出可审查的结果、依据、假设和下一步。本包不会授予分析权限或发布 GTM 容器;实时事件、同意行为、去重和归因需另行测试。[INPUT][CONSTRAINTS]审查缺失参数和重复事件 适用于:审查缺失参数和重复事件。请准备:用户路径、分析技术栈、已有事件、转化定义、同意机制和事件载荷样例。
请使用已安装的 analytics-tracking Skill。任务:审查缺失参数和重复事件。输入:[INPUT]。限制:[CONSTRAINTS]。先检查缺失信息,再输出可审查的结果、依据、假设和下一步。本包不会授予分析权限或发布 GTM 容器;实时事件、同意行为、去重和归因需另行测试。[INPUT][CONSTRAINTS]制作考虑同意状态的埋点验证步骤 适用于:制作考虑同意状态的埋点验证步骤。请准备:用户路径、分析技术栈、已有事件、转化定义、同意机制和事件载荷样例。
请使用已安装的 analytics-tracking Skill。任务:制作考虑同意状态的埋点验证步骤。输入:[INPUT]。限制:[CONSTRAINTS]。先检查缺失信息,再输出可审查的结果、依据、假设和下一步。本包不会授予分析权限或发布 GTM 容器;实时事件、同意行为、去重和归因需另行测试。[INPUT][CONSTRAINTS]输入模拟站点事件需求与现有配置问题,包括重复 page_view、刷新重复 purchase、缺币种和同意默认值。商家需要一份开发能按字段实施的跟踪计划。
案例输入资料:business-inputs.zip
Use the analytics-tracking Skill.
Create an ecommerce measurement plan for the supplied purchase journey and business goals. Map actual customer actions to GA4 events, define parameters, successful triggers, transaction deduplication and consent handling, and specify GTM tags and variables. Give implementation acceptance checks for the developer and analyst.
The attached business materials are:
- inputs/brief.json
- inputs/context.json
Deliver a complete result.md report that the operations team can read, plus any finished files needed for this task. Keep supporting calculations and evidence with the deliverables. Write the report in English; use the requested target language for customer-facing copy. The business datasets are fictional examples unless the brief explicitly names a live public website.下方直接展示本次 Prompt 产生的主要文件,保留实际输出语言。
Build a consent-gated GA4 funnel from product view through confirmed paid order. Use one router-owned page-view implementation, application success callbacks for commerce events, USD on all monetary events, and stable transaction IDs. A guest who declines optional consent must generate zero analytics or advertising requests. The operational order system remains the source of truth for all sales and refunds.
This plan uses synthetic supplied business data and configuration observations; no storefront integration, GA4 account, GTM container, CMP implementation, or measured business improvement has been verified.
Decisions and scope
The supplied journey is /products/harbormug → /cart → /checkout in a React SPA on a single US storefront. The core business decision is where consenting shoppers leave the journey and whether successful paid orders are measured accurately. USD is the proposed currency based on the supplied US storefront; the implementation owner must confirm it against the order system before release. Shipping and payment step events below are conditional because separate steps are not specified.
The brief lists Google Ads and Meta, but the context explicitly excludes paid-channel activation and purchase optimization. Therefore this delivery specifies GA4 measurement only: no Ads imports, conversion linker, Meta pixel, CAPI, remarketing audiences, or enhanced conversions. Purchase is a GA4 key event for measurement, with no ad-platform activation. No cross-domain or server-side analytics is planned. Guest user_id omission is intentional; do not create an identifier or require login for measurement.
Evidence confidence: verified in supplied materials means documented input, not observed telemetry; proposed means implementation design; unconfirmed means a release dependency. The supplied dual page-view sources, thank-you load trigger, missing currency and unset consent default are documented design risks, not findings from a live audit.
Business questions and reporting definitions
| Decision | Measurement | Interpretation |
|---|---|---|
| Does product interest turn into cart intent? | Consented sessions with view_item then add_to_cart / consented sessions with view_item | Same-session ordered funnel; successful additions, not clicks |
| Does the cart lead to checkout? | Sessions with view_cart then begin_checkout / sessions with view_cart | A cart drawer or skipped cart route may bypass this step; keep a separate direct-to-checkout segment |
| Does checkout result in payment? | Sessions with begin_checkout then purchase / sessions with begin_checkout | Payment failures and exits are not paid orders; cross-session purchases also appear in an open funnel |
| Are sales and amounts trustworthy? | Distinct paid transaction IDs, purchased item quantities, merchandise purchase revenue | Reconcile to eligible order records on identical date, currency and revenue basis |
| Has money actually been returned? | Confirmed refunded merchandise and quantities by original transaction | Return requests and refund approvals are not refunds |
Use a closed, same-session product → add → checkout → purchase funnel for the main journey. Use an open funnel alongside it for direct checkout and returning shoppers. Do not divide raw event counts to estimate shopper conversion: repeated actions and quantities differ. Pick and record the property reporting timezone with operations before launch, and use it for ledger reconciliation.
For orientation only, supplied prior/current totals are 100/120 orders and 4,000/4,800 sessions. Orders per session are 2.5% in both periods; gross average order value is $24 in both. Orders, sessions and gross sales each rise 20%; these examples do not show improved conversion. Gross sales less supplied refunds are $2,280 and $2,736. Refund amounts are 5% of gross in each period, not a refunded-order rate. These are supplied all-business totals, not a consented GA4 funnel or evidence of tracking performance. Calculations are in supporting/calculations.json.
Customer action → event contract
Use Google's recommended ecommerce names, including view_item, begin_checkout and purchase, to populate ecommerce reporting. These intentionally supersede the Skill generator's generic names product_viewed, checkout_started and checkout_completed; do not send aliases alongside them. The generated search event is excluded because no search surface is supplied. Google ecommerce guide
All rows require analytics consent granted at the time of the action and immediately before dispatch. Commerce rows use currency, value, and items unless stated otherwise.
| Customer action | GA4 event | Successful trigger and counting rule |
|---|---|---|
| Views a rendered route | page_view | Initial render or completed navigation, once per navigation; not rerenders |
| Sees the HarborMug product | view_item | Product fetch succeeds and product content renders, once per product per navigation |
| Adds mugs | add_to_cart | Cart mutation succeeds; quantity/value describe only the increment |
| Removes mugs | remove_from_cart | Cart mutation succeeds; quantity/value describe only the decrement |
| Views cart | view_cart | Cart snapshot renders on /cart, once per navigation; full current cart |
| Enters valid checkout | begin_checkout | Nonempty cart accepted and checkout ready, once per checkout attempt, including direct valid entry |
| Saves shipping selection, if a separate step exists | add_shipping_info | Valid selection persisted; once per distinct saved selection per attempt; add shipping_tier |
| Supplies an accepted payment method, if a separate step exists | add_payment_info | Checkout service accepts method; once per distinct accepted method per attempt; add payment_type |
| Completes payment | purchase | Trusted order endpoint confirms paid/captured state; add transaction_id, shipping, tax; one logical event per order |
| Receives an actual refund, future workflow | refund | Provider confirms refund executed; original transaction ID and refunded items/value; inactive at launch |
An attempt begins when the checkout service creates or resumes a checkout token; resuming the same token is the same attempt. A new service token after expiry or a deliberate new checkout is a new attempt. Tokens remain internal and are never sent to GA4. Failed validation, failed cart requests, pending payment and authorization without capture produce no success event. Do not infer abandonment by sending a purchase failure on every exit.
The complete portable contract is event-contract.csv; consent-granted example payloads for every event are in data-layer-examples.json. Neither is evidence of actual actions. No new customer-facing copy is needed.
Parameter dictionary and financial basis
| Field | Type and rule | Source |
|---|---|---|
currency | String, uppercase ISO currency; proposed USD; required with every monetary value | Validated cart/order currency |
value | Number in major currency units; sum of discounted unit price × quantity; excludes tax and shipping | Accepted cart mutation/snapshot or paid order lines |
items | Array of item objects; required, nonempty except an empty view_cart | Product/cart/order API |
item_id | String HM-BLUE-001; stable SKU | Product catalog |
item_name | String Insulated stainless steel mug 500ml | Product catalog |
price | Number, actual unit merchandise price after discounts; current list price 24 | Accepted line item |
quantity | Positive integer for nonempty lines; additions/removals use positive changed quantity | Accepted line item |
transaction_id | Immutable unique opaque order reference; nonempty, no personal data; purchase/refund only | Order system, never URL or random browser ID |
shipping, tax | Nonnegative numbers for purchase; actual charged amounts, explicit zero only when genuinely zero | Paid order totals |
shipping_tier | Controlled string such as standard; optional step only | Saved checkout selection |
payment_type | Controlled generic method such as card; no financial instrument data | Accepted checkout method |
page_location | Sanitized absolute current URL | Router state |
page_title | Nonpersonal current route title, ready before event | Route metadata |
page_referrer | Sanitized previous committed route; first entry uses sanitized external referrer if available | Router navigation state |
Use actual paid amounts, never the brief's $24 hint as a constant purchase value. For one mug without discounts: merchandise value=24, shipping 5, and tax from the order API; total charged is 29 + tax. Two mugs give value=48, shipping 5; three give value=72, shipping 0 because the free-shipping threshold is $50. Do not confuse the merchant's $4 shipping cost with the $5 customer shipping charge. The example payload's zero tax is a test scenario, not a tax assumption. If discounts are introduced, confirm threshold and discount-allocation rules with operations before implementation. Recommended event parameter definitions
Clear ecommerce with dataLayer.push({ecommerce:null}) before each commerce push to prevent old order fields merging into cart events. Supply a complete fresh ecommerce object, and explicitly reset irrelevant optional fields. Keep route fields fresh on every event; send sanitized page fields on commerce hits as well. Reject malformed purchase payloads instead of sending partial revenue. Log a minimal reason in first-party operational diagnostics without personal or payment data.
SPA page views and attribution
Choose the application router as the only page-view source. Set the Google tag's send_page_view=false on every initialization and disable Enhanced Measurement history-based page views. Remove all GTM History Change page-view triggers and hardcoded analytics sends. The router emits after the committed route, data and title are ready, including the initial route. Deduplicate by a navigation token kept internal; React Strict Mode, state updates and fragment changes without new content must not create another navigation. Back/forward to a rendered route is a new view. Google manual page-view guidance
On delayed consent grant, emit one current route view and current visible product/cart snapshot only. Do not replay prior routes or past mutations. Use the prior committed route as virtual referrer; never use checkout tokens or order references as page URLs or titles. Preserve approved nonpersonal external campaign parameters on the current landing URL through tag initialization when consent permits. Do not persist prior browsing or campaign history while consent is denied.
For future campaign hygiene, normalize the supplied example to ?utm_source=google&utm_medium=cpc&utm_campaign=mug-launch. Keep approved campaign names lowercase and nonpersonal. Do not add UTMs to internal product/cart/checkout links or invent source values for direct traffic. Allowlist campaign parameters in the URL sanitizer; strip email, addresses, tokens, sensitive fragments and arbitrary query values. No account linking or paid-channel activation is part of this delivery.
Consent handling: basic mode, fail closed
Use basic consent mode rather than the generator's advanced-mode default. Default analytics_storage, ad_storage, ad_user_data, and ad_personalization to denied before any measurement tag can run. Defaults also deny optional functionality and personalization storage; strictly necessary security and cart functions are separate from analytics. Use a CMP template with GTM's consent APIs (setDefaultConsentState and updateConsentState), on Consent Initialization. A plain data-layer object containing consent strings is not an API update. Google consent implementation guide
The CMP must update consent before emitting a separate analytics_ready orchestration event. The Google tag loads only after analytics consent is granted; every GA4 event has both an explicit current-consent trigger condition and an additional analytics_storage consent requirement. Default-denied flags alone are insufficient to enforce zero requests: Google's advanced behavior can send cookieless pings. Basic mode blocks Google measurement tags before consent. Basic versus advanced consent behavior
| State | Required behavior |
|---|---|
| Unknown, CMP unavailable, or decline all | No GA4 library, collect hit, analytics cookie, dedup browser storage or advertising request; no queue for later replay |
| Analytics granted only | Initialize Google tag once; send current view and future eligible events; all advertising flags remain denied |
| Optional marketing accepted | Still no ad tags; only configured analytics may run, according to analytics choice |
| Analytics revoked | Update API immediately, block future tags, discard unsent events, clear analytics cookies and analytics-only guards according to their configured domains/paths; retain only necessary CMP preference |
| Later re-grant | Resume current view and future actions; never backfill payment or browsing that occurred while denied |
Check consent in the application before constructing analytics payloads and again in GTM. Serialize CMP transitions and dispatch so an event queued before revocation cannot escape afterward. Necessary order records and consent preferences are not an alternate analytics route. Do not send the declined guest's order through Measurement Protocol or any other analytics channel. The plan deliberately accepts incomplete GA4 coverage.
Transaction deduplication and delivery limits
The paid order endpoint supplies one stable transaction ID per order. The callback must validate payment status, ID, currency, items and totals. Never fire purchase from a thank-you route mount, refresh, click, payment attempt ID or browser-generated random ID. Repeated captures belonging to the same business order do not create new purchases; a genuinely separate order has a new ID.
After consent, use an in-memory single-flight lock plus an analytics-consented browser guard per transaction to stop duplicate callbacks, rerenders and reloads. Cross-tab/reopened-device protection must use an atomic first-party order-system claim keyed by transaction ID. The claim records only order measurement eligibility/handoff status, and must not send anything to GA4 or run for denied users. This is an order API requirement, not server-side tagging. If that endpoint cannot support the claim, document the residual cross-device duplication risk and do not treat local storage as sufficient.
Dispatch only after a successful claim, set the local handoff guard, and retain the same ID throughout. GA4's purchase deduplication is an additional defense; it does not justify repeated sends or protect every possible multi-user case. Never use a blank ID or reuse one ID for different orders. Google transaction-ID deduplication
The claim and GTM handoff cannot guarantee GA4 delivery. A blocked request or closed tab after claim can leave an eligible order unmeasured. Record it as delivery-unconfirmed in operational reconciliation, not as a proven GA4 receipt. A GTM callback is not a receipt either. Do not automatically replay on page load or introduce a server analytics fallback. Any later retry design needs an explicit delivery policy, current consent and the original ID. Prioritize zero duplicate logical purchases in controlled acceptance tests and transparent reporting of missing deliveries.
Returns and refunds
The supplied return was requested 14 calendar days after delivery and is unopened, within the stated 30-day window. Eligibility does not establish approval or payment. The recorded refund requires merchant approval and has not been paid: emit no refund event and deduct no amount for this individual return yet. The supplied weekly refund totals are separate aggregate examples.
Keep refund instrumentation inactive until there is a confirmed-refund source and consent-aware delivery route. A future refund sends the original transaction ID, actual refunded merchandise value and quantities, and only any tax/shipping actually refunded. Never send negative purchase events. Guard future partial refunds by an internal unique refund-operation reference; do not assume purchase transaction-ID deduplication handles multiple legitimate partial refunds. Browser-only measurement will miss refunds executed away from the shopper's session, so the refund ledger remains authoritative.
GTM build specification
This is a build specification, not an importable or deployed container. Use a separate test property/container environment before production; no real measurement identifiers are included.
| Tag | Trigger | Configuration |
|---|---|---|
CMP - Defaults and updates | Consent Initialization — All Pages; CMP change callback | Audited CMP template using consent APIs; defaults before measurement, then readiness orchestration |
Google tag - GA4 | Custom Event analytics_ready, only when analytics granted | Measurement destination constant; send_page_view=false; once per document; no all-pages load |
GA4 - page_view | Custom Event exact page_view, analytics granted and initialization complete | Fixed event name; sanitized location/title/referrer variables |
GA4 - EVENT for each of the eight active commerce rows | Exact Custom Event with matching fixed event name; analytics granted and initialization complete | One tag per event; parameters from that row; optional step tags disabled if no such step exists |
GA4 - refund | None at launch | Disabled until confirmed-refund workflow passes acceptance |
The eight active commerce rows are view_item, add_to_cart, remove_from_cart, view_cart, begin_checkout, add_shipping_info, add_payment_info, and purchase. Readiness initializes the Google tag before the app emits current-view events. Hold only post-grant events briefly while initialization completes; discard on revoke. The app must not send a second gtag implementation beside GTM.
| Variable | GTM type / exact source | Use |
|---|---|---|
CON - GA4 destination | Constant set during account creation | Google tag and all GA4 event tags |
DLV - currency/value/items | Three Version 2 variables: ecommerce.currency, ecommerce.value, ecommerce.items | Commerce tags |
DLV - transaction_id/shipping/tax | Three Version 2 variables under ecommerce with corresponding key | Purchase; refund only when applicable |
DLV - shipping_tier/payment_type | Two Version 2 variables under ecommerce | Corresponding optional step only |
DLV - page_location/page_title/page_referrer | Three Version 2 variables at root, already sanitized | All event tags |
JS - analytics allowed | Boolean from current CMP state, default false | Explicit trigger gate; never trust a stale data-layer value |
JS - analytics initialized | Boolean set only after Google tag initialization | Dispatch ordering gate |
CON - debug mode | Boolean true in test environment; absent in production | debug_mode on test events only |
Map value to DLV - value, items to DLV - items, and each other named parameter to its same-named variable. Configure ecommerce parameters explicitly; do not also turn on a second automatic ecommerce mapping that duplicates them. No click, generic form submit, DOM-ready or all-pages purchase trigger is allowed.
GA4 configuration and acceptance
Create one web stream for the storefront, confirm currency and reporting timezone, and configure one Google tag destination. Keep Google signals, advertising personalization and account links inactive for this scope. Use built-in ecommerce dimensions and metrics; do not register SKU, value, transaction ID or guest user_id as custom dimensions. No custom dimension is required for the core plan. If analysts need shipping_tier or payment_type and the required report does not expose them, register event-scoped definitions before testing those reports. Use a proposed two-month event-data retention setting, subject to the merchant's retention policy. Keep internal/developer traffic filters in testing until verified; use a separate test property to avoid permanent exclusion mistakes.
Use purchase as the sole commerce key event and count once per event so distinct orders in one session count separately. No funnel micro-event or pending return is a key event. Treat the key-event setup as prospective; do not promise historical backfill.
acceptance-checks.csv contains 16 executable test scenarios with explicit pass criteria and developer/analyst ownership. None has been run against a storefront. Required release gates are:
Evidence to retain for release: sanitized payload examples, GTM tag/consent traces, sanitized network event counts, DebugView observations, processed report counts and a synthetic transaction reconciliation table. Do not attach raw URLs, cookies, customer records or credentials. Troubleshoot from app to reports; adding another tag to fix a reporting delay risks duplicates.
Completed deliverables and remaining dependency
The finished plan includes event-contract.csv, data-layer-examples.json, acceptance-checks.csv, and supporting calculation, generator-review and verification evidence. It is ready for implementation. Live acceptance remains dependent on creating the planned GA4/GTM/CMP setup and wiring the order API; the supplied example domain and configuration cannot establish tag firing or delivery. Until the confirmed refund route exists, measure refunds in the operational ledger only.
案例中的商家经营资料为模拟数据;涉及网站检查时,报告中的页面观察来自所列公开网址。
本包不会授予分析权限或发布 GTM 容器;实时事件、同意行为、去重和归因需另行测试。
核对源码及随包文件:GitHub 6d2f02ea077e。本次为静态审查,不代表已完成安装运行或业务效果测试。
使用获授权输入,不把密钥贴入提示词。采用前检查面向客户的声明、计算、代码改动及任何拟议的外部操作。
规划和审查 GA4/GTM 事件、转化定义、同意机制和数据质量。事件分类流程和本地跟踪计划生成器把业务动作对应到参数和验证方法。
按实际 Agent 选择方式,安装完整包,不要只复制页面中的 SKILL.md。 用户路径、分析技术栈、已有事件、转化定义、同意机制和事件载荷样例。 开启新 Agent 会话,明确要求使用 analytics-tracking。先用小型样本尝试下方一个场景,并检查输出。
起草购买与漏斗事件规格;审查缺失参数和重复事件;制作考虑同意状态的埋点验证步骤
本包不会授予分析权限或发布 GTM 容器;实时事件、同意行为、去重和归因需另行测试。
核对源码及随包文件:GitHub 6d2f02ea077e。本次为静态审查,不代表已完成安装运行或业务效果测试。
核对源码及随包文件:GitHub 6d2f02ea077e。本次为静态审查,不代表已完成安装运行或业务效果测试。
暂无评论。