# Firebase Cloud Messaging v1 API - Clean Implementation

This repository contains a clean implementation of Firebase Cloud Messaging using only the **v1 API** (no legacy code).

## 🔥 Files Overview

### Core Files (v1 API Only)
- **`config.php`** - Firebase v1 configuration (project ID, service account path)
- **`firebase.php`** - Main FirebaseV1 class with full v1 API implementation
- **`firebase_hybrid.php`** - Simplified Firebase class wrapper (v1 only)
- **`service-account-key.json`** - Your Firebase service account credentials

### Testing & Examples
- **`test_migration.php`** - Test script to verify your v1 setup
- **`test_v1_compliance.php`** - Compliance checker against Firebase documentation
- **`example_usage_v1.php`** - Usage examples for all v1 methods

### Legacy Files (For Reference Only)
- **`firebase_old.php`** - Original legacy implementation (deprecated)
- **`config_old.php`** - Old config with server key (deprecated)

## 🚀 Quick Start

### 1. Configuration
Update `config.php` with your Firebase project details:
```php
define('FIREBASE_PROJECT_ID', 'your-project-id');
define('FIREBASE_SERVICE_ACCOUNT_PATH', __DIR__ . '/service-account-key.json');
```

### 2. Service Account
Download your service account JSON file from:
Firebase Console → Project Settings → Service Accounts → Generate New Private Key

### 3. Basic Usage

#### Option A: Direct FirebaseV1 Class
```php
require_once 'config.php';
require_once 'firebase.php';

$firebase = new FirebaseV1(FIREBASE_PROJECT_ID, FIREBASE_SERVICE_ACCOUNT_PATH);

// Send notification
$result = $firebase->sendNotification($deviceToken, "Title", "Body", $data);

// Send to topic
$result = $firebase->sendNotificationToTopic("news", "Breaking News", "Story text");

// Send data message
$result = $firebase->send($deviceToken, $dataArray);
```

#### Option B: Simplified Firebase Class
```php
require_once 'firebase_hybrid.php';

$firebase = new Firebase(); // Auto-configured for v1

// Same methods available
$result = $firebase->sendNotification($deviceToken, "Title", "Body");
$result = $firebase->sendToTopic("news", $dataArray);
```

### Step 4: Enable FCM v1 API (if needed)
1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Select your project
3. Go to APIs & Services > Library
4. Search for "Firebase Cloud Messaging API"
5. Make sure it's enabled

## Migration Options

### Option 1: Direct Migration (Recommended)
Replace your existing Firebase class usage with the new v1 implementation:

```php
// Old way (Legacy API)
require_once 'firebase.php';
$firebase = new Firebase();
$result = $firebase->send($token, $message);

// New way (v1 API)
require_once 'firebase_v1.php';
require_once 'config_v1.php';
$firebase = new FirebaseV1(FIREBASE_PROJECT_ID, FIREBASE_SERVICE_ACCOUNT_PATH);
$result = $firebase->send($token, $message);
```

### Option 2: Gradual Migration (Hybrid Approach)
Use the hybrid class that supports both APIs:

```php
require_once 'firebase_hybrid.php';

// Use legacy API (during transition)
$firebase = new Firebase(false);
$result = $firebase->send($token, $message);

// Switch to v1 API
$firebase = new Firebase(true, FIREBASE_PROJECT_ID, FIREBASE_SERVICE_ACCOUNT_PATH);
$result = $firebase->send($token, $message);
```

## Message Format Changes

### Legacy Format:
```php
// Single device
$message = array(
    'to' => $deviceToken,
    'data' => array('key' => 'value')
);

// Topic
$message = array(
    'to' => '/topics/news',
    'notification' => array(
        'title' => 'Title',
        'body' => 'Body'
    )
);
```

### v1 Format:
```php
// Single device
$message = array(
    'message' => array(
        'token' => $deviceToken,
        'data' => array('key' => 'value')
    )
);

// Topic
$message = array(
    'message' => array(
        'topic' => 'news',  // No '/topics/' prefix
        'notification' => array(
            'title' => 'Title',
            'body' => 'Body'
        )
    )
);
```

## Usage Examples

### Send Data Message
```php
$firebase = new FirebaseV1(FIREBASE_PROJECT_ID, FIREBASE_SERVICE_ACCOUNT_PATH);
$result = $firebase->send($deviceToken, array(
    'title' => 'Test',
    'custom_data' => 'value'
));
```

### Send Notification
```php
$result = $firebase->sendNotification(
    $deviceToken,
    'Breaking News',
    'Something important happened',
    array('story_id' => '12345')
);
```

### Send to Topic
```php
$result = $firebase->sendNotificationToTopic(
    'news',
    'Topic Update',
    'New content available',
    array('category' => 'general')
);
```

### Send to Multiple Devices
```php
$tokens = array('token1', 'token2', 'token3');
$results = $firebase->sendMultiple($tokens, array(
    'bulk_message' => 'true',
    'batch_id' => 'batch_001'
));
```

## Security Best Practices

1. **Protect Service Account File**: Never commit it to version control
2. **Use Environment Variables**: Store path in environment variable
3. **Restrict File Permissions**: Make service account file readable only by your app
4. **Monitor Token Usage**: Implement logging for authentication failures

### Environment Variable Setup:
```bash
# Linux/Mac
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"

# Windows
set GOOGLE_APPLICATION_CREDENTIALS=C:\path\to\service-account-key.json
```

Then in config:
```php
define('FIREBASE_SERVICE_ACCOUNT_PATH', getenv('GOOGLE_APPLICATION_CREDENTIALS'));
```

## Troubleshooting

### Common Issues:

1. **"Service account file not found"**
   - Check file path in config
   - Verify file exists and is readable

2. **"Authentication failed"**
   - Verify service account has FCM permissions
   - Check project ID is correct

3. **"Invalid project ID"**
   - Confirm project ID in Firebase Console
   - Check for typos in config

4. **"FCM API not enabled"**
   - Enable Firebase Cloud Messaging API in Google Cloud Console

### Testing Your Setup:
```php
// Test authentication
try {
    $firebase = new FirebaseV1(FIREBASE_PROJECT_ID, FIREBASE_SERVICE_ACCOUNT_PATH);
    echo "✅ Firebase v1 initialized successfully\n";
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
```

## Performance Considerations

1. **Token Caching**: Access tokens are cached for 55 minutes
2. **Batch Processing**: For multiple devices, consider queuing/batching
3. **Error Handling**: Implement retry logic for failed requests
4. **Rate Limiting**: Respect FCM rate limits (1 million/minute)

## Migration Checklist

- [ ] Get Firebase Project ID
- [ ] Download service account JSON
- [ ] Update configuration files
- [ ] Test authentication
- [ ] Update message format
- [ ] Test sending to single device
- [ ] Test sending to topics
- [ ] Test multiple device sending
- [ ] Update error handling
- [ ] Deploy and monitor

## Support

- [Firebase Documentation](https://firebase.google.com/docs/cloud-messaging)
- [Migration Guide](https://firebase.google.com/docs/cloud-messaging/migrate-v1)
- [FCM v1 API Reference](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages)

---

**Note**: Keep your legacy implementation as backup until you've fully tested the v1 migration in production.
