Back to blog
tutorialanalyticsgoogle

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.

By ClawPort Team

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:

CountryUsersBounce RateAvg Duration
China49499.8%0.2s
Singapore27499.6%0.1s
Netherlands4532%3m 12s
Germany2841%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.

  1. Go to console.cloud.google.com
  2. Click New Project in the top bar
  3. Name it something like my-chatbot-analytics
  4. Note the project number (you'll need this later)

Step 2: Enable the APIs

In your GCP project, enable each API you need:

Click Enable on each page. Takes 10 seconds per API.

Step 3: Create OAuth 2.0 credentials

  1. Go to APIs & Services → Credentials
  2. Click Create Credentials → OAuth client ID
  3. Application type: Web application
  4. Add https://developers.google.com/oauthplayground as an authorized redirect URI
  5. 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.

  1. Go to OAuth Playground
  2. Click the gear icon (⚙️) in the top right
  3. Check "Use your own OAuth credentials"
  4. Enter your Client ID and Client Secret
  5. In the left panel, select these scopes:
    • https://www.googleapis.com/auth/analytics.readonly
    • https://www.googleapis.com/auth/analytics
    • https://www.googleapis.com/auth/webmasters.readonly
    • https://www.googleapis.com/auth/tagmanager.readonly
    • https://www.googleapis.com/auth/adwords
  6. Click Authorize APIs and sign in with the Google account that has access to your Analytics/Ads
  7. Click Exchange authorization code for tokens
  8. 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:

  1. Refreshes the access token
  2. Pulls GA4 data by country
  3. Flags any country with 95%+ bounce rate and 50+ users
  4. Sends you a Slack/Telegram alert
  5. 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 Free