# Stripe Setup Guide for Plugin Compass

This guide will walk you through setting up Stripe for Plugin Compass to process payments and manage subscriptions for the Professional and Agency plans.

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Create a Stripe Account](#create-a-stripe-account)
3. [Get Your API Keys](#get-your-api-keys)
4. [Configure Environment Variables](#configure-environment-variables)
5. [Create Products and Prices](#create-products-and-prices)
6. [Set Up Webhooks](#set-up-webhooks)
7. [Testing with Stripe Test Mode](#testing-with-stripe-test-mode)
8. [Going Live](#going-live)
9. [Troubleshooting](#troubleshooting)

## Prerequisites

Before you begin, ensure you have:
- Access to your server's environment variables
- Admin/root access to the Plugin Compass deployment
- A verified business email address
- Business registration details (for live mode)

## Create a Stripe Account

1. Go to [https://dashboard.stripe.com/register](https://dashboard.stripe.com/register)
2. Sign up with your business email
3. Verify your email address
4. Complete your business profile:
   - Business name: "Plugin Compass" (or your business name)
   - Business type
   - Industry: "Software as a Service (SaaS)"
   - Website URL
   - Support email

## Get Your API Keys

### Test Mode Keys (for development)

1. Log into your Stripe Dashboard
2. Ensure you're in **Test mode** (toggle in the top right)
3. Navigate to **Developers** → **API keys**
4. You'll see two keys:
   - **Publishable key** (starts with `pk_test_`)
   - **Secret key** (starts with `sk_test_`) - Click "Reveal test key"
5. Keep these keys secure - you'll need them for configuration

### Live Mode Keys (for production)

1. Complete Stripe account verification first
2. Toggle to **Live mode** in the top right
3. Navigate to **Developers** → **API keys**
4. You'll see:
   - **Publishable key** (starts with `pk_live_`)
   - **Secret key** (starts with `sk_live_`) - Click "Reveal live key"

## Configure Environment Variables

Add these environment variables to your deployment:

```bash
# Test mode (for development)
STRIPE_SECRET_KEY=sk_test_your_secret_key_here
STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key_here
# One-off top-up price IDs (one-time prices)
STRIPE_TOPUP_PRICE_FREE=price_test_free_topup
STRIPE_TOPUP_PRICE_PLUS=price_test_plus_topup
STRIPE_TOPUP_PRICE_PRO=price_test_pro_topup

# Live mode (for production)
STRIPE_SECRET_KEY=sk_live_your_secret_key_here
STRIPE_PUBLISHABLE_KEY=pk_live_your_publishable_key_here
# One-off top-up price IDs (one-time prices)
STRIPE_TOPUP_PRICE_FREE=price_live_free_topup
STRIPE_TOPUP_PRICE_PLUS=price_live_plus_topup
STRIPE_TOPUP_PRICE_PRO=price_live_pro_topup
```

### Docker/Docker Compose

Add to your `.env` file or `docker-compose.yml`:

```yaml
environment:
  - STRIPE_SECRET_KEY=sk_test_your_key
  - STRIPE_PUBLISHABLE_KEY=pk_test_your_key
```

### Kubernetes

Create a secret:

```bash
kubectl create secret generic stripe-keys \
  --from-literal=STRIPE_SECRET_KEY=sk_test_your_key \
  --from-literal=STRIPE_PUBLISHABLE_KEY=pk_test_your_key
```

### Environment Variable File

Or add to your `.env` file:

```
STRIPE_SECRET_KEY=sk_test_your_secret_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key
```

## Create Products and Prices

You need to create Products and Prices in Stripe for each plan and currency.

### Option 1: Using Stripe Dashboard (Recommended for beginners)

#### Create Professional Plan

1. Go to **Products** in the Stripe Dashboard
2. Click **+ Add product**
3. Fill in the details:
   - **Name**: Professional Plan
   - **Description**: For serious WordPress plugin developers
   - **Image**: (optional) Upload your plan icon/image

4. **Create USD Price**:
   - **Pricing model**: Standard pricing
   - **Price**: $25.00
   - **Billing period**: Monthly
   - **Currency**: USD
   - Click **Add another price** to add yearly: $20.00/month (billed annually as $240)

5. **Create GBP Price**:
   - Click **Add price** on the product page
   - **Price**: £20.00
   - **Billing period**: Monthly
   - **Currency**: GBP
   - Add yearly: £16.00/month (billed annually as £192)

6. **Create EUR Price**:
   - Click **Add price** on the product page
   - **Price**: €25.00
   - **Billing period**: Monthly
   - **Currency**: EUR
   - Add yearly: €20.00/month (billed annually as €240)

#### Create Agency Plan

Repeat the same process with these prices:

- **USD**: $99/month, $79/month (yearly)
- **GBP**: £79/month, £63/month (yearly)
- **EUR**: €99/month, €79/month (yearly)

### Create Token Top-up Products

Create three one-time products to power the `/topup` purchase page:

1. Add a **Free/Starter Top-up** product (one-time) with a single price (e.g., $15 for 500k credits).
2. Add a **Plus Top-up** product (one-time) with a single price (e.g., $25 for 1M credits).
3. Add a **Pro Top-up** product (one-time) with a single price (e.g., $40 for 1M pro-tier credits).

Copy the resulting Price IDs into the environment variables:

- `STRIPE_TOPUP_PRICE_FREE`
- `STRIPE_TOPUP_PRICE_PLUS`
- `STRIPE_TOPUP_PRICE_PRO`

The app automatically applies a 2.5% discount for Business plans and a 5% discount for Enterprise plans during checkout. Successful payments redirect back to `/topup`, confirm the Stripe session, and immediately add the purchased credits to the user's balance.

### Option 2: Using Stripe CLI (Advanced)

Install the [Stripe CLI](https://stripe.com/docs/stripe-cli) and run:

```bash
# Professional Plan - USD
stripe products create \
  --name="Professional Plan" \
  --description="For serious WordPress plugin developers"

# Get the product ID (e.g., prod_xxxxx) and create prices:
stripe prices create \
  --product=prod_xxxxx \
  --unit-amount=2500 \
  --currency=usd \
  --recurring[interval]=month

stripe prices create \
  --product=prod_xxxxx \
  --unit-amount=24000 \
  --currency=usd \
  --recurring[interval]=year

# Repeat for GBP (2000 pence = £20) and EUR (2500 cents = €25)
```

### Copy Price IDs

After creating prices, you'll see Price IDs like `price_xxxxx`. You'll need these for:
- Checkout page integration
- Subscription management
- Webhook handling

Store them in your environment variables if needed:

```bash
STRIPE_PRICE_PROFESSIONAL_USD_MONTHLY=price_xxxxx
STRIPE_PRICE_PROFESSIONAL_USD_YEARLY=price_xxxxx
STRIPE_PRICE_PROFESSIONAL_GBP_MONTHLY=price_xxxxx
# ... etc
```

## Set Up Webhooks

Webhooks allow Stripe to notify your application about payment events.

### Configure Webhook Endpoint

1. Go to **Developers** → **Webhooks**
2. Click **+ Add endpoint**
3. Enter your endpoint URL:
   - Test: `https://your-test-domain.com/api/stripe/webhook`
   - Live: `https://plugincompass.com/api/stripe/webhook`
4. Select events to listen to:
   - `customer.subscription.created`
   - `customer.subscription.updated`
   - `customer.subscription.deleted`
   - `invoice.payment_succeeded`
   - `invoice.payment_failed`
   - `payment_method.attached`
   - `payment_method.detached`
5. Click **Add endpoint**
6. Copy the **Signing secret** (starts with `whsec_`)

### Add Webhook Secret to Environment

```bash
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret_here
```

### Test Webhook Locally

Using Stripe CLI:

```bash
stripe listen --forward-to localhost:4000/api/stripe/webhook
```

This will give you a webhook signing secret for local testing.

## Testing with Stripe Test Mode

Stripe provides test card numbers for testing payments:

### Test Cards

| Card Number         | Scenario                          |
|---------------------|-----------------------------------|
| 4242 4242 4242 4242 | Successful payment                |
| 4000 0027 6000 3184 | Requires 3D Secure authentication |
| 4000 0000 0000 9995 | Declined card                     |
| 4000 0000 0000 0341 | Attaching card fails              |

**For all test cards:**
- Use any future expiration date (e.g., 12/34)
- Use any 3-digit CVC (e.g., 123)
- Use any 5-digit ZIP code (e.g., 12345)

### Test the Payment Flow

1. Go to your pricing page
2. Select a plan (Professional or Agency)
3. Enter test card details
4. Complete the payment
5. Verify in Stripe Dashboard:
   - Go to **Payments** to see the test payment
   - Go to **Customers** to see the test customer
   - Go to **Subscriptions** to see active test subscriptions

## Going Live

### Before Going Live Checklist

- [ ] Complete Stripe account verification (identity, business, banking)
- [ ] Add payout/bank account information
- [ ] Test all payment flows in test mode
- [ ] Test webhook handling
- [ ] Set up email notifications
- [ ] Configure tax settings (if applicable)
- [ ] Review pricing and product descriptions
- [ ] Set up dispute handling process
- [ ] Configure automatic subscription management
- [ ] Test cancellation and refund flows

### Activate Live Mode

1. Complete all required verification steps in Stripe Dashboard
2. Submit your application for review (may take 1-2 business days)
3. Once approved, toggle to **Live mode**
4. Update environment variables with live API keys:
   ```bash
   STRIPE_SECRET_KEY=sk_live_your_live_key
   STRIPE_PUBLISHABLE_KEY=pk_live_your_live_key
   ```
5. Recreate products and prices in Live mode (or copy from test mode)
6. Create a new webhook endpoint for live mode
7. Update webhook secret in environment variables
8. Deploy the changes to production
9. Test with a real card (or your own card) to verify

### Security Recommendations

1. **Never commit API keys to version control**
2. **Use environment variables** for all keys
3. **Rotate keys periodically** (every 90 days recommended)
4. **Set up Stripe Radar** for fraud prevention
5. **Enable 3D Secure** for European customers (PSD2 compliance)
6. **Log all payment events** for audit trails
7. **Monitor webhook delivery** in Stripe Dashboard
8. **Set up alerts** for failed payments and disputes

## Troubleshooting

### Common Issues

#### 1. "No such customer" error

**Solution**: Ensure the customer is created before attempting to create/attach payment methods:

```javascript
// First check if customer exists
let customer;
if (user.stripeCustomerId) {
  try {
    customer = await stripe.customers.retrieve(user.stripeCustomerId);
  } catch (err) {
    customer = null;
  }
}

// Create if doesn't exist
if (!customer) {
  customer = await stripe.customers.create({
    email: user.email,
    metadata: { userId: user.id }
  });
}
```

#### 2. Webhook signature verification fails

**Causes**:
- Wrong webhook secret in environment variables
- Request body was modified before verification
- Using test secret with live mode (or vice versa)

**Solution**: Verify webhook secret matches the endpoint, and raw request body is used for verification.

#### 3. "Invalid API Key" error

**Solution**: 
- Check you're using the correct key for the mode (test vs live)
- Verify no extra spaces or quotes in environment variables
- Check key hasn't been rolled/revoked in Stripe Dashboard

#### 4. Payment method attachment fails

**Solution**: Ensure you're passing the payment method ID (starts with `pm_`), not the card token.

#### 5. Currency mismatch errors

**Solution**: When creating a subscription, ensure the price ID matches the customer's selected currency.

### Debug Mode

Enable Stripe debug logging:

```javascript
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY, {
  apiVersion: '2024-06-20',
  maxNetworkRetries: 2,
  telemetry: false, // Disable telemetry in production
  appInfo: {
    name: 'Plugin Compass',
    version: '1.0.0',
  }
});

// Log all requests (development only)
if (process.env.NODE_ENV === 'development') {
  stripe._emitter.on('request', (request) => {
    console.log('Stripe request:', request);
  });
}
```

### Support Resources

- **Stripe Documentation**: https://stripe.com/docs
- **Stripe Support**: https://support.stripe.com
- **Stripe Discord**: https://stripe.com/discord
- **Stripe API Reference**: https://stripe.com/docs/api
- **Test Card Numbers**: https://stripe.com/docs/testing

## Additional Configuration

### Subscription Management

The application automatically handles:
- Payment method storage (encrypted in Stripe)
- Subscription creation and updates
- Plan upgrades/downgrades
- Cancellations and pause/resume
- Failed payment retry logic

### Plan Comparison

| Plan         | USD/month | GBP/month | EUR/month | Apps | Features                 |
|--------------|-----------|-----------|-----------|------|--------------------------|
| Hobby        | Free      | Free      | Free      | 3    | Basic features           |
| Professional | $25       | £20       | €25       | 20   | All features + priority  |
| Agency       | $99       | £79       | €99       | ∞    | Everything + white-label |

### Currency Detection

The app automatically detects user currency based on:
1. Previously saved preference (localStorage)
2. Browser language/region (navigator.languages)
3. Timezone (Intl.DateTimeFormat)
4. Fallback to USD if detection fails

Users can manually change currency using the dropdown on pricing pages.

## Compliance

### GDPR (Europe)

- Stripe is GDPR compliant
- Customer data is stored securely
- Users can request data deletion
- Cookie consent required for tracking

### PSD2 (Europe)

- 3D Secure authentication required for European cards
- Automatically handled by Stripe Elements
- No additional code needed

### PCI DSS

- Never store raw card numbers
- Use Stripe Elements for card input
- Stripe handles PCI compliance
- Annual compliance verification required

## Next Steps

1. ✅ Complete Stripe account setup
2. ✅ Configure environment variables
3. ✅ Create products and prices
4. ✅ Set up webhooks
5. ✅ Test in test mode
6. ✅ Go live with real payments
7. ✅ Monitor payments and subscriptions
8. ✅ Set up customer support for billing issues

For technical support or questions about the Plugin Compass Stripe integration, please refer to the main documentation or contact support.
