# API Documentation
This document provides comprehensive information about all API endpoints available in the Global Goods server application.
## Base URL
All API endpoints are prefixed with `/api`. For example, if the server is running on `http://localhost:3000`, the base URL for API requests would be `http://localhost:3000/api`.
## Health Check Endpoint
### Server Status Check
Simple endpoint to verify server connectivity.
- **URL**: `/`
- **Method**: `GET`
- **URL Parameters**: None
- **Success Response**:
  - **Code**: 200
  - **Content**: `"Hello from the server!"`

- **Error Response**: None

## Location Management Endpoints
### Get All Continents
Retrieves a list of all continents.
- **URL**: `/continents`
- **Method**: `GET`
- **URL Parameters**: None
- **Success Response**:
  - **Code**: 200
  - **Content Example**:
``` json
    [
      {
        "id": 1,
        "title": "Africa",
        "slug": "africa",
        "created_at": "2025-07-12T04:00:03.000Z",
        "updated_at": "2025-07-12T04:00:03.000Z"
      },
      {
        "id": 2,
        "title": "Asia",
        "slug": "asia",
        "created_at": "2025-07-12T04:00:03.000Z",
        "updated_at": "2025-07-12T04:00:03.000Z"
      }
    ]
```
- **Error Response**:
  - **Code**: 500
  - **Content**: `{ "error": "Failed to fetch continents" }`

### Get Sub-Regions
Retrieves a list of sub-regions with optional filtering.
- **URL**: `/sub-regions`
- **Method**: `GET`
- **URL Parameters**:
  - `continent_id` (optional): Filter by continent ID
  - Any field in the sub_regions table can be used as a filter parameter

- **Success Response**:
  - **Code**: 200
  - **Content Example**:
``` json
    [
      {
        "id": 1,
        "continent_id": 1,
        "title": "Northern Africa",
        "slug": "northern-africa",
        "created_at": "2025-07-12T04:31:39.000Z",
        "updated_at": "2025-07-12T04:31:39.000Z"
      }
    ]
```
- **Error Response**:
  - **Code**: 500
  - **Content**: `{ "error": "Failed to fetch sub-regions" }`

### Get Countries
Retrieves a list of countries with pagination and optional filtering.
- **URL**: `/countries`
- **Method**: `GET`
- **URL Parameters**:
  - `limit` (optional): Number of records to return (default: 500)
  - `offset` (optional): Number of records to skip (default: 0)
  - `sub_region_id` (optional): Filter by sub-region ID
  - Any field in the countries table can be used as a filter parameter

- **Success Response**:
  - **Code**: 200
  - **Content Example**:
``` json
    [
      {
        "id": 4,
        "sub_region_id": 1,
        "title": "Algeria",
        "slug": "algeria",
        "created_at": "2025-07-12T05:30:34.000Z",
        "updated_at": "2025-07-12T05:30:34.000Z"
      }
    ]
```
- **Error Responses**:
  - **Code**: 400
  - **Content**: `{ "error": "Limit and offset must be non-negative integers" }`
  - **Code**: 500
  - **Content**: `{ "error": "Failed to fetch countries" }`

### Get States
Retrieves a list of states with pagination and optional filtering.
- **URL**: `/states`
- **Method**: `GET`
- **URL Parameters**:
  - `limit` (optional): Number of records to return (default: 500)
  - `offset` (optional): Number of records to skip (default: 0)
  - `country_id` (optional): Filter by country ID
  - Any field in the states table can be used as a filter parameter

- **Success Response**:
  - **Code**: 200
  - **Content Example**:
``` json
    [
      {
        "id": 3870,
        "country_id": 1,
        "title": "Ghazni",
        "slug": "ghazni",
        "created_at": "2025-07-12T05:33:27.000Z",
        "updated_at": "2025-07-12T05:33:27.000Z"
      }
    ]
```
- **Error Responses**:
  - **Code**: 400
  - **Content**: `{ "error": "Limit and offset must be non-negative integers" }`
  - **Code**: 500
  - **Content**: `{ "error": "Failed to fetch states" }`

### Get Cities
Retrieves a list of cities with pagination and optional filtering.
- **URL**: `/cities`
- **Method**: `GET`
- **URL Parameters**:
  - `limit` (optional): Number of records to return (default: 500)
  - `offset` (optional): Number of records to skip (default: 0)
  - `state_id` (optional): Filter by state ID
  - Any field in the cities table can be used as a filter parameter

- **Success Response**:
  - **Code**: 200
  - **Content Example**:
``` json
    [
      {
        "id": 38592,
        "state_id": 1,
        "title": "Alaba Special Wereda",
        "slug": "alaba-special-wereda",
        "created_at": "2025-07-12T05:59:33.000Z",
        "updated_at": "2025-07-12T05:59:33.000Z"
      }
    ]
```
- **Error Responses**:
  - **Code**: 400
  - **Content**: `{ "error": "Limit and offset must be non-negative integers" }`
  - **Code**: 500
  - **Content**: `{ "error": "Failed to fetch cities" }`

