# Google Cloud Vision API Setup Guide

**Last Updated:** 2026-01-19

## Overview

This guide covers the complete setup and configuration of Google Cloud Vision API for business card OCR functionality in the event lead capture forms.

## Prerequisites

- Google Cloud Platform account
- Access to the same GCP project that ShiftOps uses (Google Maps API key project)
- Billing account enabled (required for Vision API)

**Note:** Vision API uses the same API key as ShiftOps (`v2/api/shiftops.php`), so it must be enabled in the same GCP project that the Google Maps API key belongs to.

## Step 1: Enable Cloud Vision API

1. **Navigate to API Library:**
   - First, identify which GCP project your Google Maps API key belongs to (check in Google Cloud Console → APIs & Services → Credentials)
   - Go to: https://console.cloud.google.com/apis/library/vision.googleapis.com?project=YOUR_PROJECT_ID
   - Or search for "Cloud Vision API" in the API Library
   - **Important:** Use the same project that your Google Maps API key belongs to (the one ShiftOps uses)

2. **Enable the API:**
   - Click "Enable" button
   - Wait for the API to be enabled (usually takes a few seconds)

3. **Verify Enablement:**
   - Check that the API shows as "Enabled" in the API Library
   - Note: It may take a few minutes for changes to propagate

## Step 2: Enable Billing

**Important:** Cloud Vision API requires billing to be enabled, even for free tier usage.

1. **Navigate to Billing:**
   - Go to: https://console.cloud.google.com/billing?project=YOUR_PROJECT_ID
   - Or: APIs & Services → Billing
   - **Important:** Use the same project that your Google Maps API key belongs to

2. **Link Billing Account:**
   - If no billing account is linked, click "Link a billing account"
   - Select or create a billing account
   - Confirm the link

3. **Verify Billing:**
   - Ensure billing account shows as "Active"
   - Check that billing is enabled for the project

## Step 3: Create or Configure API Key

### Option A: Use Existing Google Maps API Key (Default)

The system automatically uses the same Google Maps API key that ShiftOps uses:

1. **Automatic Fallback:** If `GOOGLE_VISION_API_KEY` is not set, the system uses `GOOGLE_MAPS_API_KEY` (same key used by `v2/api/shiftops.php`, `v2/pages/shiftops.php`, etc.)
2. **Consistent Configuration:** This ensures all Google APIs use the same key source for easier management
3. **Default Key:** If no environment variable or constant is set, it uses the default fallback key (same as ShiftOps)
4. **Enable Vision API:** Ensure the API key has Vision API enabled in its restrictions in Google Cloud Console

### Option B: Create New API Key

1. **Navigate to Credentials:**
   - Go to: https://console.cloud.google.com/apis/credentials?project=YOUR_PROJECT_ID
   - **Important:** Use the same project that your Google Maps API key belongs to (the one ShiftOps uses)

2. **Create API Key:**
   - Click "Create Credentials" → "API Key"
   - Copy the generated API key

3. **Configure API Key Restrictions:**
   - Click on the API key to edit
   - Under "API restrictions", select "Restrict key"
   - Check "Cloud Vision API"
   - Optionally set HTTP referrer restrictions (recommended for production)
   - Save changes

## Step 4: Configure API Key in Application

### Method 1: Environment Variable (Recommended)

Set the environment variable in your server configuration:

```bash
export GOOGLE_VISION_API_KEY=your-api-key-here
```

**For Apache (.htaccess):**
```apache
SetEnv GOOGLE_VISION_API_KEY "your-api-key-here"
```

**For PHP-FPM:**
Add to `php-fpm.conf`:
```
env[GOOGLE_VISION_API_KEY] = your-api-key-here
```

### Method 2: PHP Constant

Add to your configuration file (e.g., `v2/config/google-vision.php`):

```php
define('GOOGLE_VISION_API_KEY', 'your-api-key-here');
```

### Method 3: Automatic Fallback to Google Maps API Key (Default)

If neither `GOOGLE_VISION_API_KEY` environment variable nor constant is set, the system automatically uses the same Google Maps API key that ShiftOps uses.

**This is the default behavior** - Vision API uses the same key source as:
- `v2/api/shiftops.php`
- `v2/pages/shiftops.php`
- `v2/pages/shiftops-report.php`

**Note:** Ensure the Google Maps API key has Vision API enabled in its restrictions in Google Cloud Console.

## Step 5: Verify Configuration

### Using Diagnostic Script

Run the diagnostic script to verify your configuration:

```bash
php v2/scripts/ocr-diagnose-api-key.php
```

This will show:
- Which API key source is being used
- Key format validation
- Configuration status

### Using Direct API Test

Test the API directly:

```bash
php v2/scripts/test-vision-api-direct.php
```

This will:
- Test API connectivity
- Verify API enablement
- Check billing status
- Show detailed error messages if issues exist

### Using Python Test Suite

Run comprehensive tests:

```bash
python3 v2/scripts/test-vision-api.py --api-key YOUR_KEY
```

### Using Diagnostics Dashboard

Access the web-based diagnostics:

```
/v2/admin/ocr-diagnostics.php?debug=1
```

This provides:
- API key status
- API connectivity test
- Recent logs
- Troubleshooting guidance

