# Google Sheets Integration - Setup Guide

This guide walks you through setting up automatic order syncing to Google Sheets. Each seller can connect their own Google account and all their orders will sync to their personal Google Sheet in real-time.

## What You Get

- Automatic order syncing for each seller
- Real-time backup of order data
- Each seller gets their own Google Sheet
- Complete order history with customer details
- Tracking numbers, notes, and product information
- Easy to export and analyze in Excel/Google Sheets

## Requirements

Before starting, make sure you have:

- PHP 7.4 or higher
- Composer installed
- A Google account (free Gmail account works)
- Access to Google Cloud Console

## Installation Steps

### 1. Install Google API Library

The system needs Google's PHP library to communicate with Google Sheets. Install it using Composer:

```bash
composer require google/apiclient:^2.0
```

If the installation times out, try increasing the timeout:

```bash
COMPOSER_PROCESS_TIMEOUT=900 composer require google/apiclient:^2.0
```

Or use this alternative method:

```bash
composer config --global process-timeout 900
composer require google/apiclient:^2.0 --no-interaction --prefer-dist
```

### 2. Database Setup

Run the migration to add Google Sheets fields to your database:

```bash
php artisan migrate
```

This adds these columns to the users table:
- `google_sheet_id` - Stores the spreadsheet ID
- `google_access_token` - OAuth access token (encrypted)
- `google_refresh_token` - OAuth refresh token (encrypted)
- `google_token_expires_at` - Token expiration time
- `google_sheets_sync_enabled` - On/off toggle
- `google_sheets_last_sync` - Last sync timestamp
- `google_email` - Connected Gmail address

### 3. Google Cloud Console Setup

You need to create a Google Cloud project and get OAuth credentials. Don't worry, it sounds complicated but it's straightforward. Follow these steps:

#### Create a New Project

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Sign in with your Google account (any Gmail works)
3. Click "Select a Project" dropdown at the top
4. Click "New Project"
5. Enter a project name (e.g., "Multistore Sync")
6. Click "Create" and wait a few seconds

#### Enable the Required APIs

Google needs to know which services you'll use:

1. In the left sidebar, click "APIs & Services" > "Library"
2. Search for "Google Sheets API" and click it
3. Click "Enable"
4. Go back to the Library (click "APIs & Services" > "Library" again)
5. Search for "Google Drive API" and click it
6. Click "Enable"

#### Configure OAuth Consent Screen

This is the screen users see when connecting their Google account:

1. Go to "APIs & Services" > "OAuth consent screen"
2. Select "External" (unless you have a Google Workspace account)
3. Click "Create"
4. Fill in the required fields:
   - **App name:** Multistore Order Sync (or your app name)
   - **User support email:** Your email address
   - **Developer contact:** Your email address
5. Click "Save and Continue"
6. On the Scopes screen, click "Add or Remove Scopes"
7. Add these scopes (paste them in the manual entry box if needed):
   - `https://www.googleapis.com/auth/spreadsheets`
   - `https://www.googleapis.com/auth/drive.file`
   - `https://www.googleapis.com/auth/userinfo.email`
8. Click "Update" then "Save and Continue"
9. Skip the "Test Users" section (or add yourself for testing)
10. Click "Save and Continue"
11. Review and click "Back to Dashboard"

#### Create OAuth Credentials

Now you'll get the client ID and secret needed for your app:

1. Go to "APIs & Services" > "Credentials"
2. Click "Create Credentials" > "OAuth client ID"
3. Select "Web application" as the application type
4. Enter a name (e.g., "Multistore Web App")
5. Under "Authorized redirect URIs", click "Add URI"
6. Add your callback URL:
   - **Local development:** `http://localhost/multistore/public/auth/google/callback`
   - **Production:** `https://yourdomain.com/auth/google/callback`

   You can add multiple URLs for different environments.

7. Click "Create"
8. Copy the Client ID and Client Secret (you'll need these next)

### 4. Configure Your Application

Add your Google credentials to the `.env` file:

```env
# Google OAuth Configuration
GOOGLE_CLIENT_ID=your-client-id-here.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret-here
GOOGLE_REDIRECT_URI=https://yourdomain.com/auth/google/callback
```

Replace the values with your actual credentials from the previous step.

**Important:** Different environments need different redirect URIs:
- **Local:** `http://localhost/multistore/public/auth/google/callback`
- **Production:** `https://yourdomain.com/auth/google/callback`

### 5. Clear Configuration Cache

After updating `.env`, clear Laravel's config cache:

```bash
php artisan config:clear
php artisan cache:clear
```

### 6. Set Up Queue Workers

Google Sheets syncing happens in the background using Laravel queues. You need a queue worker running at all times.

**For Development (localhost):**

```bash
php artisan queue:work database --sleep=3 --tries=3
```

Keep this terminal window open. Orders will sync as long as this is running.

**For Production:**

Use Supervisor to keep the queue worker running permanently. See the [Queue Workers Guide](../../deployment/queue-workers.md) for detailed instructions.

## Testing the Integration

Now let's test if everything works:

1. Log in as a seller account
2. Go to Settings > Google Sheets
3. Click "Connect Google Account"
4. You'll be redirected to Google
5. Sign in and grant permissions
6. You'll be redirected back to your app
7. A new Google Sheet will be created automatically
8. Create a test order
9. Check your Google Sheet - the order should appear within a few seconds

## What's Synced?

Each order row in Google Sheets contains:

- Global Order ID (unique identifier)
- Order Number
- Date Created
- Customer Name, Phone, Email
- Shipping Address (full address breakdown)
- Products, SKUs, Quantities
- Order Total, Currency
- Payment Method
- Order Status
- Tracking Number
- Store Name
- Customer Notes (from checkout)

## Multi-Seller Support

Each seller operates completely independently:

- **Seller A** connects their Gmail → gets their own sheet → only sees their orders
- **Seller B** connects their Gmail → gets their own sheet → only sees their orders
- No cross-contamination of data
- Each seller manages their own Google connection

## Disconnecting

If a seller wants to disconnect:

1. Go to Settings > Google Sheets
2. Click "Disconnect Google Account"
3. Their sheet remains in Google Drive (not deleted)
4. New orders stop syncing
5. They can reconnect later and continue using the same sheet

## Common Issues

**"Failed to fetch access token"**
- Check your Client ID and Secret in `.env`
- Make sure the redirect URI matches exactly
- Clear config cache: `php artisan config:clear`

**Orders not syncing**
- Check if queue worker is running
- Check Laravel logs: `storage/logs/laravel.log`
- Make sure `google_sheets_sync_enabled` is true for the user

**"Insufficient Permission" errors**
- Make sure you enabled both Google Sheets API and Google Drive API
- Check that all three scopes were added in OAuth consent screen

For more troubleshooting help, see [Troubleshooting Guide](troubleshooting.md).

## Next Steps

- [Learn about all the features](features.md)
- [View change history](changelog.md)
- [Troubleshoot common issues](troubleshooting.md)

---

**Last updated:** 2025-11-21
