# Stripe Sandbox Setup - Complete ✅

**Date:** 2025-10-18
**Status:** Test Mode Active | Ready for Browser Testing
**Session:** Stripe Implementation Phase

---

## Summary

The Stripe donation system for Koha is now fully configured in test mode and ready for end-to-end testing. All backend services are operational, the database is configured, and the frontend form is connected.

---

## What Was Completed

### 1. Stripe Product and Price Configuration ✅

**Product Created:**
- Name: "Tractatus Framework Support"
- ID: `prod_TFusJH4Q3br8gA`
- Description: Koha (reciprocal gift) to support the Tractatus AI Safety Framework

**Monthly Subscription Prices Created:**
- Foundation ($5 NZD/month): `price_1SJP2fGhfAwOYBrf9yrf0q8C`
- Advocate ($15 NZD/month): `price_1SJP2fGhfAwOYBrfNc6Nfjyj`
- Champion ($50 NZD/month): `price_1SJP2fGhfAwOYBrf0A62TOpf`

**Multi-Currency Support:**
- Base currency: NZD
- 10 currencies supported: USD, EUR, GBP, AUD, CAD, JPY, CHF, SGD, HKD
- Configured via Stripe's `currency_options` feature
- Exchange rates configurable in `src/config/currencies.config.js`

### 2. Environment Configuration ✅

**.env file updated with:**
```bash
STRIPE_SECRET_KEY=sk_test_51RX67k... (configured)
STRIPE_PUBLISHABLE_KEY=pk_test_51RX67k... (configured)
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
STRIPE_KOHA_WEBHOOK_SECRET=whsec_koha_dev_placeholder (needs Stripe CLI)
FRONTEND_URL=http://localhost:9000
```

### 3. Database Configuration ✅

**Fixed Index Issues:**
- Changed `stripe_payment_id` index from unique to **sparse unique**
- This allows multiple pending donations (with null payment_id) while enforcing uniqueness for completed payments
- Prevents E11000 duplicate key errors during checkout session creation

**Collections Ready:**
- `koha_donations` - Main donation records
- All indexes configured for performance
- Test data cleared for clean testing

### 4. Backend API Testing ✅

**Endpoints Verified:**
- `POST /api/koha/checkout` - Creates Stripe checkout sessions (200 OK)
- `POST /api/koha/webhook` - Webhook handler ready (needs signing secret)
- `GET /api/koha/transparency` - Public metrics endpoint

**Test Results:**
```
[KOHA] Creating checkout session: monthly donation of NZD $15 (NZD $15)
[KOHA] Checkout session created: cs_test_b1pzkYTZE7F77jcOcV1VJ5mcFiDbTpokfLtdoymCQqKHGv47JvKnPqO9Oc
POST /api/koha/checkout 200 - 1030ms
```

Both monthly subscriptions and one-time donations tested successfully via curl.

### 5. Frontend Integration ✅

**Fixed Issues:**
- i18n system now loads koha and transparency page translations correctly
- Transparency link fixed (was missing .html extension)
- Service worker cache version bumped to 1.1.4 to clear old cached JavaScript
- Donation form connected to backend API via `koha-donation.js`

**Form Features:**
- Monthly subscription tiers ($5, $15, $50)
- One-time donations with custom amounts
- Multi-currency selector (10 currencies)
- Public acknowledgement opt-in
- Anonymous donation by default
- Email validation
- Stripe Checkout redirect integration

### 6. Automated Setup Scripts Created ✅

**scripts/test-stripe-connection.js**
- Verifies Stripe API keys are working
- Lists existing products and prices
- Checks webhook endpoint configuration
- Usage: `node scripts/test-stripe-connection.js`

**scripts/setup-stripe-products.js**
- Automatically creates Tractatus product
- Creates all 3 monthly price tiers with multi-currency options
- Saves IDs to `.stripe-ids.json` for reference
- Updates needed environment variables
- Usage: `node scripts/setup-stripe-products.js`

**scripts/test-stripe-integration.js**
- Comprehensive integration test suite
- Tests monthly subscription checkout sessions
- Tests one-time donation checkout sessions
- Validates environment variables
- Verifies product and price configuration
- Usage: `node scripts/test-stripe-integration.js`

**scripts/stripe-webhook-setup.sh**
- Interactive webhook setup guide
- Checks for Stripe CLI installation
- Provides installation instructions
- Guides through webhook forwarding setup
- Usage: `./scripts/stripe-webhook-setup.sh`

### 7. Documentation Updated ✅

**KOHA_STRIPE_SETUP.md** updated with:
- Automated setup instructions (Quick Start section)
- Manual setup fallback instructions
- Current status section showing actual product/price IDs
- Multi-currency configuration guide
- Testing procedures
- Production deployment checklist

---

## Testing Instructions

### Test Donation Form (Browser)

1. **Visit:** http://localhost:9000/koha.html
2. **Select tier:** Foundation ($5), Advocate ($15), or Champion ($50)
   - OR select "One-Time" and enter custom amount
3. **Fill form:**
   - Name: (optional, defaults to Anonymous)
   - Email: test@example.com
   - Country: (optional)
