# WhatsApp Integration Service - Documentation

## 📋 Table of Contents

1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Installation & Setup](#installation--setup)
4. [Core Components](#core-components)
5. [Usage Guide](#usage-guide)
6. [Testing](#testing)
7. [Configuration Reference](#configuration-reference)
8. [Error Handling](#error-handling)
9. [T2 Provider Details](#t2-provider-details)
10. [Best Practices](#best-practices)
11. [Troubleshooting](#troubleshooting)

---

## 🔍 Overview

### What Is This Service?

The WhatsApp Integration Service is a reusable, provider-agnostic abstraction layer for sending WhatsApp messages through various messaging providers. Currently implemented with support for T2 Communicate platform.

### Purpose

This service provides a clean, consistent API for sending WhatsApp notifications to customers, decoupling the application logic from specific provider implementations.

### Key Features

- **Provider Agnostic**: Switch between WhatsApp providers (T2, Twilio, etc.) without code changes
- **Type-Safe DTOs**: Validated data structures for messages and templates
- **Automatic Authentication**: Handles token management and renewal transparently
- **Comprehensive Error Handling**: Detailed exceptions with contextual information
- **Fully Tested**: Includes unit tests and testing command
- **Well Documented**: Clear PHPDoc comments and usage examples

---

## 🏗️ Architecture

### Component Overview

```
┌─────────────────────────────────────────────────────────┐
│                    Application Layer                    │
│         (Controllers, Jobs, Event Listeners)            │
└─────────────────────────┬───────────────────────────────┘
                          │
                          ↓
┌─────────────────────────────────────────────────────────┐
│                  WhatsAppService                        │
│              (Main Public Interface)                    │
└─────────────────────────┬───────────────────────────────┘
                          │
                          ↓
┌─────────────────────────────────────────────────────────┐
│            WhatsAppProviderInterface                    │
│                  (Contract)                             │
└─────────────────────────┬───────────────────────────────┘
                          │
                          ↓
┌─────────────────────────────────────────────────────────┐
│                   T2Provider                            │
│         (T2 Communicate Implementation)                 │
└─────────────────────────┬───────────────────────────────┘
                          │
                          ↓
┌─────────────────────────────────────────────────────────┐
│              T2 Communicate API                         │
│         https://communicateapi.t2.sa/api                │
└─────────────────────────────────────────────────────────┘
```

### Directory Structure

```
app/
├── Services/
│   └── WhatsApp/
│       ├── WhatsAppService.php
│       ├── Contracts/
│       │   └── WhatsAppProviderInterface.php
│       ├── Providers/
│       │   └── T2Provider.php
│       ├── DTOs/
│       │   ├── WhatsAppMessage.php
│       │   └── WhatsAppTemplate.php
│       └── Exceptions/
│           └── WhatsAppException.php
│
├── Console/
│   └── Commands/
│       └── WhatsAppTestCommand.php
│
config/
└── whatsapp.php

tests/
└── Unit/
    └── Services/
        └── WhatsApp/
            ├── WhatsAppServiceTest.php
            └── Providers/
                └── T2ProviderTest.php
```

---

## 📦 Installation & Setup

### Step 1: File Installation

Copy all service files to the VOM Subscription project following the directory structure above.

### Step 2: Configuration File

Ensure `config/whatsapp.php` exists with the following structure:

```php
<?php

return [
    'default' => env('WHATSAPP_PROVIDER', 't2'),

    'providers' => [
        't2' => [
            'base_url' => env('T2_WHATSAPP_BASE_URL', 'https://communicateapi.t2.sa/api'),
            'email' => env('T2_WHATSAPP_EMAIL'),
            'password' => env('T2_WHATSAPP_PASSWORD'),
            'timeout' => env('T2_WHATSAPP_TIMEOUT', 30),
            'token_cache_key' => 't2_whatsapp_access_token',
            'token_expiry_buffer' => 300,
        ],
    ],

    'default_language' => env('WHATSAPP_DEFAULT_LANGUAGE', 'ar'),
];
```

### Step 3: Environment Variables

Add to `.env`:

```env
# WhatsApp Configuration
WHATSAPP_PROVIDER=t2
WHATSAPP_DEFAULT_LANGUAGE=ar

# T2 Communicate Credentials
T2_WHATSAPP_BASE_URL=https://communicateapi.t2.sa/api
T2_WHATSAPP_EMAIL=your-email@example.com
T2_WHATSAPP_PASSWORD=your-password
T2_WHATSAPP_TIMEOUT=30
```

### Step 4: Verify Installation

Run the test command:

```bash
php artisan whatsapp:test --type=config
```

Expected output:
```
✅ WhatsApp service is properly configured
```

---

## 🧩 Core Components

### 1. WhatsAppService

**Location**: `app/Services/WhatsApp/WhatsAppService.php`

**Purpose**: Main entry point for sending WhatsApp messages. Provides a clean, provider-agnostic API.

**Public Methods**:

```php
// Send a plain text message
public function sendMessage(WhatsAppMessage $message): array

// Send a templated message
public function sendTemplate(WhatsAppTemplate $template): array

// Check if provider is configured
public function isConfigured(): bool
```

**Usage Example**:

```php
use App\Services\WhatsApp\WhatsAppService;

$service = new WhatsAppService();
$result = $service->sendMessage($message);
```

---

### 2. WhatsAppProviderInterface

**Location**: `app/Services/WhatsApp/Contracts/WhatsAppProviderInterface.php`

**Purpose**: Contract that all WhatsApp providers must implement. Ensures consistency across different provider implementations.

**Required Methods**:

```php
public function sendMessage(WhatsAppMessage $message): array;
public function sendTemplate(WhatsAppTemplate $template): array;
public function isConfigured(): bool;
```

**Why It Exists**: Allows easy switching between providers (T2, Twilio, direct WhatsApp API) without changing application code.

---

### 3. T2Provider

**Location**: `app/Services/WhatsApp/Providers/T2Provider.php`

**Purpose**: Implementation of WhatsApp integration for T2 Communicate platform.

**Key Responsibilities**:
- Authenticates with T2 API
- Manages JWT token lifecycle (caching, auto-renewal)
- Formats messages according to T2 specifications
- Handles T2-specific error responses

**Important Details**:
- Tokens are cached for 55 minutes (T2 tokens expire after 1 hour)
- Phone numbers are automatically formatted (removes `+` prefix)
- Template messages use T2's special syntax: `##template_name##param1##param2##`

---

### 4. DTOs (Data Transfer Objects)

#### WhatsAppMessage

**Location**: `app/Services/WhatsApp/DTOs/WhatsAppMessage.php`

**Purpose**: Represents a plain text WhatsApp message with validation.

**Properties**:
```php
public readonly string $to;           // E.164 format: +966501234567
public readonly string $body;         // Message content
public readonly ?string $language;    // Default: 'ar'
public readonly ?array $metadata;     // Additional tracking data
```

**Validation**: Automatically validates phone number format (E.164). Throws `InvalidArgumentException` if invalid.

**Example**:
```php
$message = new WhatsAppMessage(
    to: '+966501234567',
    body: 'مرحباً! اشتراكك سينتهي قريباً.',
    language: 'ar',
    metadata: ['tenant_id' => 123]
);
```

#### WhatsAppTemplate

**Location**: `app/Services/WhatsApp/DTOs/WhatsAppTemplate.php`

**Purpose**: Represents a templated WhatsApp message with variable substitution.

**Properties**:
```php
public readonly string $to;              // E.164 format
public readonly string $templateName;    // Template identifier
public readonly array $variables;        // Template variables
public readonly ?string $language;       // Default: 'ar'
public readonly ?array $metadata;        // Additional tracking data
```

**Example**:
```php
$template = new WhatsAppTemplate(
    to: '+966501234567',
    templateName: 'subscription_expiring',
    variables: ['أحمد', '7 أيام', '500 ريال'],
    language: 'ar'
);
```

---

### 5. WhatsAppException

**Location**: `app/Services/WhatsApp/Exceptions/WhatsAppException.php`

**Purpose**: Custom exception for WhatsApp-related errors with context.

**Key Features**:
- Stores additional context (API responses, request details)
- Factory methods for common error types

**Usage**:
```php
try {
    $service->sendMessage($message);
} catch (WhatsAppException $e) {
    Log::error('WhatsApp error: ' . $e->getMessage());
    Log::error('Context: ' . json_encode($e->getContext()));
}
```

---

## 📖 Usage Guide

### Basic Usage: Send Plain Message

```php
<?php

use App\Services\WhatsApp\WhatsAppService;
use App\Services\WhatsApp\DTOs\WhatsAppMessage;
use App\Services\WhatsApp\Exceptions\WhatsAppException;
use Illuminate\Support\Facades\Log;

// Create service instance
$whatsapp = new WhatsAppService();

// Create message
$message = new WhatsAppMessage(
    to: '+966501234567',
    body: 'مرحباً! هذه رسالة تجريبية من نظام VOM.',
    language: 'ar',
    metadata: [
        'tenant_id' => 123,
        'notification_type' => 'test'
    ]
);

// Send message
try {
    $result = $whatsapp->sendMessage($message);
    
    Log::info('Message sent', [
        'message_id' => $result['messageId'],
        'status' => $result['status']
    ]);
    
} catch (WhatsAppException $e) {
    Log::error('Failed to send message', [
        'error' => $e->getMessage(),
        'context' => $e->getContext()
    ]);
}
```

---

### Advanced Usage: Send Template Message

```php
<?php

use App\Services\WhatsApp\WhatsAppService;
use App\Services\WhatsApp\DTOs\WhatsAppTemplate;
use App\Services\WhatsApp\Exceptions\WhatsAppException;

$whatsapp = new WhatsAppService();

// Assuming template exists in T2 with format:
// "مرحباً {{1}}! اشتراكك سينتهي خلال {{2}}. قيمة التجديد: {{3}}"

$template = new WhatsAppTemplate(
    to: '+966501234567',
    templateName: 'subscription_expiring',
    variables: [
        'أحمد محمد',      // {{1}} - Customer name
        '7 أيام',         // {{2}} - Days remaining
        '500 ريال'        // {{3}} - Renewal amount
    ],
    language: 'ar',
    metadata: [
        'tenant_id' => 123,
        'subscription_id' => 456
    ]
);

try {
    $result = $whatsapp->sendTemplate($template);
    
    Log::info('Template sent', [
        'message_id' => $result['messageId']
    ]);
    
} catch (WhatsAppException $e) {
    Log::error('Template send failed', [
        'error' => $e->getMessage()
    ]);
}
```

---

### Usage in Laravel Jobs (Recommended)

For production use, always queue WhatsApp messages:

```php
<?php

namespace App\Jobs;

use App\Services\WhatsApp\WhatsAppService;
use App\Services\WhatsApp\DTOs\WhatsAppMessage;
use App\Services\WhatsApp\Exceptions\WhatsAppException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SendWhatsAppNotificationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;
    public $backoff = [60, 300, 900];

    public function __construct(
        public string $phone,
        public string $messageBody,
        public string $language = 'ar',
        public ?array $metadata = null
    ) {}

    public function handle(WhatsAppService $whatsapp): void
    {
        $message = new WhatsAppMessage(
            to: $this->phone,
            body: $this->messageBody,
            language: $this->language,
            metadata: $this->metadata
        );

        try {
            $result = $whatsapp->sendMessage($message);
            
            Log::info('WhatsApp notification sent', [
                'phone' => $this->phone,
                'message_id' => $result['messageId']
            ]);
            
        } catch (WhatsAppException $e) {
            Log::error('WhatsApp notification failed', [
                'phone' => $this->phone,
                'error' => $e->getMessage(),
                'attempt' => $this->attempts()
            ]);
            
            throw $e; // Let Laravel handle retry
        }
    }
}
```

**Dispatching the job**:

```php
SendWhatsAppNotificationJob::dispatch(
    phone: '+966501234567',
    messageBody: 'اشتراكك سينتهي قريباً!',
    language: 'ar',
    metadata: ['tenant_id' => 123]
);
```

---

### Usage in Controllers

```php
<?php

namespace App\Http\Controllers;

use App\Services\WhatsApp\WhatsAppService;
use App\Services\WhatsApp\DTOs\WhatsAppMessage;
use App\Services\WhatsApp\Exceptions\WhatsAppException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function __construct(
        private WhatsAppService $whatsapp
    ) {}

    public function sendNotification(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'phone' => 'required|regex:/^\+[1-9]\d{1,14}$/',
            'message' => 'required|string|max:4096',
        ]);

        $message = new WhatsAppMessage(
            to: $validated['phone'],
            body: $validated['message'],
            language: 'ar'
        );

        try {
            $result = $this->whatsapp->sendMessage($message);
            
            return response()->json([
                'success' => true,
                'message_id' => $result['messageId']
            ]);
            
        } catch (WhatsAppException $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
```

---

## 🧪 Testing

### Test Command

The service includes a comprehensive testing command for validation and debugging.

**Available Options**:

```bash
# Test configuration only
php artisan whatsapp:test --type=config

# Test plain message sending
php artisan whatsapp:test --type=message --phone=+966501234567

# Test template message sending
php artisan whatsapp:test --type=template --phone=+966501234567

# Run all tests
php artisan whatsapp:test --type=all --phone=+966501234567

# Dry run (show what would be sent without sending)
php artisan whatsapp:test --dry-run
```

**Example Output**:

```
🚀 WhatsApp Service Test Suite
================================

🔧 Testing Configuration...
✅ WhatsApp service is properly configured

📋 Current Configuration:
+-----------------+------------------------------------------+
| Setting         | Value                                    |
+-----------------+------------------------------------------+
| Provider        | t2                                       |
| Base URL        | https://communicateapi.t2.sa/api        |
| Email           | ✓ Set                                    |
| Password        | ✓ Set                                    |
| Timeout         | 30s                                      |
| Default Language| ar                                       |
+-----------------+------------------------------------------+

📱 Testing Plain Message...
📤 Preparing to send message to: +966501234567
💬 Message: مرحباً! هذه رسالة تجريبية من نظام VOM Subscription. 🚀
✅ Plain message sent successfully!

✅ All tests completed successfully!
```

---

### Unit Tests

**Running Tests**:

```bash
# Run all WhatsApp tests
php artisan test --filter=WhatsApp

# Run specific test class
php artisan test tests/Unit/Services/WhatsApp/WhatsAppServiceTest.php

# Run with coverage
php artisan test --filter=WhatsApp --coverage
```

**Example Unit Test**:

```php
<?php

namespace Tests\Unit\Services\WhatsApp;

use App\Services\WhatsApp\WhatsAppService;
use App\Services\WhatsApp\DTOs\WhatsAppMessage;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class WhatsAppServiceTest extends TestCase
{
    public function test_send_message_successfully(): void
    {
        Http::fake([
            'communicateapi.t2.sa/api/auth/login' => Http::response([
                'token' => 'fake-token',
                'expireInSeconds' => 3600,
            ], 200),
            
            'communicateapi.t2.sa/api/message/send-custom' => Http::response([
                'messageId' => 'msg-123',
                'status' => 'sent',
            ], 200),
        ]);

        $service = new WhatsAppService();
        
        $message = new WhatsAppMessage(
            to: '+966501234567',
            body: 'Test message'
        );

        $result = $service->sendMessage($message);

        $this->assertArrayHasKey('messageId', $result);
        $this->assertEquals('msg-123', $result['messageId']);
    }
}
```

---

## ⚙️ Configuration Reference

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `WHATSAPP_PROVIDER` | Yes | `t2` | Provider name (currently only `t2` supported) |
| `WHATSAPP_DEFAULT_LANGUAGE` | No | `ar` | Default language for messages |
| `T2_WHATSAPP_BASE_URL` | Yes | `https://communicateapi.t2.sa/api` | T2 API base URL |
| `T2_WHATSAPP_EMAIL` | Yes | - | T2 account email |
| `T2_WHATSAPP_PASSWORD` | Yes | - | T2 account password |
| `T2_WHATSAPP_TIMEOUT` | No | `30` | API request timeout (seconds) |

### Configuration File

**Location**: `config/whatsapp.php`

**Key Settings**:

- `default`: Default provider to use
- `providers.t2`: T2-specific configuration
- `providers.t2.token_cache_key`: Cache key for storing JWT token
- `providers.t2.token_expiry_buffer`: Seconds before expiry to refresh token (default: 300)
- `default_language`: Default language code for messages

---

## 🚨 Error Handling

### Exception Hierarchy

```
Exception
  └── WhatsAppException
```

### Common Errors

| Error Message | HTTP Code | Cause | Solution |
|--------------|-----------|-------|----------|
| `T2 WhatsApp provider is not properly configured` | - | Missing credentials in `.env` | Set `T2_WHATSAPP_EMAIL` and `T2_WHATSAPP_PASSWORD` |
| `Authentication failed: The email or password is incorrect` | 401 | Invalid T2 credentials | Verify email/password with T2 support |
| `Invalid phone number format` | - | Phone not in E.164 format | Use format: `+966501234567` |
| `You need to use a pre-approved WhatsApp Message Template` | 400 | No active session, template required | Use approved template or ensure user messaged first |
| `Resource not found` | 404 | Contact doesn't exist in T2 | Create contact via T2 API first |

### Error Handling Best Practices

```php
use App\Services\WhatsApp\Exceptions\WhatsAppException;
use Illuminate\Support\Facades\Log;

try {
    $result = $whatsapp->sendMessage($message);
} catch (WhatsAppException $e) {
    // Log error with full context
    Log::error('WhatsApp error occurred', [
        'error' => $e->getMessage(),
        'code' => $e->getCode(),
        'context' => $e->getContext(),
        'phone' => $message->to,
    ]);
    
    // Handle different error types
    if ($e->getCode() === 401) {
        // Authentication error - may resolve on retry
        throw $e;
    } elseif ($e->getCode() === 404) {
        // Resource not found - don't retry
        Log::alert('Contact not found in T2', ['phone' => $message->to]);
        return;
    } else {
        // Other errors - retry with backoff
        throw $e;
    }
}
```

---

## 📡 T2 Provider Details

### Authentication Flow

1. **Initial Request**: Service calls `/auth/login` with email/password
2. **Token Received**: T2 returns JWT token (valid for 1 hour)
3. **Token Cached**: Token stored in Laravel cache for 55 minutes
4. **Auto-Refresh**: When cache expires, new token is automatically fetched
5. **Error Recovery**: On 401 error, cache is cleared and re-authentication occurs

### Phone Number Formatting

**Input**: E.164 format with `+` prefix  
**Example**: `+966501234567`

**T2 Requirement**: No `+` prefix  
**Example**: `966501234567`

**Handling**: The service automatically strips the `+` prefix when sending to T2.

### Template Message Format

T2 uses a special template syntax:

**Format**: `##template_name##variable1##variable2##variable3##`

**Example**:
```
Template in T2: "Hello {{1}}, welcome to {{2}}!"
Variables: ['John', 'T2 Communicate']
Sent to T2 as: "##welcome_message##John##T2 Communicate##"
```

**Automatic Handling**: The service builds this format automatically when using `sendTemplate()`.

### WhatsApp Business API Rules

**24-Hour Session Window**:
- Free-form messages can only be sent if the user messaged the business within the last 24 hours
- Outside this window, only pre-approved templates can be sent

**Template Requirements**:
- Templates must be created and approved in T2/WhatsApp Manager
- Approval takes 2-48 hours (UTILITY templates are faster than MARKETING)
- Templates can be sent to any number at any time

**Message Limits**:
- Text: 4,096 characters maximum
- Image: 5MB maximum
- Document: 100MB maximum

### Response Structure

**Success Response**:
```json
{
    "messageId": "msg-abc123",
    "status": "sent",
    "contactNumber": "966501234567",
    "contactName": "Ahmed Ali",
    "lastMessageDate": "2025-02-08T12:34:56.789Z"
}
```

**Error Response**:
```json
{
    "Type": 0,
    "Message": "Error description",
    "StatusCode": 400,
    "InnerException": null
}
```

---

## ✅ Best Practices

### 1. Always Use Jobs for Production

```php
// ✅ GOOD: Non-blocking, queued
SendWhatsAppNotificationJob::dispatch($phone, $message);

// ❌ BAD: Blocks HTTP request
$whatsapp->sendMessage($message);
```

### 2. Comprehensive Logging

```php
// Before sending
Log::info('Sending WhatsApp notification', [
    'tenant_id' => $tenant->id,
    'phone' => $message->to,
    'type' => 'subscription_expiring',
]);

// After success
Log::info('WhatsApp sent successfully', [
    'message_id' => $result['messageId'],
    'status' => $result['status'],
]);

// On error
Log::error('WhatsApp send failed', [
    'error' => $e->getMessage(),
    'context' => $e->getContext(),
]);
```

### 3. Graceful Error Handling

```php
try {
    $whatsapp->sendMessage($message);
} catch (WhatsAppException $e) {
    // Don't crash - log and continue
    Log::error('WhatsApp error', ['error' => $e->getMessage()]);
    
    // Optionally notify administrators
    // NotifyAdminOfWhatsAppFailure::dispatch($e);
}
```

### 4. Phone Number Validation

```php
// Validate at request level
$validated = $request->validate([
    'phone' => 'required|regex:/^\+[1-9]\d{1,14}$/',
]);

// Or create custom validation rule
class E164PhoneNumber implements Rule
{
    public function passes($attribute, $value): bool
    {
        return preg_match('/^\+[1-9]\d{1,14}$/', $value) === 1;
    }
}
```

### 5. Use Metadata for Tracking

```php
$message = new WhatsAppMessage(
    to: $phone,
    body: $body,
    metadata: [
        'tenant_id' => $tenant->id,
        'notification_type' => 'subscription_expiring',
        'triggered_by' => 'cron_job',
        'subscription_id' => $subscription->id,
        'timestamp' => now()->toISOString(),
    ]
);
```

### 6. Implement Retry Logic in Jobs

```php
class SendWhatsAppNotificationJob implements ShouldQueue
{
    public $tries = 3;
    public $backoff = [60, 300, 900]; // 1min, 5min, 15min

    public function handle(WhatsAppService $whatsapp): void
    {
        try {
            $whatsapp->sendMessage($this->message);
        } catch (WhatsAppException $e) {
            // Retry for server errors
            if (in_array($e->getCode(), [500, 502, 503, 504])) {
                throw $e;
            }
            // Don't retry for client errors
            Log::error('Non-retryable error', ['error' => $e->getMessage()]);
        }
    }
}
```

### 7. Test in Dry-Run Mode First

```bash
# Test without sending real messages
php artisan whatsapp:test --dry-run

# Verify configuration
php artisan whatsapp:test --type=config
```

---

## 🔧 Troubleshooting

### Problem: Configuration Error

**Symptoms**:
```
WhatsAppException: T2 WhatsApp provider is not properly configured
```

**Solutions**:
1. Verify all required variables exist in `.env`:
   ```bash
   grep "T2_WHATSAPP" .env
   ```
2. Clear configuration cache:
   ```bash
   php artisan config:clear
   ```
3. Test configuration:
   ```bash
   php artisan whatsapp:test --type=config
   ```
4. Verify credentials with T2 support team

---

### Problem: Authentication Failed

**Symptoms**:
```
Authentication failed: The email or password is incorrect
```

**Solutions**:
1. Verify credentials are correct in `.env`
2. Try logging into T2 web dashboard with same credentials
3. Check if account is locked or requires password reset
4. Clear cached token:
   ```bash
   php artisan cache:forget t2_whatsapp_access_token
   ```

---

### Problem: Invalid Phone Number

**Symptoms**:
```
InvalidArgumentException: Invalid phone number format
```

**Solutions**:
1. Ensure phone number is in E.164 format: `+966501234567`
2. Include country code with `+` prefix
3. Remove spaces, dashes, parentheses
4. Validate before creating DTO:
   ```php
   if (!preg_match('/^\+[1-9]\d{1,14}$/', $phone)) {
       throw new \Exception('Invalid phone format');
   }
   ```

---

### Problem: Template Required Error

**Symptoms**:
```
You need to use a pre-approved WhatsApp Message Template to initiate a conversation
```

**Explanation**: The recipient hasn't messaged the business in the last 24 hours.

**Solutions**:
1. Use `sendTemplate()` instead of `sendMessage()`
2. Ensure template is approved in T2/WhatsApp Manager
3. For testing: Have recipient send a message first, then reply within 24 hours
4. Check template status:
   ```bash
   GET /template/list?Status=APPROVED
   ```

---

### Problem: Messages Not Sending

**Debug Checklist**:

1. ✅ Check Laravel logs:
   ```bash
   tail -f storage/logs/laravel.log
   ```

2. ✅ Verify queue is running:
   ```bash
   php artisan queue:work
   ```

3. ✅ Test configuration:
   ```bash
   php artisan whatsapp:test --type=config
   ```

4. ✅ Check T2 dashboard for message status

5. ✅ Verify phone number format (E.164)

6. ✅ Ensure user has messaged first OR use approved template

7. ✅ Clear token cache and retry:
   ```bash
   php artisan cache:forget t2_whatsapp_access_token
   ```

---

### Problem: Token Expired Errors

**Symptoms**: Intermittent 401 errors

**Solutions**:
1. Token caching is automatic - verify cache is working:
   ```bash
   php artisan cache:get t2_whatsapp_access_token
   ```
2. Check cache driver in `.env`:
   ```env
   CACHE_DRIVER=redis  # or file, database
   ```
3. Increase token expiry buffer if needed in `config/whatsapp.php`

---

## 📚 Summary

### What This Service Provides

The WhatsApp Integration Service is a production-ready abstraction layer that:

- ✅ Sends plain text WhatsApp messages
- ✅ Sends templated messages with variable substitution
- ✅ Handles authentication automatically (token management, caching, renewal)
- ✅ Provides detailed error messages with context
- ✅ Includes comprehensive testing tools
- ✅ Is provider-agnostic (easy to add Twilio, direct WhatsApp API, etc.)
- ✅ Uses type-safe DTOs with validation
- ✅ Includes unit tests and test command

### How to Use

```php
// Two lines to send a WhatsApp message
$whatsapp = new WhatsAppService();
$whatsapp->sendMessage(new WhatsAppMessage($phone, $message));
```

### Integration Points

The service is designed to be used from:
- **Controllers**: For API endpoints
- **Jobs**: For queued/background sending (recommended)
- **Event Listeners**: For subscription lifecycle events
- **Commands**: For batch operations or manual testing

### Future Extensions

The service architecture supports:
- Adding new providers (Twilio, direct WhatsApp API)
- Adding delivery tracking (webhooks, status updates)
- Adding rate limiting
- Adding template management
- Adding multi-language template selection

---

**Version**: 1.0  
**Date**: February 8, 2025  
**Status**: Production Ready ✅

---

*For questions or issues, contact the VOM Subscription development team.*