HamTestPro Accounting API Documentation

# Stand-Alone Accounting System API Documentation

## Overview

The Accounting System provides a RESTful API for integrating with external applications like HamTestPro.com. All API endpoints require authentication via API key.

## Authentication

Include your API key in requests using one of these methods:

1. **Header (Recommended):**

   ```http
   X-API-Key: your-api-key-here
   ```

2. **Query Parameter:**

   ```http
   GET /api/subscriptions?api_key=your-api-key-here
   ```

## Base URL

- **Local Development:** `http://localhost/dh_cnrdt2/accounting/api/`
- **Production:** `https://accounting.hamtestpro.com/api/`

## Endpoints

### Health Check

Check system health and configuration.

**GET** `/health`

**Response:**

```json
{
  "success": true,
  "status": "healthy",
  "timestamp": "2025-07-29T12:00:00Z",
  "version": "2.0.0",
  "environment": "sandbox",  
  "checks": {
    "database": {
      "status": "healthy",
      "message": "Database connection is working properly"
    },
    "paypal": {
      "valid": true,
      "errors": []
    }
  }
}
```

### Services

Get available subscription services.

**GET** `/services`

**Response:**

```json
{
  "success": true,
  "services": {
    "ham_club_membership": {
      "name": "Ham Club Membership",
      "description": "Annual amateur radio club membership",
      "price_annual": "25.00",
      "billing_cycles": ["yearly"],
      "category": "membership"
    },
    "hamtestpro_premium": {
      "name": "HamTestPro Premium", 
      "description": "Premium ham radio test preparation service",
      "price_monthly": "9.99",
      "price_annual": "49.99",
      "trial_days": "7",
      "billing_cycles": ["monthly", "yearly"],
      "category": "service"
    }
  }
}
```

**GET** `/services/{service_code}`

Get specific service details.

**Response:**

```json
{
  "success": true,
  "service": {
    "name": "HamTestPro Premium",
    "description": "Premium ham radio test preparation service", 
    "price_monthly": "9.99",
    "price_annual": "49.99",
    "trial_days": "7",
    "billing_cycles": ["monthly", "yearly"],
    "category": "service"
  }
}
```

### Subscriptions

Manage user subscriptions.

**GET** `/subscriptions`

Get all subscriptions with optional filtering.

**Query Parameters:**

- `email` - Filter by subscriber email
- `status` - Filter by status (active, cancelled, suspended, expired)
- `service` - Filter by service name (partial match)
- `page` - Page number (default: 1)
- `limit` - Results per page (default: 50)

**Response:**

```json
{
  "success": true,
  "subscriptions": [
    {
      "subscription_id": 1,
      "paypal_subscription_id": "I-BW452GLLEP1G",
      "service_name": "HamTestPro Premium",
      "subscriber_email": "user@example.com",
      "subscriber_name": "John Doe",
      "amount": "9.99",
      "currency": "USD",
      "billing_cycle": "monthly",
      "status": "active",
      "start_date": "2025-07-29 12:00:00",
      "end_date": null,
      "next_billing_date": "2025-08-29 12:00:00",
      "created_at": "2025-07-29 12:00:00",
      "updated_at": "2025-07-29 12:00:00"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 50,
    "total": 1
  }
}
```

**GET** `/subscriptions/{subscription_id}`

Get specific subscription details.

**Response:**

```json
{
  "success": true,
  "subscription": {
    "subscription_id": 1,
    "paypal_subscription_id": "I-BW452GLLEP1G",
    "service_name": "HamTestPro Premium",
    "subscriber_email": "user@example.com",
    "subscriber_name": "John Doe", 
    "amount": "9.99",
    "currency": "USD",
    "billing_cycle": "monthly",
    "status": "active",
    "start_date": "2025-07-29 12:00:00",
    "end_date": null,
    "next_billing_date": "2025-08-29 12:00:00",
    "created_at": "2025-07-29 12:00:00",
    "updated_at": "2025-07-29 12:00:00"
  }
}
```

### Users

Get user subscription information.

**GET** `/users/{email}`

Get all active subscriptions for a user by email address.

**Response:**

```json
{
  "success": true,
  "email": "user@example.com",
  "subscriptions": [
    {
      "subscription_id": 1,
      "paypal_subscription_id": "I-BW452GLLEP1G",
      "service_name": "HamTestPro Premium",
      "amount": "9.99",
      "billing_cycle": "monthly",
      "status": "active",
      "start_date": "2025-07-29 12:00:00",
      "next_billing_date": "2025-08-29 12:00:00"
    }
  ],
  "has_active_subscription": true
}
```

## Error Responses

All endpoints return consistent error responses:

```json
{
  "error": true,
  "message": "Error description",
  "code": 400
}
```

### Common HTTP Status Codes

- `200` - Success
- `400` - Bad Request (invalid parameters)
- `401` - Unauthorized (invalid API key)
- `404` - Not Found (resource doesn't exist)
- `405` - Method Not Allowed
- `500` - Internal Server Error
- `501` - Not Implemented
- `503` - Service Unavailable

## Example Usage

### Check User Subscription Status (HamTestPro Integration)

```javascript
async function checkUserSubscription(email) {
  const response = await fetch(`/api/users/${email}`, {
    headers: {
      'X-API-Key': 'your-api-key-here'
    }
  });
  
  const data = await response.json();
  
  if (data.success && data.has_active_subscription) {
    // User has active subscription
    const hamtestproSubs = data.subscriptions.filter(sub => 
      sub.service_name.includes('HamTestPro')
    );
    
    if (hamtestproSubs.length > 0) {
      return {
        hasAccess: true,
        subscription: hamtestproSubs[0]
      };
    }
  }
  
  return {
    hasAccess: false,
    subscription: null
  };
}
```

### Get All Active Subscriptions

```javascript
async function getActiveSubscriptions() {
  const response = await fetch('/api/subscriptions?status=active', {
    headers: {
      'X-API-Key': 'your-api-key-here'
    }
  });
  
  return await response.json();
}
```

## Rate Limiting

API requests are limited to prevent abuse:

- **Default Limit:** 100 requests per hour per API key
- **Burst Limit:** 10 requests per minute

Rate limit headers are included in responses:

- `X-RateLimit-Limit` - Requests allowed per hour
- `X-RateLimit-Remaining` - Requests remaining
- `X-RateLimit-Reset` - Time when limit resets (Unix timestamp)

## Webhooks

The system receives PayPal webhooks for subscription events:

**Webhook URL:** `/paypal/webhook.php`

**Events Handled:**

- `BILLING.SUBSCRIPTION.ACTIVATED`
- `BILLING.SUBSCRIPTION.CANCELLED`
- `BILLING.SUBSCRIPTION.SUSPENDED`
- `BILLING.SUBSCRIPTION.EXPIRED`
- `PAYMENT.SALE.COMPLETED`
- `PAYMENT.SALE.REFUNDED`

## Security

- All API requests require valid API key
- HTTPS recommended for production
- API keys should be stored securely
- CORS headers configured for cross-origin requests
- Request validation and sanitization implemented

## Support

For API support, contact: `support@hamtestpro.com`

## Changelog

### Version 2.0.0

- Initial API release
- Subscription management endpoints
- PayPal integration
- User subscription validation
- Health check endpoint

Return to Home