# Stripe Payment Checkout - Next.js

A production-ready, enterprise-grade checkout system integrating WooCommerce and Stripe with Next.js 16.

## Features

- ✅ **Secure Payment Processing** - Stripe Payment Element with PCI compliance
- ✅ **WooCommerce Integration** - Seamless order management
- ✅ **ShipStation Integration** - Automatic order fulfillment after payment ⭐ NEW
- ✅ **Token-Based Security** - HMAC-signed tokens with replay attack prevention
- ✅ **Real-time Order Updates** - Webhook-driven payment confirmation
- ✅ **Shipment Tracking** - Automatic order status updates when shipped ⭐ NEW
- ✅ **Beautiful UI** - Sophisticated design with light/dark mode support (Tailwind CSS v4)
- ✅ **Type Safety** - Full TypeScript implementation with runtime validation
- ✅ **Form Validation** - React Hook Form with Zod schemas
- ✅ **Error Handling** - Comprehensive error boundaries and user feedback
- ✅ **Responsive Design** - Mobile-first approach
- ✅ **Rate Limiting** - Built-in API rate limiting for security
- ✅ **Environment Validation** - Runtime validation of all environment variables
- ✅ **Custom Logging** - Structured logging with environment-aware output
- ✅ **CORS Protection** - Origin validation for production environments
- ✅ **Accessibility** - ARIA live regions and screen reader support

## Architecture

### Payment Flow

1. External system generates checkout token for WooCommerce order
2. User redirected to `/checkout?token=xxx`
3. Frontend loads order details from WooCommerce
4. User fills billing/shipping information
5. Payment intent created via backend API
6. Stripe processes payment
7. Webhook confirms payment and updates order status
8. **⭐ Order automatically synced to ShipStation** (NEW)
9. User redirected to success page with order confirmation

### Fulfillment Flow ⭐ NEW

1. Order appears in ShipStation as "Awaiting Shipment"
2. Warehouse ships order and marks as shipped in ShipStation
3. ShipStation webhook notifies application
4. WooCommerce order status updated to "shipped"
5. Customer receives tracking information

### Security Features

- **HMAC Token Signing** - Prevents token tampering
- **Nonce-based Replay Protection** - One-time use tokens
- **Server-side Amount Calculation** - Client can't manipulate prices
- **Webhook Signature Verification** - Prevents spoofing
- **Idempotent Payment Creation** - Prevents duplicate charges
- **Security Headers** - XSS, clickjacking, and MIME-sniffing protection

## Setup

### Prerequisites

- Node.js 18+ 
- npm or pnpm package manager
- WooCommerce store with REST API enabled
- Stripe account (test or live mode)

### Installation

1. Clone the repository:
```bash
git clone <repository-url>
cd Stripe-Payment-Page-NextJs
```

2. Install dependencies:
```bash
npm install
# or
pnpm install
```

3. Configure environment variables:
```bash
cp .env.example .env.local
```

Edit `.env.local` with your credentials:
```env
# Stripe Keys
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_your_key
STRIPE_SECRET_KEY=sk_test_your_key
STRIPE_WEBHOOK_SECRET=whsec_your_secret

# WooCommerce
WC_BASE_URL=https://your-store.com
WC_CONSUMER_KEY=ck_your_key
WC_CONSUMER_SECRET=cs_your_secret

# ShipStation (Optional)
SHIPSTATION_API_KEY=your_api_key
SHIPSTATION_API_SECRET=your_api_secret

# Security
CHECKOUT_TOKEN_SECRET=random_32_char_minimum_secret
```

4. Start development server:
```bash
npm run dev
```

