How to Connect Google Analytics, Ads & GTM to Your AI Chatbot
A step-by-step guide to connecting Google Analytics 4, Google Ads, Tag Manager, and Search Console to your AI chatbot using OAuth 2.0 — so you can track real engagement, measure ROI, and separate bots from humans.
You've deployed your AI chatbot. It's live on Telegram, WhatsApp, or your website. People are talking to it.
But how many people? And are they real — or bots?
If you're running Google Analytics, Google Ads, or Tag Manager, you already have the tools to answer these questions. The problem is connecting them to your chatbot infrastructure.
This guide walks you through the complete setup: OAuth credentials, API access, and practical queries you can run today.
What you'll set up
By the end of this guide, you'll have programmatic access to:
- Google Analytics 4 — real-time user counts, engagement metrics, traffic sources
- Google Tag Manager — manage tracking tags without code deploys
- Google Search Console — organic search performance and indexing
- Google Ads — campaign performance, spend, and conversions
All through a single OAuth 2.0 token that auto-refreshes.
Why this matters for AI chatbots
Traditional websites have clear pageview metrics. AI chatbots don't. A chatbot might handle 500 conversations a day, but if 480 of them are automated spam hitting your webhook endpoint, your numbers are meaningless.
We discovered this the hard way. One of our hosted bots showed 1,136 monthly users in Google Analytics. After digging into the data by country:
| Country | Users | Bounce Rate | Avg Duration |
|---|---|---|---|
| China | 494 | 99.8% | 0.2s |
| Singapore | 274 | 99.6% | 0.1s |
| Netherlands | 45 | 32% | 3m 12s |
| Germany | 28 | 41% | 2m 45s |
768 out of 1,136 "users" were bots. The real user count was closer to 350.
Without API access to query this data programmatically, you'd never notice.
Step 1: Create a Google Cloud project
If you already have a GCP project, skip to Step 2.
- Go to console.cloud.google.com
- Click New Project in the top bar
- Name it something like
my-chatbot-analytics - Note the project number (you'll need this later)
Step 2: Enable the APIs
In your GCP project, enable each API you need:
- Analytics Data API — for GA4 reports
- Analytics Admin API — for listing properties
- Tag Manager API — for GTM access
- Search Console API — for search data
- Google Ads API — for ad campaign data
Click Enable on each page. Takes 10 seconds per API.
Step 3: Create OAuth 2.0 credentials
- Go to APIs & Services → Credentials
- Click Create Credentials → OAuth client ID
- Application type: Web application
- Add
https://developers.google.com/oauthplaygroundas an authorized redirect URI - Save your Client ID and Client Secret
Step 4: Get a refresh token
The refresh token lets you generate access tokens programmatically — no browser login required.
- Go to OAuth Playground
- Click the gear icon (⚙️) in the top right
- Check "Use your own OAuth credentials"
- Enter your Client ID and Client Secret
- In the left panel, select these scopes:
https://www.googleapis.com/auth/analytics.readonlyhttps://www.googleapis.com/auth/analyticshttps://www.googleapis.com/auth/webmasters.readonlyhttps://www.googleapis.com/auth/tagmanager.readonlyhttps://www.googleapis.com/auth/adwords
- Click Authorize APIs and sign in with the Google account that has access to your Analytics/Ads
- Click Exchange authorization code for tokens
- Copy the refresh token — this is your long-lived credential
Important: Sign in with the account that actually owns or has access to your Analytics properties. If your Google Ads MCC is on a different account, you'll need a separate token for that.
Step 5: Refresh your access token
Access tokens expire after 1 hour. Use the refresh token to get a new one:
curl -s -X POST "https://oauth2.googleapis.com/token" \
-d "client_id=YOUR_CLIENT_ID" \
-d "client_secret=YOUR_CLIENT_SECRET" \
-d "refresh_token=YOUR_REFRESH_TOKEN" \
-d "grant_type=refresh_token"
Response:
{
"access_token": "ya29.a0ATko...",
"expires_in": 3599,
"token_type": "Bearer"
}
In production, cache the access token and refresh it when it expires.
Step 6: Query your data
GA4 — Get user and session data
curl -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/YOUR_PROPERTY_ID:runReport" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [{"name": "country"}],
"metrics": [
{"name": "activeUsers"},
{"name": "sessions"},
{"name": "bounceRate"},
{"name": "averageSessionDuration"}
],
"orderBys": [{"metric": {"metricName": "activeUsers"}, "desc": true}],
"limit": 20
}'
This is the query that exposed our bot traffic problem. Sort by country, look for 99%+ bounce rates with near-zero session duration — those are bots.
Search Console — Top search queries
curl -X POST \
"https://www.googleapis.com/webmasters/v3/sites/sc-domain%3Ayourdomain.com/searchAnalytics/query" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"startDate": "2026-02-01",
"endDate": "2026-03-01",
"dimensions": ["query"],
"rowLimit": 20
}'
GTM — List your containers
curl "https://www.googleapis.com/tagmanager/v2/accounts" \
-H "Authorization: Bearer $TOKEN"
Google Ads — Campaign performance
curl -X POST \
"https://googleads.googleapis.com/v19/customers/YOUR_CUSTOMER_ID/googleAds:searchStream" \
-H "Authorization: Bearer $TOKEN" \
-H "developer-token: YOUR_DEV_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"query": "SELECT campaign.name, metrics.impressions, metrics.clicks, metrics.cost_micros FROM campaign WHERE segments.date DURING LAST_30_DAYS"
}'
Note: Google Ads requires a developer token from your MCC account. If your MCC is on a different Google account than your Analytics, you'll need to either add your analytics account as an MCC admin, or use a separate OAuth token.
What to do with the data
Once you have API access, here are the most valuable things to monitor for your chatbot:
1. Bot detection — Query GA4 by country and bounce rate weekly. If you see countries with 99%+ bounce and sub-second durations, add them to your Cloudflare WAF block list.
2. Real engagement tracking — Filter out bot countries and look at average session duration and engaged sessions. For a chatbot, a "session" where someone actually talks to the bot should last 2+ minutes.
3. Channel attribution — If you're running Google Ads to drive traffic to your chatbot, track which campaigns actually produce conversations (not just clicks).
4. Organic discovery — Search Console tells you what people search before finding your bot. This is gold for understanding what problems people want your bot to solve.
Common gotchas
Different Google accounts: Your GA4, Ads, and GTM might be on different Google accounts. Each needs its own OAuth token, or you need to add a shared account as admin on all of them.
API not enabled: Every Google API needs to be explicitly enabled per GCP project. If you get a "has not been used in project" error, click the link in the error message to enable it.
Refresh token expiry: OAuth Playground tokens expire after 7 days by default. For production use, set up a proper OAuth consent screen (even in "testing" mode) to get longer-lived tokens.
Rate limits: GA4 allows 60 requests per minute per property. Search Console allows 200 requests per minute. Batch your queries and cache results.
Automate it
Don't query this manually. Set up a cron job or scheduled function that:
- Refreshes the access token
- Pulls GA4 data by country
- Flags any country with 95%+ bounce rate and 50+ users
- Sends you a Slack/Telegram alert
- Optionally auto-adds WAF rules via the Cloudflare API
We built exactly this for ClawPort-hosted bots. Every agent gets automatic bot traffic detection and WAF rules out of the box.
Need help setting this up for your AI agent? Deploy on ClawPort and get analytics integration included — plus managed hosting, one-click Telegram/WhatsApp deployment, and automatic security hardening.
Ready to deploy your AI agent?
Get started with ClawPort in 60 seconds. No credit card required.
Get Started FreeRelated Articles
Add an AI Chatbot to Your Shopify Store (Without Apps)
How to connect an OpenClaw agent to your Shopify store for product recommendations, order tracking, and FAQ automation — without paying $50/month for a chatbot app.
How to Migrate From ChatGPT Assistants API to OpenClaw
Why developers are moving away from the OpenAI Assistants API, a full feature comparison, and step-by-step migration guide — including conversation history, file search, and function calling.
Track Your AI Agent's Performance (Messages, Costs, Satisfaction)
How to monitor your OpenClaw agent's conversation volume, API costs, user satisfaction scores, and response quality — with dashboard setup and alerting.
Build an AI Appointment Booking Agent (Google Calendar + OpenClaw)
How to build an AI agent that checks availability, books appointments, and sends confirmations using Google Calendar — ideal for service businesses, coaches, and consultants.