## WordPress Content Endpoints
### Get Global Issues
Retrieves a list of global issues from WordPress.
- **URL**: `/global-issues`
- **Method**: `GET`
- **URL Parameters**: None
- **Success Response**:
  - **Code**: 200
  - **Content**: Array of WordPress pages with tag `Global Issue`

- **Error Response**:
  - **Code**: Various
  - **Content**: Error message from WordPress API

### Get Programs
Retrieves a list of programs from WordPress.
- **URL**: `/programs`
- **Method**: `GET`
- **URL Parameters**: None
- **Success Response**:
  - **Code**: 200
  - **Content**: Array of WordPress pages with tag `Programs`

- **Error Response**:
  - **Code**: Various
  - **Content**: Error message from WordPress API

### Get Missions
Retrieves a list of missions from WordPress.
- **URL**: `/missions`
- **Method**: `GET`
- **URL Parameters**: None
- **Success Response**:
  - **Code**: 200
  - **Content**: Array of WordPress pages with tag `Missions`

- **Error Response**:
  - **Code**: Various
  - **Content**: Error message from WordPress API

### Get Projects
Retrieves a list of projects from WordPress.
- **URL**: `/projects`
- **Method**: `GET`
- **URL Parameters**: None
- **Success Response**:
  - **Code**: 200
  - **Content**: Array of WordPress pages with tag `Projects`

- **Error Response**:
  - **Code**: Various
  - **Content**: Error message from WordPress API

### Get Products
Retrieves a list of products from WooCommerce.
- **URL**: `/products`
- **Method**: `GET`
- **URL Parameters**: None
- **Success Response**:
  - **Code**: 200
  - **Content**: Array of WooCommerce products

- **Error Response**:
  - **Code**: Various
  - **Content**: Error message from WooCommerce API

## Payment & Checkout Endpoints
### Create Payment Intent
Creates a payment intent for transactions.
- **URL**: `/payment`
- **Method**: `POST`
- **Request Body**: Payment details (structure depends on payment method)
- **Success Response**:
  - **Code**: 200
  - **Content**: Payment intent object

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Create PayPal Order
Creates a PayPal order for checkout.
- **URL**: `/paypal/create-order`
- **Method**: `POST`
- **Request Body**: Order details
- **Success Response**:
  - **Code**: 200
  - **Content**: PayPal order object with order ID

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Capture PayPal Order
Captures a PayPal order after approval.
- **URL**: `/paypal/capture-order`
- **Method**: `POST`
- **Request Body**: Order ID and capture details
- **Success Response**:
  - **Code**: 200
  - **Content**: Capture confirmation details

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Payment Success
Handles successful payment redirects.
- **URL**: `/success`
- **Method**: `GET`
- **URL Parameters**: Payment confirmation parameters
- **Success Response**:
  - **Code**: 200
  - **Content**: Success confirmation

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Payment Cancel
Handles cancelled payment redirects.
- **URL**: `/cancel`
- **Method**: `GET`
- **URL Parameters**: Cancellation parameters
- **Success Response**:
  - **Code**: 200
  - **Content**: Cancellation confirmation

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Get Success Details
Retrieves transaction success details.
- **URL**: `/success-details`
- **Method**: `GET`
- **URL Parameters**:
  - `transaction_id` (optional): Transaction ID to fetch details for

- **Success Response**:
  - **Code**: 200
  - **Content**: Transaction details object

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

## Transfer & Banking Endpoints
### Create Customer
Creates a new customer for banking/transfer operations.
- **URL**: `/create-customer`
- **Method**: `POST`
- **Request Body**: Customer information
- **Success Response**:
  - **Code**: 200
  - **Content**: Customer object with ID

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Create Setup Intent
Creates a setup intent for payment method setup (ACH, cards, etc.).
- **URL**: `/create-setup-intent`
- **Method**: `POST`
- **Request Body**: Setup intent parameters
- **Success Response**:
  - **Code**: 200
  - **Content**: Setup intent object

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Create Payment Intent
Creates a payment intent for domestic transfers.
- **URL**: `/create-payment-intent`
- **Method**: `POST`
- **Request Body**: Payment intent parameters
- **Success Response**:
  - **Code**: 200
  - **Content**: Payment intent object

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Create International Payment Intent
Creates a payment intent for international transfers.
- **URL**: `/create-international-payment-intent`
- **Method**: `POST`
- **Request Body**: International payment parameters
- **Success Response**:
  - **Code**: 200
  - **Content**: Payment intent object

- **Error Response**:
  - **Code**: 400/500
  - **Content**: Error message

