# Testing Guide

Complete testing guide for the Stripe Payment Checkout system.

## Table of Contents

- [Prerequisites](#prerequisites)
- [Test Environment Setup](#test-environment-setup)
- [Stripe Test Cards](#stripe-test-cards)
- [Testing Workflows](#testing-workflows)
- [Webhook Testing](#webhook-testing)
- [Common Issues](#common-issues)

## Prerequisites

Before testing, ensure you have:

1. ✅ Development server running (`npm run dev`)
2. ✅ `.env.local` configured with test credentials
3. ✅ WooCommerce store accessible
4. ✅ Stripe account in test mode
5. ✅ Valid checkout token from your WooCommerce system

## Test Environment Setup

### 1. Stripe Test Mode

Ensure you're using test mode keys:
- Publishable key starts with `pk_test_`
- Secret key starts with `sk_test_`
- Never use live keys (`pk_live_`, `sk_live_`) in development

### 2. WooCommerce Test Order

Create a test order in WooCommerce:
1. Log into WooCommerce admin
2. Create a new order manually or via your system
3. Set status to "Pending Payment"
4. Generate checkout token for the order ID

### 3. Generate Checkout Token

The checkout token should be generated server-side using the token utility:

```typescript
import { CheckoutToken } from "@/lib/token"

const token = CheckoutToken.generate(orderId)
// Example: eyJvcmRlcl9pZCI6MTIzNDUsImV4cCI6MTcwMjg...
```

Then redirect to: `http://localhost:3000/checkout?token={token}`

## Stripe Test Cards

### Successful Payments

| Card Number | Description |
|-------------|-------------|
| `4242 4242 4242 4242` | Visa - Always succeeds |
| `5555 5555 5555 4444` | Mastercard - Always succeeds |
| `3782 822463 10005` | American Express - Always succeeds |

### Failed Payments

| Card Number | Failure Type |
|-------------|--------------|
| `4000 0000 0000 0002` | Card declined |
| `4000 0000 0000 9995` | Insufficient funds |
| `4000 0000 0000 0069` | Expired card |
| `4000 0000 0000 0127` | Incorrect CVC |

### 3D Secure Authentication

| Card Number | 3DS Behavior |
|-------------|--------------|
| `4000 0025 0000 3155` | Requires authentication |
| `4000 0000 0000 3220` | Authentication fails |

**Note:** Use any future expiry date, any 3-digit CVC, and any postal code.

## Testing Workflows

### Workflow 1: Successful Payment

**Steps:**
1. Visit `/checkout?token={valid_token}`
2. Verify order details load correctly in right sidebar
3. Fill in contact information:
   - Email: `test@example.com`
   - Phone: `555-0100` (optional)
4. Fill in billing address:
   - Name: `John Doe`
   - Address: `123 Main St`
   - City: `San Francisco`
   - State: `CA`
   - Postal Code: `94103`
   - Country: `United States`
5. Choose shipping option:
   - ✅ Check "Use billing address for shipping"
6. Click **"Continue to Payment"**
7. Wait for payment form to load
8. Enter card details:
   - Card: `4242 4242 4242 4242`
   - Expiry: `12/34`
   - CVC: `123`
   - Postal: `12345`
9. Click **"Complete Secure Purchase"**
10. Wait for redirect to `/success?token={token}`
11. Verify payment confirmation appears
12. Check order status in WooCommerce (should be "Processing")

**Expected Result:** ✅ Payment succeeds, order status updates, success page displays

### Workflow 2: Declined Payment

**Steps:**
1. Follow steps 1-7 from Workflow 1
2. Enter declined card: `4000 0000 0000 0002`
3. Complete other fields
4. Click **"Complete Secure Purchase"**

**Expected Result:** ❌ Error toast appears, payment form stays visible, try again possible

### Workflow 3: Invalid Token

**Steps:**
1. Visit `/checkout?token=invalid_token_here`

**Expected Result:** ❌ Error page displays with message about invalid token

### Workflow 4: Expired Token

**Steps:**
1. Generate token
2. Wait 16 minutes (default TTL is 15 minutes)
3. Visit `/checkout?token={expired_token}`

**Expected Result:** ❌ Error displays: "Token expired"

### Workflow 5: Different Shipping Address

**Steps:**
1. Follow steps 1-4 from Workflow 1
2. ❌ Uncheck "Use billing address for shipping"
3. Fill shipping address with different details:
   - Name: `Jane Smith`
   - Address: `456 Oak Ave`
   - City: `Los Angeles`
   - State: `CA`
   - Postal: `90001`
4. Continue with payment
5. Verify both addresses sent to API

**Expected Result:** ✅ Both billing and shipping addresses saved to WooCommerce

### Workflow 6: Form Validation

**Test Cases:**
- Leave email blank → Error: "Please enter a valid email address"
- Enter invalid email → Error displays
- Leave required address fields blank → Errors display
- Select wrong country code → Should accept 2-letter codes only

**Expected Result:** ✅ Validation errors display inline before submission

## Webhook Testing

### Local Webhook Testing with Stripe CLI

1. **Install Stripe CLI:**
```bash
# macOS
brew install stripe/stripe-cli/stripe

# Windows
scoop install stripe

# Or download from https://stripe.com/docs/stripe-cli
```

2. **Login to Stripe:**
```bash
stripe login
```

3. **Forward webhooks to local server:**
```bash
stripe listen --forward-to localhost:3000/api/stripe/webhook
```

4. **Copy the webhook signing secret:**
```
> Ready! Your webhook signing secret is whsec_xxxxxxxxxxxxx
```

5. **Update `.env.local`:**
```env
STRIPE_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxx
```

6. **Restart dev server**

7. **Trigger test webhook:**
```bash
stripe trigger payment_intent.succeeded
```

8. **Verify in console:**
Look for `[v0] Webhook event: payment_intent.succeeded`

### Manual Webhook Testing

1. Make a test payment
2. Check Stripe Dashboard → Webhooks → Events
3. Find the `payment_intent.succeeded` event
4. Verify webhook delivered successfully (200 response)
5. Check WooCommerce order status changed to "Processing"

## Common Issues

### Issue 1: Stripe Not Loading

**Symptoms:** Payment form shows loading spinner forever

**Solutions:**
- Check `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` is set
- Verify key starts with `pk_test_`
- Check browser console for errors
- Clear browser cache

### Issue 2: Webhook Not Receiving Events

**Symptoms:** Payment succeeds but order status doesn't update

**Solutions:**
- Verify `STRIPE_WEBHOOK_SECRET` is correct
- Check webhook endpoint is publicly accessible
- Use Stripe CLI for local testing
- Check Stripe Dashboard webhook logs

### Issue 3: Token Validation Fails

**Symptoms:** "Invalid checkout token" error

**Solutions:**
- Verify `CHECKOUT_TOKEN_SECRET` matches between token generator and app
- Check token hasn't expired (15 min default)
- Ensure token format is correct (base64url encoded)

### Issue 4: WooCommerce Connection Fails

**Symptoms:** "Failed to load checkout session"

**Solutions:**
- Verify `WC_BASE_URL` is correct (no trailing slash)
- Check `WC_CONSUMER_KEY` and `WC_CONSUMER_SECRET`
- Test WooCommerce REST API directly:
```bash
curl https://your-store.com/wp-json/wc/v3/orders/123 \
  -u ck_xxx:cs_xxx
```
- Ensure order exists and status is "pending"

### Issue 5: CORS Errors

**Symptoms:** Network errors in browser console

**Solutions:**
- In development, CORS should work automatically
- In production, set `ALLOWED_ORIGINS` in `.env.local`
- Check Next.js server is running

### Issue 6: Payment Intent Already Exists

**Symptoms:** "Payment intent already exists for this order"

**Solutions:**
- This is normal for idempotency
- Existing payment intent will be reused
- If testing, create a new WooCommerce order

## Testing Checklist

Before deploying to production:

- [ ] Successful payment completes end-to-end
- [ ] Declined payment shows appropriate error
- [ ] Form validation works on all fields
- [ ] Different shipping address saves correctly
- [ ] Webhook updates order status
- [ ] Success page displays correct information
- [ ] Invalid tokens show error page
- [ ] Expired tokens are rejected
- [ ] Amount matches between order and Stripe
- [ ] Email and phone capture works
- [ ] Order summary shows correct totals
- [ ] Loading states appear during async operations
- [ ] Error boundaries catch React errors
- [ ] Toast notifications appear for errors
- [ ] Mobile responsive design works
- [ ] Dark mode (if implemented) displays correctly

## Performance Testing

### Load Times
- Checkout page should load < 2 seconds
- Payment Element should initialize < 3 seconds
- Payment processing should complete < 5 seconds
- Success page polling should confirm < 30 seconds

### Monitoring
Check browser console for:
- `[v0]` prefixed logs
- Network requests to `/api/*` endpoints
- Stripe.js loading time
- Any console errors or warnings

## Security Testing

### Test Security Features
- ✅ Token signature validation
- ✅ Token expiry enforcement
- ✅ Nonce replay prevention
- ✅ Server-side amount calculation
- ✅ Webhook signature verification
- ✅ HTTPS in production only
- ✅ No sensitive data in client

### Penetration Testing
DO NOT attempt to:
- Modify checkout token manually
- Change amounts in browser dev tools
- Replay tokens after use
- Spoof webhook requests

These should all be blocked by security measures.

## Debugging Tips

1. **Enable Verbose Logging:**
   - Check browser console (F12)
   - Check server logs (`npm run dev` output)
   - Look for `[v0]` prefixed messages

2. **Stripe Dashboard:**
   - View payment intents in real-time
   - Check webhook delivery logs
   - Review event details

3. **WooCommerce Logs:**
   - WooCommerce → Status → Logs
   - Look for REST API errors

4. **Network Tab:**
   - Open browser DevTools → Network
   - Filter by Fetch/XHR
   - Check API request/response payloads

## Support

If issues persist:
1. Review [BACKEND_SETUP.md](./BACKEND_SETUP.md) for architecture
2. Check environment variables are correctly set
3. Verify all dependencies are installed
4. Test with minimal configuration first
5. Contact support with error logs and steps to reproduce







