Files
AdPlatform-Server/GoogleApi/GOOGLE_ADS_SETUP.md
2026-02-03 15:04:37 -08:00

260 lines
8.3 KiB
Markdown

# Google Ads API Configuration Guide
## Overview
This document describes how to configure the GoogleApi service to connect to the real Google Ads API. The service supports both **emulated mode** (for testing without Google credentials) and **real API mode**.
## Configuration Levels
| Level | Storage | Examples |
|-------|---------|----------|
| **Platform secrets** | Azure Key Vault | Developer token, OAuth client secret |
| **Platform config** | App Settings / appsettings.json | API version, timeouts |
| **Per-account credentials** | Database (tbGoogleCredential) | Refresh tokens per linked account |
## Quick Start (Test Account)
1. Create a Google Ads test manager account
2. Get a developer token (works immediately for test accounts)
3. Set up OAuth credentials in Google Cloud Console
4. Configure the environment variables below
## Environment Variables for Azure Container Apps
> **Note:** This service runs **server-to-server**. There is **no interactive OAuth UI** at runtime.
> Generate the refresh token once (out-of-band) and store it securely (Key Vault / secrets).
### GoogleApi Service
```bash
# ==========================================
# Core Settings
# ==========================================
# Enable real Google Ads API calls (default: false)
GoogleAds__EnableRealApi=true
# API version (default: v22)
GoogleAds__ApiVersion=v22
# ==========================================
# Authentication - Developer Token
# Required for all API calls
# ==========================================
# Your developer token from Google Ads API Center
# Format: 22-character alphanumeric string
# Get from: https://ads.google.com/aw/apicenter
GoogleAds__DeveloperToken=YOUR_DEVELOPER_TOKEN_HERE
# ==========================================
# Authentication - OAuth 2.0
# Required for authenticating API requests
# ==========================================
# OAuth Client ID from Google Cloud Console
GoogleAds__OAuth__ClientId=YOUR_CLIENT_ID.apps.googleusercontent.com
# OAuth Client Secret from Google Cloud Console
# SENSITIVE - Use Key Vault reference in production
GoogleAds__OAuth__ClientSecret=YOUR_CLIENT_SECRET
# Refresh token for platform-level access
# Generated via OAuth flow or gcloud CLI
# SENSITIVE - Use Key Vault reference in production
GoogleAds__OAuth__RefreshToken=YOUR_REFRESH_TOKEN
# ==========================================
# Manager Account (Optional)
# Required if accessing client accounts under a manager
# ==========================================
# Default login customer ID (manager account)
# Format: 1234567890 (no dashes)
GoogleAds__DefaultLoginCustomerId=1234567890
# ==========================================
# Internal Authentication
# For Gateway -> GoogleApi communication
# ==========================================
# Shared secret for internal API authentication
# SENSITIVE - Use Key Vault reference
GOOGLE_INTERNAL_KEY=your-secure-internal-key
# ==========================================
# Optional Settings
# ==========================================
# HTTP timeout in seconds (default: 60)
GoogleAds__TimeoutSeconds=60
# Max retry attempts (default: 3)
GoogleAds__MaxRetries=3
```
### Azure Key Vault References
For sensitive values, use Key Vault references in Azure Container Apps:
```bash
# Instead of plain values:
GoogleAds__DeveloperToken=@Microsoft.KeyVault(SecretUri=https://your-vault.vault.azure.net/secrets/GoogleAdsDeveloperToken/)
GoogleAds__OAuth__ClientSecret=@Microsoft.KeyVault(SecretUri=https://your-vault.vault.azure.net/secrets/GoogleAdsClientSecret/)
GoogleAds__OAuth__RefreshToken=@Microsoft.KeyVault(SecretUri=https://your-vault.vault.azure.net/secrets/GoogleAdsRefreshToken/)
GOOGLE_INTERNAL_KEY=@Microsoft.KeyVault(SecretUri=https://your-vault.vault.azure.net/secrets/GoogleInternalKey/)
```
## Step-by-Step Setup
### 1. Create Google Ads Manager Account
1. Go to https://ads.google.com/aw/apicenter
2. Sign in with a Google account NOT linked to production ads
3. Create a new manager account
4. For test accounts, click "Create a test manager account" link
### 2. Get Developer Token
1. In your manager account, go to **Tools & Settings > API Center**
2. Your developer token will be displayed
3. For test accounts: Token works immediately
4. For production: Apply for Basic Access (takes a few days)
### 3. Create Google Cloud Project
1. Go to https://console.cloud.google.com
2. Create a new project (or use existing)
3. Enable the **Google Ads API**:
- Go to APIs & Services > Library
- Search "Google Ads API"
- Click Enable
### 4. Create OAuth Credentials
1. Go to APIs & Services > Credentials
2. Click **Create Credentials > OAuth client ID**
3. Application type: **Desktop app** (for initial testing)
4. Download the JSON file
5. Note the Client ID and Client Secret
### 5. Generate Refresh Token
Option A: Using gcloud CLI
```bash
# Install gcloud CLI if not installed
gcloud auth login --cred-file=path/to/client_secret.json
gcloud auth print-access-token \
--scopes='https://www.googleapis.com/auth/adwords'
```
Option B: Using OAuth Playground
1. Go to https://developers.google.com/oauthplayground/
2. Click gear icon > Use your own credentials
3. Enter your Client ID and Secret
4. Select Google Ads API scope: `https://www.googleapis.com/auth/adwords`
5. Click Authorize APIs, sign in
6. Click "Exchange authorization code for tokens"
7. Copy the Refresh Token
### 6. Create Test Client Account
1. In your test manager account
2. Click Accounts > + > Create new account
3. This creates a test client account under your manager
4. Note the Customer ID (format: XXX-XXX-XXXX)
### 7. Configure Azure Container App
In Azure Portal > Container Apps > Your GoogleApi App > Settings > Environment Variables:
Add each variable from the list above, using Key Vault references for sensitive values.
## Testing the Configuration
### Check Health Endpoint
```bash
curl https://your-googleapi-url/health
```
Expected response:
```json
{
"service": "GoogleApi",
"status": "healthy",
"config": {
"realApiEnabled": true,
"apiVersion": "v18",
"developerTokenSet": true,
"oauthConfigured": true,
"defaultLoginCustomerId": "1234567890"
}
}
```
### Test API Call (via Gateway)
```bash
curl -X POST https://your-gateway-url/api/execution/request \
-H "Content-Type: application/json" \
-H "X-Dev-ClientId: test-client" \
-H "X-Dev-TenantId: 1234567890" \
-d '{
"operation": "ListAccessibleCustomers",
"payload": {}
}'
```
## Credential Flow Diagram
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Gateway │────▶│ GoogleApi │────▶│ Google Ads │
└─────────────┘ └─────────────┘ │ API │
│ └─────────────┘
┌──────┴──────┐
│ │
┌─────▼─────┐ ┌────▼────┐
│ Config │ │ Database │
│(env vars) │ │(per-acct)│
└───────────┘ └──────────┘
Config provides: Database provides:
- Developer Token - Per-account refresh tokens
- OAuth Client ID/Secret - Account-specific credentials
- Default refresh token - Linked customer IDs
```
## Troubleshooting
### "UNAUTHENTICATED" Error
- Check developer token is correct
- Verify OAuth credentials
- Ensure refresh token hasn't expired
### "PERMISSION_DENIED" Error
- Developer token may not be approved for production
- Verify account access permissions
- Check login-customer-id is correct
### "INVALID_CUSTOMER_ID" Error
- Customer ID format should be 10 digits, no dashes
- Verify account exists and is accessible
### Token Exchange Fails
- Client ID/Secret mismatch
- Refresh token was revoked
- OAuth consent was withdrawn
## Security Best Practices
1. **Never commit secrets** to source control
2. **Use Azure Key Vault** for all sensitive values
3. **Rotate refresh tokens** periodically
4. **Audit API access** via tbAdpApiLog
5. **Limit developer token access** - one token per application
6. **Use test accounts** for development and testing