# Backend Setup Guide

This is an enterprise-grade checkout backend that integrates WooCommerce and Stripe.

## Architecture Principles

1. **WooCommerce owns the order** - All order data lives in WooCommerce
2. **Stripe owns the payment** - All payment processing through Stripe
3. **Webhooks own the truth** - Payment success determined by webhooks only
4. **Frontend never decides** - No client-side amount calculation or state management

## Security Features

- HMAC-signed checkout tokens (CSRF protection)
- One-time nonce usage (replay attack prevention)
- Server-side amount calculation only (tampering prevention)
- Stripe webhook signature verification (spoofing prevention)
- Idempotent payment creation (duplicate prevention)
- PCI-compliant (Stripe Payment Element)

## Environment Variables

Copy `.env.example` to `.env.local` and fill in your credentials:

```bash
cp .env.example .env.local
```

### Required Variables

- `STRIPE_SECRET_KEY` - Your Stripe secret key (sk_test_xxx or sk_live_xxx)
- `STRIPE_WEBHOOK_SECRET` - Webhook signing secret from Stripe dashboard
- `WC_BASE_URL` - Your WooCommerce site URL (https://yourstore.com)
- `WC_CONSUMER_KEY` - WooCommerce REST API consumer key
- `WC_CONSUMER_SECRET` - WooCommerce REST API consumer secret
- `CHECKOUT_TOKEN_SECRET` - Random string (min 32 chars) for token signing

## API Endpoints

### 1. GET /api/checkout-session

Load checkout data for an order.

**Query Parameters:**
- `token` - Checkout token (generated server-side)

**Response:**
```json
{
  "success": true,
  "order": {
    "id": 12345,
    "total_cents": 9999,
    "currency": "USD",
    "items": [...],
    "email": "customer@example.com"
  }
}
```

### 2. POST /api/payment-intent

Create Stripe PaymentIntent.

**Body:**
```json
{
  "token": "checkout-token",
  "billing_address": {...},
  "shipping_address": {...}
}
```

**Response:**
```json
{
  "success": true,
  "client_secret": "pi_xxx_secret_xxx",
  "payment_intent_id": "pi_xxx"
}
```

### 3. POST /api/stripe/webhook

Handle Stripe webhook events (configure in Stripe dashboard).

**Events Handled:**
- `payment_intent.succeeded` - Updates order to "processing"
- `payment_intent.payment_failed` - Logs failure

### 4. GET /api/order-status

Poll order payment status after payment.

**Query Parameters:**
- `token` - Checkout token

**Response:**
```json
{
  "success": true,
  "order_id": 12345,
  "paid": true,
  "status": "processing"
}
```

## Stripe Webhook Setup

1. Go to Stripe Dashboard → Developers → Webhooks
2. Click "Add endpoint"
3. Enter URL: `https://yourdomain.com/api/stripe/webhook`
4. Select events: `payment_intent.succeeded`, `payment_intent.payment_failed`
5. Copy webhook signing secret to `STRIPE_WEBHOOK_SECRET`

## WooCommerce Setup

1. Go to WooCommerce → Settings → Advanced → REST API
2. Click "Add key"
3. Description: "Next.js Checkout"
4. User: Admin user
5. Permissions: Read/Write
6. Copy Consumer Key and Consumer Secret

## Order Flow

1. Customer creates order in WooCommerce (status: "pending")
2. Generate checkout token for order ID
3. Customer visits checkout page with token
4. Frontend calls `/api/checkout-session` to load order
5. Frontend calls `/api/payment-intent` to create Stripe PI
6. Customer completes payment with Stripe Payment Element
7. Stripe webhook calls `/api/stripe/webhook`
8. Backend updates WooCommerce order to "processing"
9. Customer redirected to success page
10. Frontend polls `/api/order-status` to confirm payment

## Money Handling

All amounts are stored as **integer cents** to avoid floating-point errors:

- $99.99 → 9999 cents
- Never use floats for money calculations
- Server calculates all amounts (never trust frontend)
- Stripe and WooCommerce totals must match exactly

## Error Handling

All errors are logged with `[v0]` prefix for easy debugging:

```typescript
console.log('[v0] Payment completed:', orderId)
console.error('[v0] Amount mismatch:', { order, paid })
```

## Testing

Use Stripe test cards:
- Success: `4242 4242 4242 4242`
- Decline: `4000 0000 0000 0002`

## Production Checklist

- [ ] Replace test Stripe keys with live keys
- [ ] Configure webhook endpoint in live mode
- [ ] Set `ALLOWED_ORIGINS` for CORS protection
- [ ] Test webhook delivery in Stripe dashboard
- [ ] Monitor order status transitions in WooCommerce
- [ ] Set up error alerting for webhook failures

## Security Notes

- Checkout tokens expire after 15 minutes
- Nonces prevent token replay attacks
- All amounts calculated server-side only
- Webhook signatures verified before processing
- No PCI compliance needed (Stripe handles cards)