### Get Funding Instructions
Retrieves funding instructions for a specific transaction.
- **URL**: `/get-funding-instructions/:transaction_id`
- **Method**: `GET`
- **URL Parameters**:
  - `transaction_id` (required): Transaction ID

- **Success Response**:
  - **Code**: 200
  - **Content**: Funding instructions object

- **Error Response**:
  - **Code**: 404
  - **Content**: `{ "error": "Transaction not found" }`
  - **Code**: 500
  - **Content**: Error message

## Invoice Management Endpoints
### Preview Invoice
Generates a preview of an invoice.
- **URL**: `/invoices/:invoice_id/preview`
- **Method**: `GET`
- **URL Parameters**:
  - `invoice_id` (required): Invoice ID

- **Success Response**:
  - **Code**: 200
  - **Content**: Invoice preview (HTML or PDF)

- **Error Response**:
  - **Code**: 404
  - **Content**: `{ "error": "Invoice not found" }`
  - **Code**: 500
  - **Content**: Error message

### Download Invoice
Downloads an invoice as PDF.
- **URL**: `/invoices/:invoice_id/download`
- **Method**: `POST`
- **URL Parameters**:
  - `invoice_id` (required): Invoice ID

- **Request Body**: Download options (optional)
- **Success Response**:
  - **Code**: 200
  - **Content-Type**: `application/pdf`
  - **Content**: PDF file

- **Error Response**:
  - **Code**: 404
  - **Content**: `{ "error": "Invoice not found" }`
  - **Code**: 500
  - **Content**: Error message

### Send Invoice
Sends an invoice via email.
- **URL**: `/invoices/:invoice_id/send`
- **Method**: `POST`
- **URL Parameters**:
  - `invoice_id` (required): Invoice ID

- **Request Body**:
``` json
  {
    "recipient_email": "string",
    "subject": "string (optional)",
    "message": "string (optional)"
  }
```
- **Success Response**:
  - **Code**: 200
  - **Content**: `{ "message": "Invoice sent successfully" }`

- **Error Response**:
  - **Code**: 404
  - **Content**: `{ "error": "Invoice not found" }`
  - **Code**: 400
  - **Content**: `{ "error": "Invalid email address" }`
  - **Code**: 500
  - **Content**: Error message

## Usage Examples
### Basic Location Hierarchy Fetching
``` javascript
// Fetch continents, then sub-regions, then countries
const fetchLocationHierarchy = async () => {
  try {
    const continents = await fetch('/api/continents').then(r => r.json());
    const subRegions = await fetch(`/api/sub-regions?continent_id=${continents[0].id}`).then(r => r.json());
    const countries = await fetch(`/api/countries?sub_region_id=${subRegions[0].id}`).then(r => r.json());
    console.log({ continents, subRegions, countries });
  } catch (error) {
    console.error('Error fetching location data:', error);
  }
};
```
### Creating a PayPal Order
``` javascript
const createPayPalOrder = async (orderData) => {
  try {
    const response = await fetch('/api/paypal/create-order', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(orderData)
    });
    const order = await response.json();
    return order;
  } catch (error) {
    console.error('Error creating PayPal order:', error);
  }
};
```
### Setting Up ACH Payment Method
``` javascript
const setupACH = async (customerId) => {
  try {
    const response = await fetch('/api/create-setup-intent', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        customer_id: customerId,
        payment_method_types: ['us_bank_account']
      })
    });
    const setupIntent = await response.json();
    return setupIntent;
  } catch (error) {
    console.error('Error setting up ACH:', error);
  }
};
```
### Downloading an Invoice
``` javascript
const downloadInvoice = async (invoiceId) => {
  try {
    const response = await fetch(`/api/invoices/${invoiceId}/download`, {
      method: 'POST'
    });
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `invoice-${invoiceId}.pdf`;
    a.click();
  } catch (error) {
    console.error('Error downloading invoice:', error);
  }
};
```
### Getting Funding Instructions
``` javascript
const getFundingInstructions = async (transactionId) => {
  try {
    const response = await fetch(`/api/get-funding-instructions/${transactionId}`);
    const instructions = await response.json();
    return instructions;
  } catch (error) {
    console.error('Error fetching funding instructions:', error);
  }
};
```
## Error Handling
All endpoints follow consistent error response formats:
``` json
{
  "error": "Error message description",
  "code": "ERROR_CODE (optional)",
  "details": "Additional error details (optional)"
}
```
Common HTTP status codes used:
- **200**: Success
- **400**: Bad Request (invalid parameters, malformed request)
- **404**: Not Found (resource doesn't exist)
- **500**: Internal Server Error (server-side error)

## Rate Limiting
Please note that some endpoints may have rate limiting in place. Implement appropriate retry logic with exponential backoff for production applications.
## Authentication
Currently, the API does not require authentication for most endpoints. However, payment and sensitive operations may require proper authentication tokens in production environments.