# Payment Provider Integrations

> External payment processor integration documentation.

---

## Overview

Aphrodite integrates with multiple payment processors optimized for adult
content platforms.

| Provider | Type          | Use Case                |
| -------- | ------------- | ----------------------- |
| CCBill   | Adult-focused | Primary card processing |
| SegPay   | Adult-focused | Alternative processor   |
| Epoch    | Adult-focused | Token-based payments    |
| Stripe   | General       | Non-adult transactions  |

---

## CCBill

**API Documentation:** https://ccbill.com/docs

### Configuration

```typescript
interface CCBillConfig {
  apiUrl: string; // Production or sandbox URL
  clientAccnum: string; // Account number
  clientSubacc: string; // Sub-account number
  webhookSecret: string; // Webhook signature secret
  flexFormId: string; // FlexForms form ID
  salt: string; // Dynamic pricing salt
}
```

### Generate Payment URL

```typescript
function generateCCBillUrl(
  config: CCBillConfig,
  payment: PaymentParams
): string {
  const digest = createMd5(
    `${payment.price}${payment.period}${payment.currencyCode}${config.salt}`
  );

  const params = new URLSearchParams({
    clientAccnum: config.clientAccnum,
    clientSubacc: config.clientSubacc,
    formName: config.flexFormId,
    price: payment.price.toFixed(2),
    currencyCode: payment.currencyCode,
    formPeriod: payment.period.toString(),
    formDigest: digest,
    custom_userId: payment.userId,
    custom_productId: payment.productId,
  });

  return `${config.apiUrl}/wap-frontflex/flexforms/${config.flexFormId}?${params}`;
}
```

### Webhook Handler

```typescript
app.post('/webhooks/ccbill', async (req, res) => {
  const { eventType, subscriptionId, transactionId } = req.body;

  // Verify signature
  const signature = req.headers['x-ccbill-signature'];
  if (!verifySignature(req.body, signature, config.webhookSecret)) {
    return res.status(401).send('Invalid signature');
  }

  switch (eventType) {
    case 'NewSaleSuccess':
      await handleNewSale(req.body);
      break;
    case 'RenewalSuccess':
      await handleRenewal(req.body);
      break;
    case 'Cancellation':
      await handleCancellation(req.body);
      break;
    case 'Chargeback':
      await handleChargeback(req.body);
      break;
  }

  res.status(200).send('OK');
});
```

---

## SegPay

**API Documentation:** https://segpay.com/docs

### Configuration

```typescript
interface SegPayConfig {
  apiUrl: string;
  vendorId: string;
  apiKey: string;
  webhookSecret: string;
}
```

### Generate Payment URL

```typescript
function generateSegPayUrl(
  config: SegPayConfig,
  payment: PaymentParams
): string {
  const params = new URLSearchParams({
    vendorId: config.vendorId,
    price: payment.price.toFixed(2),
    currency: payment.currencyCode,
    description: payment.description,
    x_custom_userId: payment.userId,
    x_custom_productId: payment.productId,
    successUrl: payment.successUrl,
    failUrl: payment.failUrl,
  });

  return `${config.apiUrl}/checkout?${params}`;
}
```

---

## Epoch

**API Documentation:** https://epoch.com/docs

### Configuration

```typescript
interface EpochConfig {
  apiUrl: string;
  clientId: string;
  apiSecret: string;
  piCode: string;
}
```

### Token Purchase Flow

```typescript
async function initiateEpochPurchase(
  config: EpochConfig,
  purchase: TokenPurchase
): Promise<string> {
  const response = await fetch(`${config.apiUrl}/v2/purchase`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Basic ${btoa(`${config.clientId}:${config.apiSecret}`)}`,
    },
    body: JSON.stringify({
      pi_code: config.piCode,
      amount: purchase.amount,
      currency: purchase.currency,
      customer_id: purchase.userId,
      return_url: purchase.returnUrl,
    }),
  });

  const data = await response.json();
  return data.redirect_url;
}
```

---

## Stripe (Non-Adult)

**API Documentation:** https://stripe.com/docs

### Configuration

```typescript
interface StripeConfig {
  secretKey: string;
  publishableKey: string;
  webhookSecret: string;
}
```

### Create Payment Intent

```typescript
import Stripe from 'stripe';

const stripe = new Stripe(config.secretKey);

async function createPaymentIntent(
  payment: PaymentParams
): Promise<Stripe.PaymentIntent> {
  return stripe.paymentIntents.create({
    amount: payment.amount * 100, // cents
    currency: payment.currency,
    metadata: {
      userId: payment.userId,
      productId: payment.productId,
    },
  });
}
```

### Webhook Handler

```typescript
app.post('/webhooks/stripe', async (req, res) => {
  const sig = req.headers['stripe-signature'];
  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(req.body, sig, config.webhookSecret);
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  switch (event.type) {
    case 'payment_intent.succeeded':
      await handlePaymentSuccess(event.data.object);
      break;
    case 'payment_intent.payment_failed':
      await handlePaymentFailed(event.data.object);
      break;
  }

  res.json({ received: true });
});
```

---

## In-App Purchases

### Apple App Store

```typescript
import { AppStoreServerAPI } from '@apple/app-store-server-library';

const appStoreClient = new AppStoreServerAPI(
  privateKey,
  keyId,
  issuerId,
  bundleId,
  Environment.PRODUCTION
);

async function verifyReceipt(receiptData: string): Promise<boolean> {
  const response = await appStoreClient.getTransactionInfo(receiptData);
  return response.signedTransactionInfo !== null;
}
```

### Google Play

```typescript
import { google } from 'googleapis';

const playDeveloperApi = google.androidpublisher('v3');

async function verifyPurchase(
  packageName: string,
  productId: string,
  token: string
): Promise<boolean> {
  const response = await playDeveloperApi.purchases.products.get({
    packageName,
    productId,
    token,
  });

  return response.data.purchaseState === 0; // Purchased
}
```

---

## Security Best Practices

1. **Webhook Verification**: Always verify webhook signatures
2. **Idempotency**: Use idempotency keys for all transactions
3. **PCI Compliance**: Never store raw card data
4. **Secure Secrets**: Store API keys in vault, not code
5. **Rate Limiting**: Implement rate limits on payment endpoints
6. **Logging**: Log all transactions (excluding sensitive data)

---

## Document History

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