# WooCommerce External API Integration Plugin

🚀 **The most powerful and flexible WooCommerce API integration plugin** - Automatically sync orders, customers, and subscriptions with any external system.

Ideal for SaaS platforms, membership sites, license management systems, LMS platforms, CRM integration, and any service that needs automated provisioning when customers make purchases.

## 🌟 Key Features

### Core Functionality
✅ **Product-Level API Configuration** - Configure different APIs for different products  
✅ **Multiple Authentication Methods** - Bearer Token, API Key, Basic Auth, Custom Headers  
✅ **Multiple HTTP Methods** - POST, PUT, PATCH support  
✅ **Automatic Retries** - Configurable retry mechanism with exponential backoff  
✅ **Comprehensive Logging** - Track all API requests and responses with detailed debug info  
✅ **WooCommerce Subscriptions Support** - Full integration with subscription lifecycle

### 🎯 Advanced Features (NEW!)
✅ **50+ Dynamic Variables** - Access customer, order, product, and subscription data  
✅ **Date/Time Functions** - Calculate dates dynamically ({{date:+1month}}, {{date:+1year}}, etc.)  
✅ **Timestamp Functions** - Unix timestamps with modifiers  
✅ **Random Value Generators** - UUIDs, random numbers, random strings  
✅ **Custom Payload Fields** - Full JSON customization with variable replacement  
✅ **Test API Connection** - Test your configuration before going live  
✅ **Variable Helper UI** - Built-in reference for all variables and functions  
✅ **JSON Validation** - Real-time validation with helpful error messages

## 💡 Use Cases

This plugin is perfect for:

- **SaaS Platforms** - Auto-provision user accounts, set limits, manage subscriptions
- **License Management** - Generate and activate license keys automatically
- **Membership Sites** - Grant access, set expiry dates, manage tiers
- **Online Courses** - Enroll students, set access periods, issue certificates
- **CRM Integration** - Sync customer data with Salesforce, HubSpot, etc.
- **ERP Systems** - Update inventory, customer records, order status
- **Custom Dashboards** - Send data to external analytics or management systems
- **Webhooks** - Trigger actions in Zapier, Make.com, or custom systems
- **Multi-System Sync** - Keep multiple platforms in sync with WooCommerce

## 🆕 What's New in Version 2.0

### Dynamic Functions System
- **Date calculations**: `{{date:+1month}}`, `{{date:+1year}}`, `{{date:-1week}}`
- **Timestamps**: `{{timestamp:}}`, `{{timestamp:+1year}}`
- **Random generators**: `{{uuid:}}`, `{{random:1-100}}`, `{{random_string:16}}`
- **Current values**: `{{year:}}`, `{{month:}}`, `{{today:}}`

### Enhanced Variables (50+ total)
- Full customer data (name, email, phone, company, address)
- Complete order information (totals, tax, shipping, payment method)
- Product details (SKU, price, quantity, type)
- Subscription data (billing period, next payment, trial end)

### Testing & Debugging
- One-click API connection testing
- Test mode with sample data
- Enhanced logging with debug levels
- JSON validation with helpful error messages
- Visual variable helper/reference

## Requirements

- WordPress 5.8 or higher
- WooCommerce 5.0 or higher
- PHP 7.4 or higher
- SSL certificate (recommended for secure API communications)

## Installation

### Method 1: Upload via WordPress Admin

1. Download the plugin file `woocommerce-external-api-integration.php`
2. Log in to your WordPress admin panel
3. Navigate to **Plugins** → **Add New** → **Upload Plugin**
4. Click **Choose File** and select the plugin file
5. Click **Install Now**
6. After installation, click **Activate Plugin**

### Method 2: FTP Upload

1. Download the plugin file
2. Connect to your server via FTP
3. Navigate to `/wp-content/plugins/`
4. Create a new folder called `woocommerce-external-api-integration`
5. Upload `woocommerce-external-api-integration.php` to this folder
6. Go to WordPress admin → **Plugins** → **Installed Plugins**
7. Find "WooCommerce External API Integration" and click **Activate**

### Method 3: Direct Upload to Server

```bash
# SSH into your server
cd /path/to/wordpress/wp-content/plugins/

# Create plugin directory
mkdir woocommerce-external-api-integration

# Upload the file (or use wget/curl)
cd woocommerce-external-api-integration
# Upload woocommerce-external-api-integration.php here

# Set proper permissions
chmod 644 woocommerce-external-api-integration.php
```

## Configuration

### 1. Global Settings

After activation, go to **API Integration** → **Settings** in WordPress admin:

- **Enable Logging**: Turn on/off detailed logging of API requests
- **Request Timeout**: Set timeout for API calls (5-300 seconds)
- **Retry Attempts**: Configure number of retry attempts (1-10)

