# Sponzar Public API v1 — Developer User Manual

> **Base URL:** `https://sponzar.africa/api/v1`  
> **API Version:** 1.0.0  
> **Auth Header:** `X-Api-Key: sk_live_your_api_key_here`  
> **Response Format:** JSON (`Accept: application/json`)

---

## 1. Overview & Key Concepts

The **Sponzar Public API v1** allows developers, platform owners, and enterprise partners to programmatically access Sponzar's headless commercial infrastructure. You can fetch published content, manage content series (micro-dramas, music albums, podcasts, TV series), initiate subscriptions, process tips, sell tickets, manage service bookings, trigger webhooks, and query fan intelligence metrics.

### Key Capabilities
* **Headless CMS**: Retrieve posts, series, episodes, and signed media streaming URLs.
* **Monetization Engine**: Initiate subscriptions, PPV purchases, tips, shop products, and ticket orders.
* **Fan Intelligence**: Access engagement scores, smart segments, and personalized creator recommendations.
* **Automations & Webhooks**: Programmatically construct automation workflows and listen to real-time platform events.

### Client Libraries, Embed SDK & Plugins
* **WordPress Plugin (`sponzar-connect`):** For WordPress websites, download the ready-to-use plugin archive at [`https://sponzar.africa/downloads/sponzar-connect.zip`](https://sponzar.africa/downloads/sponzar-connect.zip) (Full manual: [docs/wordpress_plugin_manual.md](file:///home/sponzar.africa/public_html/docs/wordpress_plugin_manual.md)).
* **Access Layer™ Embed SDK:** For zero-code Web Components on Webflow, Wix, Squarespace, or static HTML, use `<script src="https://sponzar.africa/sdk/sdk.js"></script>` (Full manual: [docs/embed_sdk_manual.md](file:///home/sponzar.africa/public_html/docs/embed_sdk_manual.md)).
* **Interactive Playground:** Test all components, themes, and checkout events live at [`https://sponzar.africa/sdk/demo.html`](file:///home/sponzar.africa/public_html/public/sdk/demo.html).
* **Vendor Operations Guide:** [docs/vendor_operations_guide.md](file:///home/sponzar.africa/public_html/docs/vendor_operations_guide.md)
* **EventOS User Manual:** [docs/event_os_user_manual.md](file:///home/sponzar.africa/public_html/docs/event_os_user_manual.md)

---

## 2. Authentication & Security

All API endpoints require authentication using a valid Sponzar API Key.

### 2.1 Passing Your API Key
Include your API Key in every HTTP request using the `X-Api-Key` header:

```http
GET /api/v1/content HTTP/1.1
Host: sponzar.africa
X-Api-Key: sk_live_9f8e7d6c5b4a3f2e1d0c
Accept: application/json
```

Alternatively, you can pass the key via query string parameter `?api_key=sk_live_...` (recommended only for server-to-server webhook debugging).

### 2.2 Permission Scopes

Each API Key is granted specific permission scopes during creation in the Sponzar Workspace. If your request lacks the required scope, the API responds with `403 Forbidden`.

| Permission Scope | Allowed Operations |
|---|---|
| `content.read` | View posts, series, episodes, fan scores, and fetch signed media streaming URLs |
| `content.write` | Create posts, create series, configure automations, and track traffic sources |
| `payments` | Process subscriptions, tips, PPV purchases, payouts, and view wallet balances |
| `creators.read` | Search and filter public creator profiles |
| `campaigns` | Create and manage ad/reward campaigns and view performance metrics |
| `webhooks` | Register, view, and delete webhook endpoints |
| `shop` | View shop products and execute digital product purchases |
| `tickets` | View events, purchase tickets, view user tickets, and validate ticket QR codes |
| `bookings` | View services, book appointments, view user bookings, and cancel appointments |
| `*` | Super-admin full access across all endpoints |

---

## 3. Quickstart Examples

### 3.1 cURL
```bash
curl -X GET "https://sponzar.africa/api/v1/content?per_page=10" \
  -H "X-Api-Key: sk_live_your_api_key_here" \
  -H "Accept: application/json"
```

### 3.2 JavaScript (Fetch API)
```javascript
const API_KEY = 'sk_live_your_api_key_here';

async function fetchPosts() {
  const response = await fetch('https://sponzar.africa/api/v1/content?per_page=10', {
    method: 'GET',
    headers: {
      'X-Api-Key': API_KEY,
      'Accept': 'application/json'
    }
  });
  
  if (!response.ok) {
    throw new Error(`API Error: ${response.status} ${response.statusText}`);
  }

  const data = await response.json();
  console.log('Posts:', data.data);
}

fetchPosts();
```

### 3.3 PHP (Guzzle)
```php
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client(['base_uri' => 'https://sponzar.africa/api/v1/']);

$response = $client->request('GET', 'content', [
    'headers' => [
        'X-Api-Key' => 'sk_live_your_api_key_here',
        'Accept' => 'application/json',
    ],
    'query' => ['per_page' => 10]
]);

$data = json_decode($response->getBody(), true);
print_r($data['data']);
```

### 3.4 Python (Requests)
```python
import requests

API_KEY = 'sk_live_your_api_key_here'
headers = {
    'X-Api-Key': API_KEY,
    'Accept': 'application/json'
}

response = requests.get('https://sponzar.africa/api/v1/content', headers=headers, params={'per_page': 10})
if response.status_code == 200:
    posts = response.json().get('data', [])
    print(f"Retrieved {len(posts)} posts.")
else:
    print(f"Error {response.status_code}: {response.text}")
```

---

## 4. Complete Endpoint Reference

### 4.1 Content (Posts) — Headless CMS

#### `GET /api/v1/content`
Lists published posts.
* **Scope Required:** `content.read`
* **Query Parameters:**
  - `creator_id` *(int, optional)*: Filter by specific creator ID.
  - `type` *(string, optional)*: `image`, `video`, `audio`, `file`.
  - `access` *(string, optional)*: `free`, `paid`.
  - `per_page` *(int, default: 15, max: 50)*.
* **Response Example (`200 OK`):**
```json
{
  "data": [
    {
      "id": 1024,
      "title": "Exclusive Studio Session",
      "description": "Behind the scenes recording session.",
      "type": "video",
      "price": "5.00",
      "locked": "yes",
      "media_url": "https://sponzar.africa/uploads/media/video1.mp4",
      "creator": {
        "id": 42,
        "name": "Jane Doe",
        "username": "janedoe"
      },
      "created_at": "2026-08-01T12:00:00Z"
    }
  ],
  "links": { "next": "..." }
}
```

#### `GET /api/v1/content/{id}`
Retrieve a single post details.
* **Scope Required:** `content.read`

#### `POST /api/v1/content`
Create a new post.
* **Scope Required:** `content.write`
* **Request Body:**
```json
{
  "title": "New Single Release",
  "description": "Listen to my latest track now!",
  "price": 0.00,
  "locked": "no",
  "type": "audio"
}
```

#### `GET /api/v1/content/{id}/stream`
Get signed streaming URL for a media post.
* **Scope Required:** `content.read`
* **Query Parameters:** `user_id` *(int, required)*
* **Response (`200 OK`):**
```json
{
  "status": "success",
  "stream_url": "https://sponzar.africa/stream/signed?token=eyJhbGci...",
  "expires_at": 1786000000
}
```
* **Error Response (`403 Forbidden`):**
```json
{
  "error": "purchase_required",
  "message": "User has not unlocked this content.",
  "price": "5.00"
}
```

---

### 4.2 Series (Micro-Dramas, TV, Music, Podcasts)

#### `GET /api/v1/series`
List series.
* **Scope Required:** `content.read`
* **Query Parameters:**
  - `type` *(string, optional)*: `micro_drama`, `tv_series`, `music_album`, `podcast`.
  - `creator_id` *(int, optional)*.

#### `GET /api/v1/series/{id}`
Get series details including episode count and creator metadata.

#### `GET /api/v1/series/{id}/episodes`
List episodes for a series.

#### `GET /api/v1/series/{seriesId}/episodes/{episodeId}/stream`
Get signed stream URL for a specific episode.

#### `POST /api/v1/series/{seriesId}/episodes/{episodeId}/purchase`
Purchase access to a locked episode.
* **Scope Required:** `payments`
* **Request Body:** `{ "user_id": 123 }`

---

### 4.3 Monetization — Subscriptions, Tips & Payments

#### `POST /api/v1/subscriptions`
Subscribe a fan to a creator tier.
* **Scope Required:** `payments`
* **Request Body:**
```json
{
  "creator_id": 42,
  "tier_id": 5,
  "user_id": 123,
  "payment_gateway": "payfast"
}
```

#### `POST /api/v1/tips`
Send a tip to a creator.
* **Scope Required:** `payments`
* **Request Body:**
```json
{
  "creator_id": 42,
  "amount": 10.00,
  "user_id": 123,
  "message": "Love your work!"
}
```

#### `POST /api/v1/payouts`
Request balance withdrawal to linked bank account.
* **Scope Required:** `payments`
* **Request Body:**
```json
{
  "amount": 500.00,
  "bank_account_id": 12
}
```

---

### 4.4 Shop & Digital Products

#### `GET /api/v1/shop/products`
List digital products & merchandise.
* **Scope Required:** `shop`

#### `POST /api/v1/shop/products/{id}/purchase`
Purchase a digital product.
* **Scope Required:** `shop`

---

### 4.5 Ticketing & EventOS

#### `GET /api/v1/tickets/events`
List active events.
* **Scope Required:** `tickets`

#### `POST /api/v1/tickets/events/{id}/purchase`
Purchase event ticket.
* **Scope Required:** `tickets`
* **Request Body:** `{ "ticket_tier_id": 2, "quantity": 1, "user_id": 123 }`

#### `POST /api/v1/tickets/{id}/validate`
Validate ticket QR code at gate scanner.
* **Scope Required:** `tickets`
* **Request Body:** `{ "qr_code": "SPONZAR-TCK-99201" }`

---

### 4.6 Service Bookings

#### `GET /api/v1/bookings/services`
List available creator services.
* **Scope Required:** `bookings`

#### `POST /api/v1/bookings`
Book a creator service/appointment slot.
* **Scope Required:** `bookings`
* **Request Body:**
```json
{
  "service_id": 8,
  "booking_date": "2026-08-15",
  "time_slot": "14:00",
  "user_id": 123
}
```

---

### 4.7 EventOS & Vendor Marketplace

#### `GET /api/v1/vendors`
List active vendors in the Sponzar event marketplace with category filters and ratings.
* **Scope Required:** `creators.read`
* **Query Parameters:**
  * `category` (optional, string: `Security`, `Catering`, `Audio/Visual`, `Logistics`)
  * `search` (optional, string)
  * `per_page` (optional, integer: 1-50, default: 15)
* **Response Example:**
```json
{
  "data": [
    {
      "id": 1,
      "business_name": "Apex Security Services",
      "category": "Security",
      "description": "Licensed VIP close protection and crowd control staff.",
      "average_rating": 4.9,
      "review_count": 38,
      "services_count": 3,
      "user": {
        "id": 14,
        "name": "David Ndlovu",
        "username": "apexsec",
        "avatar": "https://sponzar.africa/public/avatar/apex.jpg"
      }
    }
  ],
  "meta": { "current_page": 1, "last_page": 1, "per_page": 15, "total": 1 }
}
```

#### `GET /api/v1/vendors/{id}`
Get full vendor profile including all active bookable services and price structures.
* **Scope Required:** `creators.read`

#### `GET /api/v1/vendors/services`
Search across active vendor services with pricing filters.
* **Scope Required:** `creators.read`
* **Query Parameters:**
  * `vendor_id` (optional, integer)
  * `category` (optional, string)
  * `pricing_type` (optional: `hour`, `day`, `event`, `unit`)
  * `search` (optional, string)

#### `POST /api/v1/vendors/services/{id}/hire`
Initialize an Escrow contract to hire a vendor for an event. Funds are locked securely in Sponzar Escrow until work is delivered and approved.
* **Scope Required:** `bookings`
* **Request Body:**
```json
{
  "user_id": 42,
  "event_id": 105,
  "details": "Require 4 security guards for concert venue gate entry from 16:00 to 23:00."
}
```
* **Response Example (`201 Created`):**
```json
{
  "data": {
    "contract_id": 89,
    "reference_id": "ESCROW-2026-X9K2PL",
    "amount": 2500.00,
    "escrow_fee": 125.00,
    "total_charge": 2625.00,
    "currency": "ZAR",
    "state": "pending",
    "vendor": {
      "business_name": "Apex Security Services",
      "service": "Event Security Guard (Day Rate)"
    },
    "message": "Escrow contract initialized. Proceed to funding to confirm booking."
  }
}
```

---

### 4.8 Webhooks Management

#### `GET /api/v1/webhooks`
List active webhook endpoints.
* **Scope Required:** `webhooks`

#### `POST /api/v1/webhooks`
Register a new webhook endpoint.
* **Scope Required:** `webhooks`
* **Request Body:**
```json
{
  "url": "https://example.com/api/sponzar-webhook",
  "events": ["payment.completed", "subscription.created", "ticket.purchased"]
}
```

---

## 5. Rate Limiting & HTTP Status Codes

### Rate Limits
* Standard Tier: **60 requests / minute per API key**.
* Pro Tier: **300 requests / minute per API key**.
* When exceeded, the API returns HTTP Status `429 Too Many Requests` with response header `Retry-After: 60`.

### Standard Error Codes

| Status Code | Meaning | Cause / Remediation |
|---|---|---|
| `200 OK` | Success | Request succeeded. |
| `201 Created` | Created | Resource created successfully. |
| `400 Bad Request` | Validation Error | Missing or invalid parameters in request body. |
| `401 Unauthorized` | Invalid API Key | `X-Api-Key` header missing or invalid key format. |
| `403 Forbidden` | Scope Violation | API key lacks required permission scope. |
| `404 Not Found` | Resource Missing | Endpoint or target resource ID does not exist. |
| `429 Too Many Requests` | Rate Limit Exceeded | Slow down request frequency or upgrade API quota. |
| `500 Server Error` | System Error | Internal anomaly; check error message response. |

---

## 6. Support & Resources
* **API Portal:** `https://sponzar.africa/developer`
* **Embed SDK Guide:** [docs/embed_sdk_manual.md](file:///home/sponzar.africa/public_html/docs/embed_sdk_manual.md)
* **WordPress Plugin Guide:** [docs/wordpress_plugin_manual.md](file:///home/sponzar.africa/public_html/docs/wordpress_plugin_manual.md)