## Step 6: Test OCR Endpoint

### Test with Sample Image

```bash
php v2/scripts/test-ocr-with-image.php /path/to/business-card.jpg
```

### Test via Web Interface

Access the test page:

```
/v2/admin/test-ocr-endpoint.php?debug=1
```

Upload a business card image and verify field extraction.

## Troubleshooting

### Error: "API has not been used in project X before or it is disabled"

**Solution:**
1. **Identify the project:** Run `php v2/scripts/find-api-key-project.php` to find which project your API key belongs to
2. **Enable Cloud Vision API:** Visit the URL shown by the script (or: https://console.cloud.google.com/apis/api/vision.googleapis.com/overview?project=YOUR_PROJECT_NUMBER)
3. Click "Enable"
4. Wait a few minutes for propagation

**Important:** Vision API must be enabled in the **same GCP project** that your Google Maps API key belongs to (the project ShiftOps uses). This ensures consistency across all Google APIs.

### Error: "API requires billing"

**Solution:**
1. Enable billing for the project
2. Visit: https://console.cloud.google.com/billing?project=YOUR_PROJECT_NUMBER
3. Link a billing account
4. Verify billing is active

### Error: "API key not valid" or "Permission denied"

**Solution:**
1. **Check API key restrictions** (Most Common Issue):
   - Go to: https://console.cloud.google.com/apis/credentials?project=YOUR_PROJECT_NUMBER
   - Find your API key and click to edit
   - Check "API restrictions" section
   - **If "Restrict key" is selected:** Ensure "Cloud Vision API" is in the allowed APIs list
   - **If "Don't restrict key":** This should work (check other issues)
   - Save changes and wait 1-2 minutes
   - See [API Key Restrictions Troubleshooting](API_KEY_RESTRICTIONS_TROUBLESHOOTING.md) for detailed guide

2. Verify the key is associated with the correct project
3. Check IAM roles if using service account
4. Ensure Vision API is enabled in the project (even if key allows it)

### Error: "Project number mismatch"

**Issue:** API key is from a different project than expected.

**Solution:**
1. **Option A (Recommended):** Enable Vision API for the project the key belongs to (same project as ShiftOps)
   - Run `php v2/scripts/find-api-key-project.php` to identify the project
   - Enable Vision API in that project
   - This ensures all Google APIs (Maps, Vision) use the same project

2. **Option B:** Create a new API key from the same project that ShiftOps uses
   - Ensure it's from the same GCP project as your Google Maps API key
   - Set as `GOOGLE_VISION_API_KEY` environment variable

3. **Option C:** Use a dedicated `GOOGLE_VISION_API_KEY` environment variable
   - Must be from the same GCP project as ShiftOps for consistency

### API Key Not Found

**Solution:**
1. Set `GOOGLE_VISION_API_KEY` environment variable
2. Or define `GOOGLE_VISION_API_KEY` constant
3. Or ensure `GOOGLE_MAPS_API_KEY` is set (fallback)

## API Key Priority

The system checks for API keys in this order:

1. **Environment Variable:** `GOOGLE_VISION_API_KEY`
2. **PHP Constant:** `GOOGLE_VISION_API_KEY`
3. **Fallback:** `GOOGLE_MAPS_API_KEY` (from project ordio-256916)

## Security Best Practices

1. **Never expose API keys in client-side code**
   - API keys are only used server-side
   - Never include keys in JavaScript or HTML

2. **Use API key restrictions**
   - Restrict to Cloud Vision API only
   - Set HTTP referrer restrictions for web usage
   - Set IP restrictions if possible

3. **Rotate keys regularly**
   - Create new keys periodically
   - Update environment variables/constants
   - Revoke old keys

4. **Monitor usage**
   - Set up billing alerts
   - Monitor API usage in Google Cloud Console
   - Review logs regularly

5. **Use HTTPS only**
   - Ensure all API calls are over HTTPS
   - Never send API keys over unencrypted connections

## Cost Information

- **Free Tier:** First 1,000 images per month free
- **Pricing:** ~$1.50 per 1,000 images after free tier
- **Document Text Detection:** Same pricing as standard OCR

**Monitor costs:**
- Google Cloud Console → Billing → Reports
- Set up budget alerts

## Monitoring and Logging

### Log Files

OCR logs are stored in:
```
v2/logs/ocr-business-card-YYYY-MM-DD.log
```

### Analyze Logs

```bash
php v2/scripts/analyze-ocr-logs.php [date] [--errors-only]
```

### Check Diagnostics

Access diagnostics dashboard:
```
/v2/admin/ocr-diagnostics.php?debug=1
```

## Related Documentation

- [Event Form Implementation](../forms/EVENT_FORM_IMPLEMENTATION.md) - Complete event form guide
- [API Endpoints Core](../../../.cursor/rules/api-endpoints-core.mdc) - API endpoint patterns
- [OCR API Rules](../../../.cursor/rules/ocr-api.mdc) - OCR API development guidelines

## Support

For issues or questions:
1. Check diagnostics dashboard: `/v2/admin/ocr-diagnostics.php?debug=1`
2. Review logs: `v2/logs/ocr-business-card-*.log`
3. Run diagnostic scripts
4. Contact: hady@ordio.com