### 2. Product-Level Configuration

For each product that should trigger an API call:

1. Go to **Products** → **All Products**
2. Edit the product you want to integrate
3. Scroll down to the **External API Settings** meta box
4. Check **"Enable API Integration for this product"**
5. Configure the following:

#### API Endpoint URL
```
https://api.example.com/subscribe
```
The external API endpoint that will receive the purchase data.

#### HTTP Method
- `POST` (recommended for creating new records)
- `PUT` (for updating existing records)
- `PATCH` (for partial updates)

#### Authentication Type

**None** - No authentication
```
No additional configuration needed
```

**Bearer Token** - OAuth 2.0 / JWT tokens
```
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

**API Key (Header)** - API key in X-API-Key header
```
Key: your-api-key-here
```

**Basic Auth** - Username and password
```
Format: username:password
Example: admin:secret123
```

#### Custom Headers (Optional)
Add additional HTTP headers in JSON format:
```json
{
  "Content-Type": "application/json",
  "X-Custom-Header": "custom-value",
  "X-API-Version": "v2"
}
```

#### Custom Payload Fields (Optional)
Add or override fields in the API payload using powerful variables and functions:

**Example with Date Functions:**
```json
{
  "user_email": "{{email}}",
  "subscription_start": "{{date:}}",
  "subscription_expires": "{{date:+1year}}",
  "max_users": 100,
  "license_key": "{{random_string:16-alphanumeric}}",
  "transaction_id": "{{uuid:}}"
}
```

**Dynamic Functions Available:**
- **Dates**: `{{date:}}`, `{{date:+1month}}`, `{{date:+1year}}`, `{{date:-1week}}`
- **Timestamps**: `{{timestamp:}}`, `{{timestamp:+1year}}`
- **Random**: `{{uuid:}}`, `{{random:1-100}}`, `{{random_string:16}}`
- **Current**: `{{year:}}`, `{{month:}}`, `{{today:}}`

**50+ Variables Available** - Click "Show Available Variables & Functions" button in product settings for full reference:
- Customer data (email, name, phone, address, company)
- Order data (ID, total, tax, shipping, payment method)
- Product data (ID, name, SKU, price, quantity)
- Subscription data (status, billing period, next payment)

### 3. Test and Deploy

1. Click **"Test API Connection"** button to send a test request
   - Uses sample data to verify your configuration
   - Shows success/error message immediately
   - No need to make actual purchases for testing

2. Click **Update** to save the product

3. Make a real purchase (or wait for customer orders)

4. Check **API Integration** → **Logs** to verify API calls
   - View all requests with timestamps
   - See payloads, responses, and errors
   - Filter by log level (info, error, success, debug)

## Default Payload Structure

When a purchase is made, the plugin sends the following JSON payload:

```json
{
  "email": "customer@example.com",
  "order_id": 12345,
  "product_id": 123,
  "product_name": "Premium Software Subscription",
  "product_sku": "SOFT-PREM-001",
  "quantity": 1,
  "total": 99.99,
  "currency": "USD",
  "customer_first_name": "John",
  "customer_last_name": "Doe",
  "customer_phone": "+1234567890",
  "purchase_date": "2025-11-15T12:00:00+00:00",
  "order_status": "completed",
  "subscription_id": 456,
  "subscription_status": "active"
}
```

Custom fields from product settings will be merged with this structure.

## Usage Examples

### Example 1: Simple API Integration

**Scenario**: Send customer email to a subscription management API

**Product Configuration:**
- **API URL**: `https://api.myapp.com/users/subscribe`
- **Method**: POST
- **Auth Type**: Bearer Token
- **Token**: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...`

**Custom Fields**:
```json
{
  "subscription_tier": "premium",
  "auto_renew": true
}
```

**Result**: When customer purchases, API receives:
```json
{
  "email": "john@example.com",
  "order_id": 12345,
  "product_id": 100,
  "product_name": "Premium Plan",
  "subscription_tier": "premium",
  "auto_renew": true,
  ...
}
```

### Example 2: Multiple Products with Different APIs

**Product 1: Basic Plan**
- API URL: `https://api.myapp.com/licenses/create`
- Custom Fields:
```json
{
  "license_type": "basic",
  "max_users": 1
}
```

**Product 2: Enterprise Plan**
- API URL: `https://api.myapp.com/licenses/create`
- Custom Fields:
```json
{
  "license_type": "enterprise",
  "max_users": 50,
  "priority_support": true
}
```

### Example 3: Using Variable Replacement

**Custom Fields**:
```json
{
  "user_email": "{{email}}",
  "user_name": "{{customer_first_name}} {{customer_last_name}}",
  "license_key": "{{order_id}}-{{product_id}}",
  "notes": "Purchased {{product_name}} on {{purchase_date}}"
}
```