5. Open [http://localhost:3000](http://localhost:3000)

## Environment Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key (frontend) | Yes |
| `STRIPE_SECRET_KEY` | Stripe secret key (backend) | Yes |
| `STRIPE_WEBHOOK_SECRET` | Webhook signing secret | Yes |
| `WC_BASE_URL` | WooCommerce store URL | Yes |
| `WC_CONSUMER_KEY` | WooCommerce API key | Yes |
| `WC_CONSUMER_SECRET` | WooCommerce API secret | Yes |
| `SHIPSTATION_API_KEY` | ShipStation API key | No* |
| `SHIPSTATION_API_SECRET` | ShipStation API secret | No* |
| `SHIPSTATION_WEBHOOK_SECRET` | Webhook validation secret | No |
| `CHECKOUT_TOKEN_SECRET` | Random secret for token signing | Yes |
| `CHECKOUT_TOKEN_TTL_SECONDS` | Token expiry (default: 900) | No |
| `ALLOWED_ORIGINS` | CORS origins (production) | No |

*Required if using ShipStation integration

## API Routes

### `GET /api/checkout-session`
Load checkout data for an order.

**Query:** `token` (checkout token)  
**Response:** Order details with items, totals, and shipping

### `POST /api/payment-intent`
Create Stripe PaymentIntent.

**Body:** `{ token, billing_address, shipping_address }`  
**Response:** `{ client_secret, payment_intent_id }`

### `POST /api/stripe/webhook`
Handle Stripe webhook events.

**Events:** `payment_intent.succeeded`, `payment_intent.payment_failed`  
**New:** Creates order in ShipStation after successful payment

### `POST /api/shipstation/webhook` ⭐ NEW
Handle ShipStation webhook events.

**Events:** `SHIP_NOTIFY`, `ITEM_SHIPPED`  
**Action:** Updates WooCommerce order status to "shipped" with tracking info

### `GET /api/order-status`
Check order payment status.

**Query:** `token` (checkout token)  
**Response:** `{ order_id, paid, status }`

## WooCommerce Setup

1. Go to **WooCommerce → Settings → Advanced → REST API**
2. Click **Add key**
3. Set permissions to **Read/Write**
4. Copy Consumer Key and Consumer Secret to `.env.local`

## Stripe Webhook Setup

1. Go to [Stripe Dashboard → Webhooks](https://dashboard.stripe.com/webhooks)
2. Click **Add endpoint**
3. URL: `https://yourdomain.com/api/stripe/webhook`
4. Select events: `payment_intent.succeeded`, `payment_intent.payment_failed`
5. Copy webhook signing secret to `.env.local`

### Local Testing with Stripe CLI

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

Copy the webhook signing secret to `STRIPE_WEBHOOK_SECRET`.

## ShipStation Integration ⭐ NEW

### Setup

1. **Get API Credentials**:
   - Log in to ShipStation
   - Go to Account Settings → API Settings
   - Generate API Keys
   - Add to `.env.local`

2. **Configure Webhooks**:
   - ShipStation Settings → API Settings → Webhooks
   - URL: `https://yourdomain.com/api/shipstation/webhook`
   - Events: `SHIP_NOTIFY`, `ITEM_SHIPPED`

3. **Test Integration**:
   ```bash
   npm run test:shipstation
   ```

### Documentation

- **Setup Guide**: See [SHIPSTATION_SETUP.md](./SHIPSTATION_SETUP.md)
- **Integration Details**: See [SHIPSTATION_INTEGRATION.md](./SHIPSTATION_INTEGRATION.md)

### Features

- ✅ Automatic order creation after payment
- ✅ Idempotent sync (prevents duplicates)
- ✅ Graceful error handling (payment succeeds even if ShipStation fails)
- ✅ Tracking number updates via webhooks
- ✅ Custom "shipped" order status
- ✅ Full audit trail in metadata

## Testing

See [TESTING.md](./TESTING.md) for detailed testing instructions.

**Quick Test:**
1. Use Stripe test card: `4242 4242 4242 4242`
2. Any future expiry date
3. Any 3-digit CVC
4. Any postal code

## Project Structure

```
├── app/
│   ├── api/              # API routes (with rate limiting & CORS)
│   ├── checkout/         # Checkout page
│   ├── success/          # Success page
│   ├── not-found.tsx     # 404 page
│   └── layout.tsx        # Root layout with accessibility
├── components/           # React components
│   ├── ui/              # shadcn/ui components
│   └── *.tsx            # Checkout components
├── hooks/               # Custom React hooks
├── lib/
│   ├── types/           # TypeScript types
│   │   ├── api.ts
│   │   ├── checkout.ts
│   │   └── shipstation.ts  # ⭐ NEW
│   ├── env.ts           # Environment validation
│   ├── logger.ts        # Custom logging utility
│   ├── rate-limit.ts    # Rate limiting utility
│   ├── stripe.ts        # Server-side Stripe
│   ├── stripe-client.ts # Client-side Stripe
│   ├── shipstation.ts   # ShipStation API client ⭐ NEW
│   ├── woo.ts           # WooCommerce client (with validation)
│   ├── token.ts         # Token generation/verification
│   ├── security.ts      # Security utilities (with CORS)
│   ├── money.ts         # Money handling utilities
│   └── schemas.ts       # Zod validation schemas
├── scripts/
│   └── test-shipstation.ts  # ShipStation test script ⭐ NEW
└── public/              # Static assets
```

## Deployment

### Vercel (Recommended)

1. Push to GitHub
2. Import project in Vercel
3. Add environment variables
4. Deploy

### Other Platforms

Ensure Node.js 18+ is available and set environment variables in platform settings.

## Production Checklist

- [ ] Replace Stripe test keys with live keys
- [ ] Configure webhook endpoint in Stripe live mode
- [ ] Configure ShipStation API credentials ⭐ NEW
- [ ] Configure ShipStation webhook endpoint ⭐ NEW
- [ ] Test ShipStation integration with `npm run test:shipstation` ⭐ NEW
- [ ] Set `ALLOWED_ORIGINS` for CORS protection
- [ ] Test webhook delivery (Stripe & ShipStation)
- [ ] Monitor order status transitions (pending → processing → shipped)
- [ ] Set up error alerting/monitoring (include ShipStation sync failures)
- [ ] Test full checkout flow with test cards
- [ ] Review security headers (already configured)
- [ ] Verify rate limiting is working (already enabled)
- [ ] Test environment variable validation
- [ ] Review logger output in production
- [ ] Test 404 and error pages
- [ ] Run accessibility audit

## Money Handling

All amounts are stored as **integer cents** to avoid floating-point errors:
- $99.99 → 9999 cents
- Server calculates all amounts (never trust client)
- Stripe and WooCommerce totals must match exactly

## Technology Stack

- **Framework**: Next.js 16 with React 19
- **Styling**: Tailwind CSS v4 (no config file required)
- **UI Components**: shadcn/ui with Radix UI
- **Forms**: React Hook Form with Zod validation
- **Payment**: Stripe Payment Element
- **Type Safety**: TypeScript with runtime validation
- **Package Manager**: npm or pnpm

## New Features

### v3.0 - ShipStation Integration ⭐
- ✨ **ShipStation Integration**: Automatic order fulfillment after successful payment
- ✨ **Shipment Tracking**: Real-time order status updates via webhooks
- ✨ **Idempotent Sync**: Prevents duplicate orders in ShipStation
- ✨ **Graceful Degradation**: Payment succeeds even if ShipStation API fails
- ✨ **Custom Order Status**: "shipped" status with tracking metadata
- ✨ **Test Suite**: Automated testing script for ShipStation connectivity

### v2.0 - Enterprise Features
- ✨ **Environment Validation**: Automatic validation of all env vars at startup
- ✨ **Rate Limiting**: Built-in IP-based rate limiting on all API routes
- ✨ **Custom Logger**: Structured logging with environment awareness
- ✨ **CORS Protection**: Origin validation for production deployments
- ✨ **API Response Validation**: Zod schemas validate WooCommerce responses
- ✨ **Enhanced Security**: Improved nonce handling prevents replay attacks
- ✨ **Better Error Handling**: Amount mismatches trigger alerts and order holds
- ✨ **Accessibility**: ARIA live regions, skip links, and screen reader support
- ✨ **404 Page**: Custom styled not-found page
- ✨ **Dedicated Routes**: Separate /checkout route for clarity

## Support

For issues or questions:
1. Check [BACKEND_SETUP.md](./BACKEND_SETUP.md) for architecture details
2. Check [TESTING.md](./TESTING.md) for testing guide
3. Check [SHIPSTATION_INTEGRATION.md](./SHIPSTATION_INTEGRATION.md) for ShipStation details ⭐ NEW
4. Check [SHIPSTATION_SETUP.md](./SHIPSTATION_SETUP.md) for setup instructions ⭐ NEW
5. Check [IMPLEMENTATION_COMPLETE.md](./IMPLEMENTATION_COMPLETE.md) for implementation details
6. Review error logs with timestamps from custom logger

## License

MIT
