# 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
- ✅ **EasyShip Integration** - Automatic order fulfillment after payment
- ✅ **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
- ✅ **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 EasyShip for fulfillment
9. User redirected to success page with order confirmation

### Fulfillment Flow

1. Shipment created in EasyShip with order details
2. Warehouse ships order and marks as shipped in EasyShip
3. EasyShip webhook notifies application with tracking updates
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

# EasyShip
EASYSHIP_API_TOKEN=prod_your_api_token_here

# 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 |
| `EASYSHIP_API_TOKEN` | EasyShip API token | Yes |
| `EASYSHIP_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 |

## 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`  
Creates shipment in EasyShip after successful payment

### `POST /api/easyship/webhook`
Handle EasyShip webhook events.

**Events:** `shipment.tracking.statuschanged`, `shipment.label.created`, `shipment.label.failed`
**Action:** Updates WooCommerce order status and 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`.

## EasyShip Integration

### Setup

1. **Get API Token**:
   - Log in to [EasyShip Dashboard](https://app.easyship.com)
   - Go to Connect → New Integration → API Integration
   - Generate API token (production starts with `prod_`, sandbox with `sand_`)
   - Add to `.env.local`

2. **Configure Webhooks**:
   - Via EasyShip API or Dashboard
   - URL: `https://yourdomain.com/api/easyship/webhook`
   - Events: `shipment.tracking.statuschanged`, `shipment.label.created`, `shipment.label.failed`

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

### Features

- ✅ Automatic shipment creation after payment
- ✅ Idempotent sync (prevents duplicates)
- ✅ Graceful error handling (payment succeeds even if EasyShip 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
│   │   └── easyship.ts
│   ├── 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
│   ├── easyship.ts      # EasyShip API client
│   ├── 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-easyship.ts # EasyShip test script
└── 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 EasyShip API token
- [ ] Configure EasyShip webhook endpoint
- [ ] Test EasyShip integration with `npm run test:easyship`
- [ ] Set `ALLOWED_ORIGINS` for CORS protection
- [ ] Test webhook delivery (Stripe & EasyShip)
- [ ] Monitor order status transitions (pending → processing → shipped)
- [ ] Set up error alerting/monitoring (include EasyShip 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 - EasyShip Integration
- ✨ **EasyShip Integration**: Automatic order fulfillment after successful payment
- ✨ **Shipment Tracking**: Real-time order status updates via webhooks
- ✨ **Idempotent Sync**: Prevents duplicate shipments in EasyShip
- ✨ **Graceful Degradation**: Payment succeeds even if EasyShip API fails
- ✨ **Custom Order Status**: "shipped" status with tracking metadata
- ✨ **Test Suite**: Automated testing script for EasyShip 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 [IMPLEMENTATION_COMPLETE.md](./IMPLEMENTATION_COMPLETE.md) for implementation details
6. Review error logs with timestamps from custom logger

## License

MIT