4. **Submit** - Should redirect to Stripe Checkout

### Complete Payment (Stripe Test Mode)

Use Stripe test cards:
- **Success:** 4242 4242 4242 4242
- **3D Secure:** 4000 0027 6000 3184
- **Declined:** 4000 0000 0000 9995

**Card Details:**
- Expiry: Any future date (e.g., 12/25)
- CVC: Any 3 digits (e.g., 123)
- ZIP: Any 5 digits (e.g., 12345)

### Verify Checkout Session

Check server logs:
```bash
tail -f logs/server.log | grep KOHA
```

Expected output:
```
[KOHA] Creating checkout session: monthly donation of NZD $15 (NZD $15)
[KOHA] Using existing customer cus_...
[KOHA] Checkout session created: cs_test_...
POST /api/koha/checkout 200 - 1030ms
```

---

## Known Issues & Solutions

### Issue: Browser Shows "Donation system not yet active" (503 Error)

**Cause:** Service worker caching old JavaScript files

**Solution:**
1. Hard refresh: `Ctrl+Shift+R` (Windows/Linux) or `Cmd+Shift+R` (Mac)
2. OR use Incognito/Private window
3. OR manually clear service worker:
   - DevTools → Application → Service Workers → Unregister
   - DevTools → Application → Cache Storage → Delete all
   - Refresh page

**Status:** Fixed by bumping cache version to 1.1.4

### Issue: E11000 Duplicate Key Error

**Cause:** `stripe_payment_id` index was unique but not sparse

**Solution:** Changed to sparse unique index (allows multiple null values)

**Status:** ✅ Fixed

---

## Next Steps

### 1. Webhook Testing (Pending)

**Install Stripe CLI:**
```bash
# Ubuntu/Debian
curl -s https://packages.stripe.dev/api/security/keypair/stripe-cli-gpg/public | gpg --dearmor | sudo tee /usr/share/keyrings/stripe.gpg
echo 'deb [signed-by=/usr/share/keyrings/stripe.gpg] https://packages.stripe.dev/stripe-cli-debian-local stable main' | sudo tee -a /etc/apt/sources.list.d/stripe.list
sudo apt update
sudo apt install stripe

# macOS
brew install stripe/stripe-cli/stripe
```

**Set up webhook forwarding:**
```bash
# Authenticate
stripe login

# Forward webhooks to local server
stripe listen --forward-to localhost:9000/api/koha/webhook

# Copy the webhook signing secret (whsec_...)
# Update .env:
STRIPE_KOHA_WEBHOOK_SECRET=whsec_...

# Restart server
npm start

# Test webhook
stripe trigger checkout.session.completed
```

### 2. End-to-End Browser Testing

- Test donation form submission from browser
- Complete Stripe checkout with test card
- Verify redirect to success page
- Check donation record in database
- Verify webhook events are received

### 3. Production Deployment

Before going live:
- [ ] Switch to Stripe live mode
- [ ] Create production webhook endpoint
- [ ] Obtain live API keys (sk_live_, pk_live_)
- [ ] Update production .env
- [ ] Test with real card (small amount)
- [ ] Verify webhook delivery in Stripe Dashboard
- [ ] Deploy to agenticgovernance.digital

---

## Files Modified/Created

### Created
- `scripts/test-stripe-connection.js`
- `scripts/setup-stripe-products.js`
- `scripts/test-stripe-integration.js`
- `scripts/stripe-webhook-setup.sh`
- `.stripe-ids.json` (auto-generated)
- `docs/STRIPE_SANDBOX_SETUP_COMPLETE.md` (this file)

### Modified
- `.env` - Added actual Stripe product and price IDs
- `public/js/i18n-simple.js` - Added koha/transparency page mappings
- `public/koha.html` - Fixed transparency link
- `public/service-worker.js` - Bumped cache version to 1.1.4
- `public/version.json` - Updated to 1.1.4
- `docs/KOHA_STRIPE_SETUP.md` - Added automated setup instructions

### Database Changes
- Modified `stripe_payment_id` index to sparse unique in `koha_donations` collection

---

## Support & Resources

**Test Integration:**
```bash
node scripts/test-stripe-integration.js
```

**Check Server Logs:**
```bash
tail -f logs/server.log
```

**Stripe Dashboard:**
- Test Mode: https://dashboard.stripe.com/test
- Products: https://dashboard.stripe.com/test/products
- Webhooks: https://dashboard.stripe.com/test/webhooks

**Documentation:**
- Setup Guide: `docs/KOHA_STRIPE_SETUP.md`
- Stripe API Docs: https://stripe.com/docs/api
- Test Cards: https://stripe.com/docs/testing

---

## Summary

✅ Stripe sandbox is **fully operational**
✅ Backend API tested and working
✅ Frontend form connected
✅ Database configured correctly
✅ Automated setup scripts available
✅ Documentation updated

**Ready for:** Browser testing → Webhook setup → Production deployment

**Test URL:** http://localhost:9000/koha.html

---

**Last Updated:** 2025-10-18 01:50 UTC
**Session ID:** 2025-10-07-001 (continued)
**Status:** ✅ Complete - Ready for Testing
