# Payments

## Payments

Directories are a wonderful way to earn money, so it comes with a full payment process built-in.

DirectoryFast provides a comprehensive monetization platform with multiple revenue streams, powered by Polar for secure payment processing.

> **Why Polar?** Developer-first infrastructure with native TypeScript support, superior webhook handling, and seamless integration with modern auth systems.

### Quick Setup

#### 1. Create Polar Account

1. **Sign up** at [polar.sh](https://polar.sh)
2. **Create an organization** for your directory
3. **Get your access tokens** from both production and sandbox dashboards

#### 2. Configure Environment Variables

Add these to your `.env` file:

```bash
# Polar Production Configuration (for live payments)
POLAR_ACCESS_TOKEN_PROD=your-polar-production-access-token
POLAR_WEBHOOK_SECRET=your-polar-webhook-secret

# Polar Sandbox Configuration (for testing)
POLAR_ACCESS_TOKEN_SANDBOX=your-polar-sandbox-access-token
```

#### 3. Admin Configuration

Navigate to `/dashboard/admin/settings` to access the new separated settings:

1. **Monetization Settings** - Configure Polar sandbox/production mode via database
2. **General Settings** - Site configuration
3. **Features Settings** - Enable/disable site features
4. **Other Settings** - Layout, themes, SEO, social media

#### 4. Auto-Sync Products from Polar

**NEW:** DirectoryFast now automatically syncs products from your Polar dashboard:

1. **Navigate to** `/dashboard/admin/monetization`
2. **Click "Sync from Polar"** button to fetch all products
3. **Products are automatically imported** with current names and pricing
4. **Assign feature types** to enable different monetization features

#### 5. Setup Webhooks

**Webhook endpoint:** `https://yourdomain.com/api/polar/webhooks`

1. **Go to Polar dashboard** → Settings → Webhooks
2. **Create new webhook** with your domain endpoint
3. **Select events:** `order.created`, `subscription.created`, `subscription.updated`
4. **Add webhook secret** to your environment variables

### Monetization Features

#### Featured Product Payments

Traditional featured listings with enhanced visibility:

* **30-day placement** in featured sections
* **Enhanced visibility** throughout the site
* **Automatic expiration** and renewal options
* **Revenue tracking** and analytics

#### Paid Submissions

**NEW in v1.6.0** - Multiple submission tiers for faster processing:

**Express Submission**

* **Priority review queue**
* **24-48 hour processing** time
* **Standard listing placement**
* **Submission status tracking**

**Premium Submission**

* **Same-day review** process
* **Featured placement** for 7 days
* **Priority customer support**
* **Social media promotion**

**Free Submission (Optional)**

* **Manual review process**
* **7-14 days processing** time
* **Admin configurable** (can be disabled)

#### Advertising System

**NEW in v1.6.0** - Complete advertising platform with multiple placement options:

**Available Ad Placements**

* **Homepage Hero** - Prime banner placement (up to 4 ads)
* **Product Page Sidebar** - Product page sidebar placement (up to 4 ads)
* **Blog Sidebar** - Blog post sidebar placement (up to 4 ads)
* **Collection Page** - Collection page banner placement (up to 4 ads)
* **Category Page** - Category page banner placement (up to 4 ads)

**Ad Features**

* **Monthly flat-rate pricing** (no CPC/CPM complexity)
* **Capacity management** (maximum ads per placement)
* **Real-time approval workflow**
* **Revenue tracking and analytics**
* **Campaign management dashboard**

### Product Management

#### Feature Type System

Products can be assigned different feature types in the admin dashboard:

* `featured` - Traditional featured product listings
* `express_submission` - Fast-track submission processing (24-48h)
* `premium_submission` - Same-day review + featured placement
* `ads_homepage_hero` - Homepage hero banner placement
* `ads_product_page` - Product page sidebar placement
* `ads_blog_sidebar` - Blog post sidebar placement
* `ads_collection_page` - Collection page placement
* `ads_category_page` - Category page placement
* `unused` - Products not configured for any feature

#### Auto-Sync Capabilities

* **Automatic product discovery** from Polar dashboard
* **Real-time price updates** when syncing
* **Preserved manual configurations** (slugs, feature types, status)
* **Batch import** of all Polar products with one click
* **Error handling** for missing or invalid products

### Implementation Details

#### Enhanced Checkout Flow

```javascript
// Product submission with tier selection
const handlePaidSubmission = async (submissionType: 'free' | 'express' | 'premium') => {
  try {
    const response = await fetch('/api/submit-paid', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        productTitle,
        productOwner,
        productCategory,
        productUrl,
        productComment,
        submissionType
      })
    });
    
    const { checkoutUrl } = await response.json();
    if (checkoutUrl) {
      window.location.href = checkoutUrl;
    }
  } catch (error) {
    console.error('Submission failed:', error);
  }
};
```

#### Advertising Checkout

```javascript
// Ad campaign creation
const handleAdPurchase = async (campaignData: AdCampaignData) => {
  try {
    const response = await fetch('/api/ads/checkout', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ campaignData })
    });
    
    const { checkoutUrl } = await response.json();
    window.location.href = checkoutUrl;
  } catch (error) {
    console.error('Ad purchase failed:', error);
  }
};
```

#### Enhanced Webhook Processing

```javascript
// Webhook handling for multiple payment types
if (event.type === 'order.created' && order.state === 'succeeded') {
  const { type, submissionType, campaign_id, ad_id } = order.metadata;
  
  // Route to appropriate handler
  if (type === 'paid_submission') {
    await handlePaidSubmission(payload, userEmail, orderId, metadata);
  } else if (campaign_id || ad_id) {
    await handleAdCampaignPayment(payload, userEmail, orderId, metadata);
  } else if (metadata.productSlug) {
    await handleFeaturedProduct(payload, userEmail, orderId, metadata);
  }
}
```

### Admin Configuration

#### Settings Organization

**NEW in v1.6.0:** Settings are now organized into separate pages for better navigation:

Access settings at `/dashboard/admin/settings/`:

* **General** (`/general`) - Site title, description, logo, domain
* **Layout** (`/layout`) - Page layouts, card styles, visual structure
* **Themes** (`/themes`) - Color schemes, fonts, visual appearance
* **Features** (`/features`) - Site features, integrations, functionality
* **SEO** (`/seo`) - Search engine optimization, structured data
* **Social Media** (`/social`) - Social media links, external profiles

#### Monetization Dashboard

Access comprehensive monetization controls at `/dashboard/admin/monetization`:

* **Product Management** - Sync and configure Polar products
* **Feature Type Assignment** - Map products to directory features
* **Submission Settings** - Configure paid submission options
* **Advertising Settings** - Enable/disable advertising system
* **Revenue Analytics** - Track income across all features

#### Polar Configuration

Configure Polar settings in the admin dashboard:

* **Sandbox/Production Mode** - Database-controlled switching
* **Token Status** - View configuration status of all tokens
* **Immediate Switching** - Toggle between environments without redeployment

### Customer Portal

Users can manage their billing through:

* **Sidebar billing button** in dashboard
* **Automatic redirection** to Polar customer portal
* **Subscription management** and billing history
* **Invoice downloads** and payment tracking

### Revenue Tracking

#### Analytics Dashboard

Track revenue across all monetization features:

* **Featured product revenue** with duration tracking
* **Paid submission revenue** by tier
* **Advertising revenue** by placement and campaign
* **Monthly/annual revenue trends**
* **Customer lifetime value** tracking

### Troubleshooting

#### Common Issues

1. **Sync fails**: Check token validity for current environment
2. **Webhook not receiving**: Verify endpoint URL and secret
3. **Products not appearing**: Ensure products are active in Polar
4. **Feature types not working**: Check product configuration in monetization dashboard
5. **Environment switching**: Use admin dashboard, not environment variables
6. **Token configuration**: Ensure both production and sandbox tokens are set

#### Debug Mode

Enable detailed logging by setting:

```bash
DEBUG_POLAR=true
```

This will log all Polar API interactions and webhook events for troubleshooting.

#### Webhook Testing

Test webhook delivery using Polar's webhook testing tools or ngrok for local development:

```bash
# For local development
ngrok http 3000
# Then use the ngrok URL + /api/polar/webhooks as your webhook endpoint
```

### Environment Variables Reference

#### Required Variables

```bash
# Production environment
POLAR_ACCESS_TOKEN_PROD=your-production-access-token

# Sandbox environment  
POLAR_ACCESS_TOKEN_SANDBOX=your-sandbox-access-token

# Shared webhook secret
POLAR_WEBHOOK_SECRET=your-webhook-secret
```
