# Stripe Live Mode Deployment - Step-by-Step Guide

**Project:** Tractatus Koha Donation System
**Date:** 2025-10-18
**Current Status:** Test Mode Complete ✅
**Next Step:** Production Deployment

---

## ⚠️ Pre-Deployment Checklist

Before switching to live mode, verify:

- ✅ Test mode fully working in browser
- ✅ Webhooks tested and receiving events
- ✅ Donations recording in database correctly
- ✅ Email addresses valid (for receipt emails)
- ⚠️ Bank account connected to Stripe (required for payouts)
- ⚠️ Business verification complete (may be required)

---

## Phase 1: Stripe Dashboard - Switch to Live Mode

### Step 1.1: Access Stripe Dashboard

1. Go to https://dashboard.stripe.com
2. Log in with your Stripe account credentials
3. **Click the "Test mode" toggle** in the top-right corner
4. Switch to **"Live mode"** (toggle should turn blue/live color)

**⚠️ IMPORTANT:** From this point forward, you're working with real money and real customers.

### Step 1.2: Get Live API Keys

1. In Live Mode, click **Developers** → **API keys** in the left sidebar
2. You'll see two keys:
   - **Publishable key** (starts with `pk_live_`)
   - **Secret key** (starts with `sk_live_`)
3. **Click "Reveal test key"** next to Secret key
4. **Copy both keys** and save them securely (you'll need them soon)

```
pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

**🔒 Security:** Never commit live keys to Git. Keep them in .env only.

---

## Phase 2: Create Production Webhook

### Step 2.1: Create Webhook Endpoint

1. Still in Live Mode, go to **Developers** → **Webhooks**
2. Click **"Add endpoint"**
3. Fill in the form:

**Endpoint URL:**
```
https://agenticgovernance.digital/api/koha/webhook
```

**Description:**
```
Tractatus Koha - Production Donations
```

**Events to send:** Select these 8 events:
- ✅ `checkout.session.completed`
- ✅ `payment_intent.succeeded`
- ✅ `payment_intent.payment_failed`
- ✅ `invoice.paid`
- ✅ `invoice.payment_failed`
- ✅ `customer.subscription.created`
- ✅ `customer.subscription.updated`
- ✅ `customer.subscription.deleted`

4. Click **"Add endpoint"**

### Step 2.2: Get Webhook Signing Secret

1. After creating the endpoint, you'll see it in the list
2. Click on the endpoint to open details
3. In the "Signing secret" section, click **"Reveal"**
4. Copy the signing secret (starts with `whsec_`)

```
whsec_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

**Save this secret** - you'll add it to .env in the next phase.

---

## Phase 3: Update Production Environment Variables

### Step 3.1: Create Production .env File

⚠️ **DO NOT modify your local .env file yet!**

Create a new file for production environment variables:

```bash
# Location: /home/theflow/projects/tractatus/.env.production
```

**Content:**
```bash
# Production Environment Variables for Tractatus
NODE_ENV=production
PORT=9000
APP_NAME=Tractatus

# MongoDB (Production)
MONGODB_URI=mongodb://localhost:27017/tractatus_prod
MONGODB_PORT=27017
MONGODB_DB=tractatus_prod

# JWT Authentication
JWT_SECRET=d4d9b5ac258123dbab38abf5ca7cd6274e2247d247a5a4fc18a031853cb332ec9d661f2cdb6aac7288bfffdcfb69b7c34cef84d342c139e69064941a8525f4c5
JWT_EXPIRY=7d

# Admin
ADMIN_EMAIL=john.stroh.nz@pm.me

# Claude API
CLAUDE_API_KEY=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
CLAUDE_MODEL=claude-sonnet-4-5-20250929
CLAUDE_MAX_TOKENS=4096

# Logging
LOG_LEVEL=info
LOG_FILE=logs/app.log

# Feature Flags
ENABLE_AI_CURATION=true
ENABLE_MEDIA_TRIAGE=false
ENABLE_CASE_SUBMISSIONS=false

# Security
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# Koha Donation System - LIVE MODE
# ⚠️ REPLACE WITH YOUR ACTUAL LIVE KEYS FROM STRIPE DASHBOARD
STRIPE_SECRET_KEY=sk_live_PASTE_YOUR_LIVE_SECRET_KEY_HERE
STRIPE_PUBLISHABLE_KEY=pk_live_PASTE_YOUR_LIVE_PUBLISHABLE_KEY_HERE
STRIPE_KOHA_WEBHOOK_SECRET=whsec_PASTE_YOUR_LIVE_WEBHOOK_SECRET_HERE

# Stripe Product and Price IDs (SAME AS TEST MODE)
STRIPE_KOHA_PRODUCT_ID=prod_TFusJH4Q3br8gA
STRIPE_KOHA_5_PRICE_ID=price_1SJP2fGhfAwOYBrf9yrf0q8C
STRIPE_KOHA_15_PRICE_ID=price_1SJP2fGhfAwOYBrfNc6Nfjyj
STRIPE_KOHA_50_PRICE_ID=price_1SJP2fGhfAwOYBrf0A62TOpf

# Frontend URL (Production)
FRONTEND_URL=https://agenticgovernance.digital
```

### Step 3.2: Replace Placeholder Values

1. Open `.env.production` in your editor
2. Replace `PASTE_YOUR_LIVE_SECRET_KEY_HERE` with your actual live secret key
3. Replace `PASTE_YOUR_LIVE_PUBLISHABLE_KEY_HERE` with your actual live publishable key
4. Replace `PASTE_YOUR_LIVE_WEBHOOK_SECRET_HERE` with your actual webhook signing secret
5. **Save the file**

⚠️ **IMPORTANT:** Verify there are NO test keys (sk_test_ or pk_test_) in this file!

---

## Phase 4: Test Locally with Live Keys (OPTIONAL BUT RECOMMENDED)

Before deploying to production, test with live keys locally using a real card.

### Step 4.1: Backup Current Test .env

```bash
cp /home/theflow/projects/tractatus/.env /home/theflow/projects/tractatus/.env.test-backup
```

### Step 4.2: Temporarily Use Live Keys Locally

```bash
cp /home/theflow/projects/tractatus/.env.production /home/theflow/projects/tractatus/.env
```

### Step 4.3: Restart Server with Live Keys

```bash
# Kill existing server
pkill -9 -f "node.*server.js"

# Start with live keys
cd /home/theflow/projects/tractatus
npm start > logs/server-live-test.log 2>&1 &

# Wait for startup
sleep 4

# Check server health
curl http://localhost:9000/health
```

### Step 4.4: Make Test Donation with REAL CARD

⚠️ **You will be charged real money for this test!**

1. Go to http://localhost:9000/koha.html
2. Select the **Foundation tier ($5 NZD)**
3. Enter YOUR real email address (you'll get a receipt)
4. Click submit
5. Use a **REAL credit card** (not 4242...)
6. Complete the payment

**Expected cost:** $5 NZD (~$3 USD depending on your card)

### Step 4.5: Verify Test Donation

Check the server logs:
```bash
tail -20 logs/server-live-test.log | grep KOHA
```

Expected output:
```
[KOHA] Creating checkout session: monthly donation of NZD $5 (NZD $5)
[KOHA] Checkout session created: cs_live_...
[KOHA] Processing webhook event: checkout.session.completed
[KOHA] Donation recorded: NZD $5 (NZD $5)
```

Check Stripe Dashboard:
1. Go to https://dashboard.stripe.com (Live Mode)
2. Click **Payments**
3. You should see your $5 test payment
4. Status should be **Succeeded**

### Step 4.6: Cancel Test Subscription (Optional)

If you don't want to continue the monthly subscription:

1. Go to Stripe Dashboard → **Customers**
2. Find your test customer
3. Click on the subscription
4. Click **"Cancel subscription"**
5. Confirm cancellation

### Step 4.7: Restore Test Environment

After successful testing:
```bash
# Restore test mode .env
cp /home/theflow/projects/tractatus/.env.test-backup /home/theflow/projects/tractatus/.env

# Restart server in test mode
pkill -9 -f "node.*server.js"
npm start > logs/server-restart.log 2>&1 &
```

---

## Phase 5: Deploy to Production Server

### Step 5.1: Connect to Production Server

```bash
ssh -i ~/.ssh/tractatus_deploy ubuntu@vps-93a693da.vps.ovh.net
```

### Step 5.2: Backup Current Production .env

```bash
cd /var/www/tractatus
sudo cp .env .env.backup-$(date +%Y%m%d-%H%M%S)
```

### Step 5.3: Update Production .env

Option A: **Edit directly on server (Recommended)**
```bash
sudo nano /var/www/tractatus/.env
```

Update these lines:
```bash
# Change from test to live keys
STRIPE_SECRET_KEY=sk_live_YOUR_LIVE_SECRET_KEY
STRIPE_PUBLISHABLE_KEY=pk_live_YOUR_LIVE_PUBLISHABLE_KEY
STRIPE_KOHA_WEBHOOK_SECRET=whsec_YOUR_LIVE_WEBHOOK_SECRET

# Update database to production
MONGODB_DB=tractatus_prod

# Update frontend URL
FRONTEND_URL=https://agenticgovernance.digital
```

Save and exit (Ctrl+X, Y, Enter)

Option B: **Upload .env.production from local**
```bash
# From your LOCAL machine:
scp -i ~/.ssh/tractatus_deploy \
  /home/theflow/projects/tractatus/.env.production \
  ubuntu@vps-93a693da.vps.ovh.net:/tmp/env-production

# Then on the server:
sudo mv /tmp/env-production /var/www/tractatus/.env
sudo chown ubuntu:ubuntu /var/www/tractatus/.env
sudo chmod 600 /var/www/tractatus/.env
```

### Step 5.4: Verify .env File

```bash
# Check that live keys are present (without revealing them)
grep "STRIPE_SECRET_KEY=sk_live" /var/www/tractatus/.env && echo "✅ Live secret key configured"
grep "STRIPE_PUBLISHABLE_KEY=pk_live" /var/www/tractatus/.env && echo "✅ Live publishable key configured"
grep "STRIPE_KOHA_WEBHOOK_SECRET=whsec" /var/www/tractatus/.env && echo "✅ Webhook secret configured"
```

All three checks should print ✅.

### Step 5.5: Restart Production Server

```bash
# Check current status
sudo systemctl status tractatus

# Restart service
sudo systemctl restart tractatus

# Wait a moment
sleep 3

# Verify it started successfully
sudo systemctl status tractatus

# Check logs for errors
sudo journalctl -u tractatus -n 50 --no-pager
```

Expected output: Service should be **"active (running)"**

### Step 5.6: Test Production Endpoint

From your local machine:
```bash
curl https://agenticgovernance.digital/health
```

Expected: `{"status":"ok","timestamp":"2025-10-18T..."}`

---

## Phase 6: Verify Production Donation System

### Step 6.1: Test Donation Form

1. Open https://agenticgovernance.digital/koha.html in browser
2. Form should load correctly
3. All translations working (English, German, French)

### Step 6.2: Make First Real Donation

⚠️ **This will charge you real money!**

1. Select **Foundation tier ($5 NZD)** (smallest amount)
2. Enter YOUR real email
3. Enter your name (optional)
4. Click **"Offer Koha — Join Our Community"**
5. You should be redirected to **Stripe Checkout** (live mode)
6. Use a **REAL credit card**
7. Complete payment

### Step 6.3: Verify Webhook Delivery

1. Go to Stripe Dashboard (Live Mode) → **Developers** → **Webhooks**
2. Click on your production webhook endpoint
3. Click **"Recent deliveries"** tab
4. You should see your events with **200 OK** status:
   - checkout.session.completed ✅
   - payment_intent.succeeded ✅
   - customer.subscription.created ✅

If you see **red failed indicators**, there's a problem. Check server logs.

### Step 6.4: Check Production Database

SSH to server:
```bash
ssh -i ~/.ssh/tractatus_deploy ubuntu@vps-93a693da.vps.ovh.net
```

Check donations:
```bash
mongosh mongodb://localhost:27017/tractatus_prod --quiet --eval "
  db.koha_donations.find({}, {
    donor: 1,
    amount: 1,
    status: 1,
    created_at: 1
  }).sort({created_at: -1}).limit(3)
"
```

You should see your test donation with:
- Status: "completed"
- Amount: 500 (cents)
- Your email

### Step 6.5: Verify Receipt Email

Check your email inbox for:
- Subject: "Thank you for your Koha to Tractatus"
- From: Stripe or your configured email
- Contains donation amount and details

---

## Phase 7: Monitoring & Maintenance

### Daily Checks (First Week)

1. **Check Stripe Dashboard daily:**
   - Go to https://dashboard.stripe.com
   - Review **Payments** for new donations
   - Check **Webhooks** for failed deliveries

2. **Monitor server logs:**
```bash
ssh -i ~/.ssh/tractatus_deploy ubuntu@vps-93a693da.vps.ovh.net
sudo journalctl -u tractatus -f
```

3. **Check database:**
```bash
mongosh mongodb://localhost:27017/tractatus_prod --quiet --eval "
  print('Total donations:', db.koha_donations.countDocuments());
  print('Completed:', db.koha_donations.countDocuments({status: 'completed'}));
  print('Pending:', db.koha_donations.countDocuments({status: 'pending'}));
"
```

### Webhook Failure Recovery

If webhooks fail (show red in Stripe Dashboard):

1. **Check server status:**
```bash
sudo systemctl status tractatus
```

2. **Check server logs:**
```bash
sudo journalctl -u tractatus -n 100 --no-pager | grep -i "webhook\|koha"
```

3. **Verify endpoint is accessible:**
```bash
curl -X POST https://agenticgovernance.digital/api/koha/webhook \
  -H "Content-Type: application/json" \
  -d '{"test": true}'
```

4. **Retry failed webhooks:**
   - Go to Stripe Dashboard → Webhooks → Your endpoint
   - Click on failed event
   - Click **"Resend event"**

---

## Phase 8: Rollback Plan (If Things Go Wrong)

If you encounter critical issues in production:

### Emergency Rollback to Test Mode

1. **SSH to production server:**
```bash
ssh -i ~/.ssh/tractatus_deploy ubuntu@vps-93a693da.vps.ovh.net
```

2. **Restore backup .env:**
```bash
sudo cp /var/www/tractatus/.env.backup-TIMESTAMP /var/www/tractatus/.env
```

3. **Restart server:**
```bash
sudo systemctl restart tractatus
```

4. **Verify:**
```bash
curl https://agenticgovernance.digital/health
```

5. **Disable webhook in Stripe Dashboard:**
   - Go to Developers → Webhooks
   - Click on production endpoint
   - Click **"Disable endpoint"**

---

## Summary Checklist

Before declaring production ready:

- [ ] Live API keys obtained from Stripe Dashboard
- [ ] Production webhook created and secret obtained
- [ ] `.env.production` file created with live keys
- [ ] Tested locally with real card ($5 test donation)
- [ ] Test donation succeeded in Stripe Dashboard
- [ ] Webhook events delivered successfully (200 OK)
- [ ] Production .env updated on server
- [ ] Production server restarted successfully
- [ ] First production donation completed successfully
- [ ] Donation recorded in database
- [ ] Receipt email received
- [ ] Monitoring plan in place

---

## Support & Troubleshooting

**Stripe Support:**
- Dashboard: https://dashboard.stripe.com
- Documentation: https://stripe.com/docs
- Support: https://support.stripe.com

**Server Issues:**
```bash
# Check logs
sudo journalctl -u tractatus -n 100 --no-pager

# Check server status
sudo systemctl status tractatus

# Restart if needed
sudo systemctl restart tractatus
```

**Database Issues:**
```bash
# Check MongoDB status
sudo systemctl status mongod

# Check database
mongosh mongodb://localhost:27017/tractatus_prod
```

---

**Last Updated:** 2025-10-18
**Version:** 1.0
**Status:** Ready for Production Deployment

**⚠️ IMPORTANT:** Test thoroughly before announcing to users!
