# Payment Service API

> REST API documentation for the Aphrodite Payment Service.

**Base URL:** `https://api.aphrodite.example.com/api/v1/payments` **Port:** 4000
**Authentication:** JWT Bearer Token

---

## Table of Contents

1. [Token/Credit System](#tokencredit-system)
2. [Purchases](#purchases)
3. [Tipping](#tipping)
4. [Creator Earnings](#creator-earnings)
5. [Payouts](#payouts)
6. [Payment Methods](#payment-methods)
7. [Tax Documents](#tax-documents)
8. [Webhooks](#webhooks)

---

## Token/Credit System

### Get Token Balance

```http
GET /balance
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "balance": 1250,
    "pendingBalance": 50,
    "currency": "tokens",
    "equivalentUsd": 125.0,
    "lastUpdated": "2026-01-18T12:00:00.000Z"
  }
}
```

---

### Get Token Packages

```http
GET /packages
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": [
    {
      "id": "pkg_100",
      "name": "Starter",
      "tokens": 100,
      "price": 9.99,
      "currency": "USD",
      "bonusTokens": 0,
      "popular": false
    },
    {
      "id": "pkg_250",
      "name": "Basic",
      "tokens": 250,
      "price": 24.99,
      "currency": "USD",
      "bonusTokens": 10,
      "popular": false
    },
    {
      "id": "pkg_550",
      "name": "Popular",
      "tokens": 550,
      "price": 49.99,
      "currency": "USD",
      "bonusTokens": 50,
      "popular": true
    },
    {
      "id": "pkg_1200",
      "name": "Premium",
      "tokens": 1200,
      "price": 99.99,
      "currency": "USD",
      "bonusTokens": 150,
      "popular": false
    },
    {
      "id": "pkg_2750",
      "name": "VIP",
      "tokens": 2750,
      "price": 199.99,
      "currency": "USD",
      "bonusTokens": 500,
      "popular": false
    }
  ]
}
```

---

### Purchase Tokens

```http
POST /purchase/tokens
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "packageId": "pkg_550",
  "paymentMethodId": "pm_abc123",
  "idempotencyKey": "idem_xyz789"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "transactionId": "txn_abc123",
    "status": "completed",
    "tokensAdded": 600,
    "baseTokens": 550,
    "bonusTokens": 50,
    "newBalance": 1850,
    "amount": 49.99,
    "currency": "USD",
    "paymentMethod": {
      "type": "card",
      "last4": "4242",
      "brand": "visa"
    },
    "createdAt": "2026-01-18T12:00:00.000Z"
  }
}
```

**3D Secure Required:**

```json
{
  "success": true,
  "data": {
    "transactionId": "txn_abc123",
    "status": "requires_action",
    "actionType": "3ds_authentication",
    "redirectUrl": "https://checkout.stripe.com/3ds/...",
    "returnUrl": "https://aphrodite.example.com/payment/complete"
  }
}
```

---

### Get Transaction History

```http
GET /transactions?type=all&cursor=<cursor>&limit=20
Authorization: Bearer <access_token>
```

**Query Parameters:**

| Parameter | Type   | Description                                |
| --------- | ------ | ------------------------------------------ |
| `type`    | string | Filter: `all`, `purchase`, `tip`, `payout` |
| `from`    | string | Start date (ISO 8601)                      |
| `to`      | string | End date (ISO 8601)                        |
| `cursor`  | string | Pagination cursor                          |
| `limit`   | number | Items per page (default: 20, max: 100)     |

**Response (200 OK):**

```json
{
  "success": true,
  "data": [
    {
      "id": "txn_abc123",
      "type": "purchase",
      "amount": 49.99,
      "currency": "USD",
      "tokens": 600,
      "status": "completed",
      "description": "Token package: Popular",
      "createdAt": "2026-01-18T12:00:00.000Z"
    },
    {
      "id": "txn_def456",
      "type": "tip",
      "amount": -100,
      "currency": "tokens",
      "recipient": {
        "id": "usr_xyz789",
        "username": "janedoe"
      },
      "status": "completed",
      "description": "Tip during stream",
      "createdAt": "2026-01-18T11:30:00.000Z"
    }
  ],
  "pagination": {
    "cursor": "next_cursor",
    "hasMore": true
  }
}
```

---

## Purchases

### Purchase Content

```http
POST /purchase/content
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "contentId": "cnt_abc123",
  "contentType": "vod",
  "price": 50,
  "currency": "tokens"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "purchaseId": "pur_abc123",
    "contentId": "cnt_abc123",
    "contentType": "vod",
    "price": 50,
    "accessGranted": true,
    "expiresAt": null,
    "createdAt": "2026-01-18T12:00:00.000Z"
  }
}
```

---

### Check Content Access

```http
GET /access/:contentId
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "contentId": "cnt_abc123",
    "hasAccess": true,
    "accessType": "purchased",
    "purchasedAt": "2026-01-18T12:00:00.000Z",
    "expiresAt": null
  }
}
```

---

### Purchase Ticket Show Access

```http
POST /purchase/ticket
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "showId": "show_abc123",
  "ticketType": "standard"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "ticketId": "tkt_abc123",
    "showId": "show_abc123",
    "ticketType": "standard",
    "price": 200,
    "currency": "tokens",
    "showStartsAt": "2026-01-18T20:00:00.000Z",
    "accessUrl": "https://stream.aphrodite.example.com/show/abc123?ticket=tkt_abc123"
  }
}
```

---

## Tipping

### Send Tip

```http
POST /tips
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "recipientId": "usr_xyz789",
  "amount": 100,
  "message": "Great stream!",
  "isAnonymous": false,
  "triggerDevice": true,
  "streamId": "str_abc123"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "tipId": "tip_abc123",
    "amount": 100,
    "currency": "tokens",
    "recipient": {
      "id": "usr_xyz789",
      "username": "janedoe"
    },
    "message": "Great stream!",
    "isAnonymous": false,
    "newBalance": 1150,
    "createdAt": "2026-01-18T12:00:00.000Z"
  }
}
```

---

### Get Tip Menu

```http
GET /tips/menu/:creatorId
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "creatorId": "usr_xyz789",
    "items": [
      {
        "id": "menu_1",
        "name": "Flash",
        "description": "Quick flash",
        "price": 50,
        "category": "actions",
        "duration": 3,
        "deviceAction": {
          "type": "vibrate",
          "intensity": 50,
          "duration": 3
        }
      },
      {
        "id": "menu_2",
        "name": "High Vibration",
        "description": "30 seconds of high vibration",
        "price": 100,
        "category": "devices",
        "duration": 30,
        "deviceAction": {
          "type": "vibrate",
          "intensity": 100,
          "duration": 30
        }
      },
      {
        "id": "menu_3",
        "name": "Song Request",
        "description": "Request a song",
        "price": 25,
        "category": "requests",
        "duration": null,
        "deviceAction": null
      }
    ],
    "categories": ["actions", "devices", "requests"]
  }
}
```

---

### Tip to Goal

```http
POST /tips/goal
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "goalId": "goal_abc123",
  "amount": 50,
  "message": "Let's hit this goal!"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "tipId": "tip_def456",
    "goalId": "goal_abc123",
    "amount": 50,
    "goalProgress": {
      "current": 284,
      "target": 500,
      "percentage": 56.8
    },
    "newBalance": 1100,
    "createdAt": "2026-01-18T12:00:00.000Z"
  }
}
```

---

### Get Tip Leaderboard

```http
GET /tips/leaderboard/:creatorId?period=week&limit=10
Authorization: Bearer <access_token>
```

**Query Parameters:**

| Parameter | Type   | Description                               |
| --------- | ------ | ----------------------------------------- |
| `period`  | string | `day`, `week`, `month`, `all`             |
| `limit`   | number | Number of entries (default: 10, max: 100) |

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "creatorId": "usr_xyz789",
    "period": "week",
    "startDate": "2026-01-12T00:00:00.000Z",
    "endDate": "2026-01-18T23:59:59.000Z",
    "leaderboard": [
      {
        "rank": 1,
        "user": {
          "id": "usr_top1",
          "username": "toptipper",
          "displayName": "Top Tipper",
          "avatarUrl": "https://cdn.aphrodite.example.com/avatars/usr_top1.jpg"
        },
        "totalTips": 5000,
        "tipCount": 42
      },
      {
        "rank": 2,
        "user": {
          "id": "usr_top2",
          "username": "generous",
          "displayName": "Generous Fan",
          "avatarUrl": "https://cdn.aphrodite.example.com/avatars/usr_top2.jpg"
        },
        "totalTips": 3500,
        "tipCount": 28
      }
    ],
    "currentUserRank": {
      "rank": 15,
      "totalTips": 250,
      "tipCount": 5
    }
  }
}
```

---

## Creator Earnings

### Get Earnings Summary

```http
GET /earnings
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "availableBalance": 1250.5,
    "pendingBalance": 150.0,
    "lifetimeEarnings": 15420.75,
    "currency": "USD",
    "period": {
      "start": "2026-01-01T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z",
      "earnings": 1400.5,
      "breakdown": {
        "tips": 850.25,
        "subscriptions": 425.0,
        "contentSales": 125.25,
        "ticketShows": 0.0
      }
    },
    "lastPayout": {
      "amount": 500.0,
      "date": "2026-01-15T00:00:00.000Z",
      "method": "bank_transfer"
    }
  }
}
```

---

### Get Detailed Earnings Report

```http
GET /earnings/report?from=2026-01-01&to=2026-01-18&groupBy=day
Authorization: Bearer <access_token>
```

**Query Parameters:**

| Parameter | Type   | Description            |
| --------- | ------ | ---------------------- |
| `from`    | string | Start date (ISO 8601)  |
| `to`      | string | End date (ISO 8601)    |
| `groupBy` | string | `day`, `week`, `month` |

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "from": "2026-01-01T00:00:00.000Z",
      "to": "2026-01-18T23:59:59.000Z"
    },
    "totals": {
      "gross": 1500.0,
      "platformFee": 300.0,
      "net": 1200.0
    },
    "breakdown": [
      {
        "date": "2026-01-18",
        "gross": 125.0,
        "platformFee": 25.0,
        "net": 100.0,
        "details": {
          "tips": 75.0,
          "subscriptions": 35.0,
          "contentSales": 15.0,
          "ticketShows": 0.0
        }
      }
    ]
  }
}
```

---

## Payouts

### Get Payout Methods

```http
GET /payouts/methods
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": [
    {
      "id": "pm_bank_1",
      "type": "bank_transfer",
      "name": "Bank of America ****1234",
      "isDefault": true,
      "status": "verified",
      "details": {
        "bankName": "Bank of America",
        "accountLast4": "1234",
        "routingLast4": "6789",
        "accountType": "checking"
      }
    },
    {
      "id": "pm_paypal_1",
      "type": "paypal",
      "name": "PayPal - j***@example.com",
      "isDefault": false,
      "status": "verified",
      "details": {
        "email": "j***@example.com"
      }
    }
  ]
}
```

---

### Add Payout Method

```http
POST /payouts/methods
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "type": "bank_transfer",
  "country": "US",
  "currency": "USD",
  "accountHolderName": "Jane Doe",
  "accountNumber": "1234567890",
  "routingNumber": "021000021",
  "accountType": "checking"
}
```

**Response (201 Created):**

```json
{
  "success": true,
  "data": {
    "id": "pm_bank_2",
    "type": "bank_transfer",
    "status": "pending_verification",
    "verificationMethod": "micro_deposits",
    "verificationDeadline": "2026-01-25T00:00:00.000Z"
  }
}
```

---

### Request Payout

```http
POST /payouts/request
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "amount": 500.00,
  "payoutMethodId": "pm_bank_1"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "payoutId": "payout_abc123",
    "amount": 500.0,
    "fee": 0.0,
    "netAmount": 500.0,
    "currency": "USD",
    "method": {
      "id": "pm_bank_1",
      "type": "bank_transfer",
      "name": "Bank of America ****1234"
    },
    "status": "processing",
    "estimatedArrival": "2026-01-21T00:00:00.000Z",
    "createdAt": "2026-01-18T12:00:00.000Z"
  }
}
```

---

### Get Payout History

```http
GET /payouts?cursor=<cursor>&limit=20
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": [
    {
      "id": "payout_abc123",
      "amount": 500.0,
      "fee": 0.0,
      "netAmount": 500.0,
      "currency": "USD",
      "method": "bank_transfer",
      "status": "completed",
      "completedAt": "2026-01-15T14:30:00.000Z",
      "createdAt": "2026-01-13T12:00:00.000Z"
    }
  ],
  "pagination": {
    "cursor": "next_cursor",
    "hasMore": true
  }
}
```

---

## Payment Methods

### Get Payment Methods

```http
GET /methods
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": [
    {
      "id": "pm_card_1",
      "type": "card",
      "brand": "visa",
      "last4": "4242",
      "expiryMonth": 12,
      "expiryYear": 2028,
      "isDefault": true
    }
  ]
}
```

---

### Add Payment Method

```http
POST /methods
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "type": "card",
  "token": "tok_stripe_token",
  "setAsDefault": true
}
```

**Response (201 Created):**

```json
{
  "success": true,
  "data": {
    "id": "pm_card_2",
    "type": "card",
    "brand": "mastercard",
    "last4": "5678",
    "expiryMonth": 6,
    "expiryYear": 2027,
    "isDefault": true
  }
}
```

---

### Delete Payment Method

```http
DELETE /methods/:methodId
Authorization: Bearer <access_token>
```

**Response (204 No Content)**

---

## Tax Documents

### Get Tax Information

```http
GET /tax
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "status": "verified",
    "formType": "W-9",
    "submittedAt": "2026-01-01T00:00:00.000Z",
    "verifiedAt": "2026-01-02T00:00:00.000Z",
    "taxId": "***-**-1234",
    "documents": [
      {
        "year": 2025,
        "type": "1099-K",
        "status": "available",
        "downloadUrl": "/api/v1/payments/tax/documents/2025/1099-K"
      }
    ]
  }
}
```

---

### Submit Tax Form

```http
POST /tax/submit
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "formType": "W-9",
  "legalName": "Jane Marie Doe",
  "businessName": null,
  "taxId": "123-45-6789",
  "address": {
    "street": "123 Main St",
    "city": "Los Angeles",
    "state": "CA",
    "postalCode": "90001",
    "country": "US"
  },
  "signature": "Jane Doe",
  "signatureDate": "2026-01-18"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "status": "pending_verification",
    "formType": "W-9",
    "submittedAt": "2026-01-18T12:00:00.000Z"
  }
}
```

---

## Webhooks

### Webhook Events

Payment webhooks are sent to registered endpoints for the following events:

| Event                         | Description                       |
| ----------------------------- | --------------------------------- |
| `payment.completed`           | Payment successfully processed    |
| `payment.failed`              | Payment processing failed         |
| `payment.refunded`            | Payment was refunded              |
| `payment.disputed`            | Chargeback/dispute initiated      |
| `subscription.created`        | New subscription created          |
| `subscription.renewed`        | Subscription successfully renewed |
| `subscription.canceled`       | Subscription canceled             |
| `subscription.payment_failed` | Subscription payment failed       |
| `payout.completed`            | Payout successfully completed     |
| `payout.failed`               | Payout failed                     |

### Webhook Payload

```json
{
  "id": "evt_abc123",
  "type": "payment.completed",
  "timestamp": "2026-01-18T12:00:00.000Z",
  "data": {
    "transactionId": "txn_xyz789",
    "userId": "usr_abc123",
    "amount": 49.99,
    "currency": "USD",
    "paymentMethod": "card"
  }
}
```

### Webhook Signature Verification

```http
POST /webhook/payments
Content-Type: application/json
X-Webhook-Signature: sha256=...

{
  "id": "evt_abc123",
  ...
}
```

Verify signature:

```typescript
import crypto from 'crypto';

function verifySignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expected =
    'sha256=' +
    crypto.createHmac('sha256', secret).update(payload).digest('hex');
  return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
```

---

## Data Types

### Transaction Object

```typescript
interface Transaction {
  id: string;
  type: 'purchase' | 'tip' | 'payout' | 'refund' | 'subscription';
  amount: number;
  currency: string;
  status: 'pending' | 'completed' | 'failed' | 'refunded';
  description?: string;
  metadata?: Record<string, unknown>;
  createdAt: string;
}
```

### Payout Object

```typescript
interface Payout {
  id: string;
  amount: number;
  fee: number;
  netAmount: number;
  currency: string;
  method: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  estimatedArrival?: string;
  completedAt?: string;
  failureReason?: string;
  createdAt: string;
}
```

---

## Document History

| Date       | Version | Changes                          |
| ---------- | ------- | -------------------------------- |
| 2026-01-18 | 1.0.0   | Initial Payment Service API docs |