**Actual Payload Sent**:
```json
{
  "email": "john@example.com",
  "user_email": "john@example.com",
  "user_name": "John Doe",
  "license_key": "12345-100",
  "notes": "Purchased Premium Plan on 2025-11-15T12:00:00+00:00",
  ...
}
```

### Example 4: Custom API Authentication

**Scenario**: API requires custom authentication header

**Custom Headers**:
```json
{
  "X-Company-ID": "12345",
  "X-API-Secret": "your-secret-key",
  "X-Timestamp": "2025-11-15"
}
```

## Webhook Triggers

The plugin automatically sends API requests on the following events:

1. **Order Completed** - When order status changes to "completed"
2. **Payment Complete** - When payment is successfully processed
3. **Subscription Active** - When subscription becomes active (requires WooCommerce Subscriptions)

## Monitoring & Debugging

### Viewing Logs

1. Go to **API Integration** → **Logs**
2. View all API requests with:
   - Timestamp
   - Log level (Info, Success, Error, Warning)
   - Detailed messages

### Log Levels

- **INFO**: General information about API calls
- **SUCCESS**: Successful API responses (HTTP 2xx)
- **WARNING**: Non-critical issues (e.g., API not configured)
- **ERROR**: Failed API requests with error details
- **DEBUG**: Detailed payload and response data

### Order Notes

API call results are automatically added to WooCommerce order notes:
- ✅ "External API updated successfully for product: [Product Name]"
- ❌ "External API update failed for product: [Product Name]. Error: [Details]"

## Troubleshooting

### Issue: API Request Fails with Timeout

**Solution:**
- Increase timeout in **API Integration** → **Settings**
- Check if external API is responding slowly
- Verify network connectivity

### Issue: Authentication Errors (401/403)

**Solution:**
- Verify authentication credentials
- Check token expiration
- Ensure correct authentication type is selected
- Test API endpoint with Postman/cURL

### Issue: API Not Being Called

**Solution:**
- Verify "Enable API Integration" is checked for the product
- Check that order status is "completed"
- Review logs in **API Integration** → **Logs**
- Ensure WooCommerce is properly activated

### Issue: Duplicate API Calls

**Solution:**
- Plugin prevents duplicates automatically using meta keys
- If duplicates occur, check for multiple order status changes
- Review webhook configurations in external systems

### Issue: Custom Fields Not Working

**Solution:**
- Verify JSON syntax in custom fields
- Use valid JSON format (check with JSONLint.com)
- Ensure variables are wrapped in `{{variable_name}}`
- Check logs for payload structure

## API Response Handling

The plugin considers these HTTP status codes as successful:
- **200-299**: Success range

Failed requests (4xx, 5xx) trigger automatic retries with exponential backoff.

## Security Best Practices

1. **Use HTTPS**: Always use secure endpoints (https://)
2. **Secure Credentials**: Store API keys securely, never commit to version control
3. **Limited Permissions**: Use API credentials with minimal required permissions
4. **SSL Verification**: Plugin verifies SSL certificates by default
5. **Regular Updates**: Keep WordPress, WooCommerce, and plugin updated
6. **Access Control**: Limit admin access to API Integration settings

## Performance Considerations

- **Async Processing**: API calls are made synchronously but with timeout limits
- **Retry Logic**: Failed requests retry with exponential backoff (2s, 4s, 8s...)
- **Log Retention**: Logs limited to last 500 entries to prevent database bloat
- **Caching**: Processed orders are marked to prevent duplicate API calls

## Advanced Customization

### Custom Hooks (For Developers)

If you need to modify behavior, you can add custom filters/actions to WordPress:

```php
// Modify payload before sending
add_filter('wc_external_api_payload', function($payload, $order, $product) {
    $payload['custom_data'] = 'your_value';
    return $payload;
}, 10, 3);

// Custom action after successful API call
add_action('wc_external_api_success', function($response, $order_id, $product_id) {
    // Your custom logic
}, 10, 3);
```

## Support

For issues specific to Future Feathers website:
- Website: https://futurefeathers.com
- Email: support@futurefeathers.com

For WooCommerce issues:
- Documentation: https://woocommerce.com/documentation/

## Changelog

### Version 1.0.0
- Initial release
- Product-level API configuration
- Multiple authentication methods
- Custom payload fields
- Automatic retries
- Comprehensive logging
- WooCommerce Subscriptions support

## License

GPL v2 or later

## Credits

Developed for Future Feathers  
https://futurefeathers.com

---

**Need Help?** Check the logs first, test with a simple API endpoint (like RequestBin or webhook.site), and verify your JSON syntax!

